acpgram 1.30.0 → 1.31.3

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
@@ -49,6 +49,7 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
49
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`).
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
+ - **Documentation** — `/help` and the bot's menu button open the docs page with an AI chat; the `/help` message offers to open it in a browser or as a mini app.
52
53
  - **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
53
54
  - **Project files, bypassing the agent** — `/files` lists the project files, creates a file from a message, uploads a file from your device and deletes files. The contents never go into a model request, which is how secrets (`.env`, keys) get into a project.
54
55
  - **Git: GitHub and GitLab** — `/git` connects an account with an access token, clones a repository picked from a list, and pulls, pushes or "saves and pushes" changes. The token stays with the bot and is not given to the agent; files with secrets never get into commits.
@@ -126,7 +127,7 @@ irm https://raw.githubusercontent.com/selesnow/acpgram/main/install.ps1 | iex
126
127
  curl -fsSL https://raw.githubusercontent.com/selesnow/acpgram/main/install.sh | bash
127
128
  ```
128
129
 
129
- 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.
130
+ 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 and a private `nssm.exe` (Windows service manager) if it is not found — both official builds, SHA-256 verified, no admin rights — adds the `acpgram` command to your PATH and starts the setup wizard. An existing nssm is left alone; `ACPGRAM_NO_NSSM=1` skips it. Run it again — or `acpgram update` — to update; your settings and data are kept.
130
131
 
131
132
  ```text
132
133
  acpgram start the bot
@@ -137,6 +138,8 @@ acpgram update update to the latest release
137
138
 
138
139
  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`.
139
140
 
141
+ > On Windows, `nssm` is only needed to run the bot as a service. The one-line `install.ps1` installs it automatically into `%LOCALAPPDATA%\acpgram\bin`; with `npm install -g acpgram` you need to install it yourself: `winget install --id NSSM.NSSM -e`. Running `acpgram` in a terminal does not need nssm.
142
+
140
143
  The **setup wizard** (`acpgram setup` / `npm run setup`, safe to re-run — current values are suggested):
141
144
 
142
145
  1. bot token — checked right away with `getMe`;
@@ -153,7 +156,7 @@ Autostart with the system and restart on failure — one command:
153
156
 
154
157
  | OS | How | Command |
155
158
  |---|---|---|
156
- | 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` |
159
+ | Windows | Windows service via [nssm](https://nssm.cc) (the Windows installer already puts a private `nssm.exe` into `%LOCALAPPDATA%\acpgram\bin`; for an npm install use `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` |
157
160
  | Linux | `systemd --user` (to keep it running without a login session: `sudo loginctl enable-linger $USER`) | `npm run service:install` |
158
161
  | macOS | LaunchAgent (`launchd`) | `npm run service:install` |
159
162
 
@@ -182,6 +185,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
182
185
  | Command | Who | What |
183
186
  |---|---|---|
184
187
  | `/start` | everyone | welcome screen: engine, model, access level, project |
188
+ | `/help` | everyone | docs with an AI chat: link and mini app |
185
189
  | `/project [name or path]` | everyone | choose the working folder |
186
190
  | `/engine [gemini, claude, agy, codex, opencode]` | everyone | choose the engine |
187
191
  | `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
package/README.ru.md CHANGED
@@ -49,6 +49,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
49
49
  - **Режим «диалоги» (темы)**: если боту включены темы в личном чате (@BotFather), каждая тема чата — отдельный диалог с агентом со своим проектом, движком и историей. Можно работать в нескольких темах одновременно, а вернувшись в тему позже — продолжить с того же места: сессия агента возобновляется сама. `/new` создаёт новую тему, название ей даёт агент по первому ответу (с коротким именем проекта в начале); General работает как обычный диалог, а `/project` в нём показывает диалоги выбранного проекта кнопками, открывающими тему. Тема закреплена за своим проектом. Команда, отправленная из общего списка чатов, а не изнутри темы (Telegram сам заводит под такое сообщение новую тему), выполняется в General, а пустая тема удаляется. Режим каждый выбирает сам: `/topics` — «Диалоги» или «Один чат». Одновременно у сотрудника работает до `MAX_AGENTS_PER_USER` агентов (2), у администратора до `ADMIN_MAX_AGENTS` (4); если места нет, выгружается самый давний простаивающий агент этого же пользователя — его диалог продолжится, когда пользователь в него вернётся.
50
50
  - **Язык**: бот говорит с пользователем на языке его Telegram (`ru`, `uk` или `en`, для остальных — `DEFAULT_LANG`, по умолчанию английский). Сменить язык можно командой `/language`: выбор важнее языка Telegram. Команды `acpgram` в терминале (мастер настройки, служба, обновление, справка) говорят на языке системы: русский, украинский, в остальных случаях английский; на Windows берётся язык интерфейса системы, а не региональные настройки.
51
51
  - **Экран `/start`** с кнопками: проект, движок, модель, новая сессия, прошлые сессии, завершение сессии (у администратора — сотрудники, приглашение, активные сессии).
52
+ - **Документация**: команда `/help` и кнопка меню бота открывают страницу справки с ИИ-чатом; в сообщении `/help` можно открыть её в браузере или мини-приложением.
52
53
  - **Выбор проекта** (`/project`): агент запускается в папке выбранного проекта — кнопками, поиском по названию или путём (`/project C:\my-app`, `/project ~/projects/web`). Вверху — кнопки «🕘» с последними проектами пользователя. Выбор запоминается для каждого пользователя.
53
54
  - с `PROJECTS_ROOT` (командный сервер, например `C:\scripts`) — только папки внутри корня;
54
55
  - с `PROJECTS_ROOT` и `USER_WORKSPACES=1` (личные пространства) — у каждого сотрудника своя папка в корне, чужие папки он не видит и выбрать не может; новый проект создаётся кнопкой «➕ Новый проект» (см. «Личные пространства»);
@@ -64,6 +65,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
64
65
  | Команда | Для кого | Действие |
65
66
  |---|---|---|
66
67
  | `/start` | все | приветствие, движок, модель, уровень доступа, текущий проект |
68
+ | `/help` | все | документация с ИИ-чатом: ссылка и мини-приложение |
67
69
  | `/project [название или путь]` | все | выбор проекта кнопками или поиском по названию |
68
70
  | `/engine [gemini, claude, agy, codex, opencode]` | все | выбор движка кнопками или по названию |
69
71
  | `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
@@ -244,7 +246,7 @@ irm https://raw.githubusercontent.com/selesnow/acpgram/main/install.ps1 | iex
244
246
  curl -fsSL https://raw.githubusercontent.com/selesnow/acpgram/main/install.sh | bash
245
247
  ```
246
248
 
247
- Установщик скачивает последний [релиз](https://github.com/selesnow/acpgram/releases) (с проверкой контрольной суммы) в `%LOCALAPPDATA%\acpgram` или `~/.local/share/acpgram`, при необходимости ставит приватный Node.js 24 (официальная сборка, с проверкой контрольной суммы, без прав администратора), добавляет команду `acpgram` в PATH и запускает мастер настройки. Повторный запуск или `acpgram update` — обновление; настройки и данные сохраняются. Команды: `acpgram` (запуск), `acpgram setup`, `acpgram service install | restart | stop | status | uninstall`, `acpgram update`.
249
+ Установщик скачивает последний [релиз](https://github.com/selesnow/acpgram/releases) (с проверкой контрольной суммы) в `%LOCALAPPDATA%\acpgram` или `~/.local/share/acpgram`, при необходимости ставит приватный Node.js 24 и приватный `nssm.exe` (менеджер служб Windows; обе сборки официальные, с проверкой SHA-256, без прав администратора), добавляет команду `acpgram` в PATH и запускает мастер настройки. Уже установленный nssm не перезаписывается; `ACPGRAM_NO_NSSM=1` отключает его установку. Повторный запуск или `acpgram update` — обновление; настройки и данные сохраняются. Команды: `acpgram` (запуск), `acpgram setup`, `acpgram service install | restart | stop | status | uninstall`, `acpgram update`.
248
250
 
249
251
  Два способа, выбирайте под машину:
250
252
 
@@ -290,11 +292,13 @@ npm start # первый запуск без .env сам открое
290
292
 
291
293
  Вручную: скопировать `.env.example` в `.env`, заполнить и запустить `npm start`.
292
294
 
295
+ > `nssm` нужен только для запуска как служба Windows. Однострочный установщик (`install.ps1`) ставит его автоматически в `%LOCALAPPDATA%\acpgram\bin`; при установке через `npm install -g acpgram` его нужно установить самостоятельно: `winget install --id NSSM.NSSM -e`. Для обычного запуска в консоли `nssm` не нужен.
296
+
293
297
  **Служба одной командой** — автозапуск с системой и перезапуск при сбое:
294
298
 
295
299
  | ОС | Как | Команда |
296
300
  |---|---|---|
297
- | Windows | служба через [nssm](https://nssm.cc) (`winget install --id NSSM.NSSM -e`), терминал от имени администратора; мастер предложит запускать службу от вашей учётной записи (там авторизованы агенты) | `npm run service:install` |
301
+ | Windows | служба через [nssm](https://nssm.cc) (установщик Windows уже кладёт приватный `nssm.exe` в `%LOCALAPPDATA%\acpgram\bin`; при установке из npm — `winget install --id NSSM.NSSM -e`), терминал от имени администратора; мастер предложит запускать службу от вашей учётной записи (там авторизованы агенты) | `npm run service:install` |
298
302
  | Linux | `systemd --user` (для работы без входа в систему: `sudo loginctl enable-linger $USER`) | `npm run service:install` |
299
303
  | macOS | LaunchAgent (`launchd`) | `npm run service:install` |
300
304
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.30.0",
3
+ "version": "1.31.3",
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/bot.mjs CHANGED
@@ -27,7 +27,7 @@ import { createAlbumBuffer } from './albums.mjs';
27
27
  import { dropQueue, enqueue, onAskCallback, onPermissionCallback, onQueueCallback, runTurn } from './turn.mjs';
28
28
  import { nearCommand, quoteOf, unsupportedKind } from './incoming.mjs';
29
29
  import { onWidgetQuery } from './widgetsUi.mjs';
30
- import { startView } from './ui.mjs';
30
+ import { DOCS_URL, docsMenuButton, helpMarkup, startView } from './ui.mjs';
31
31
 
32
32
  if (!process.env.TELEGRAM_BOT_TOKEN || !ADMIN_ID) {
33
33
  console.error('Нужны TELEGRAM_BOT_TOKEN и ALLOWED_USER_ID (см. .env)');
@@ -56,6 +56,11 @@ const sendStart = (st) => {
56
56
  return sendRich(st.to, startView({ level: levelLabel(st.userId), project: userPath(st.userId, st.project, lang), engine: engineOf(st).label, model: modelLabel(st), isAdmin: admin, note: admin ? null : welcomeNote(lang), topics, lang })).catch((e) => log('start:', e.message));
57
57
  };
58
58
 
59
+ function helpCommand(st) {
60
+ const lang = langOf(st.userId);
61
+ return say(st.to, t('help.text', lang, { url: DOCS_URL }), { reply_markup: helpMarkup(lang) });
62
+ }
63
+
59
64
  /** Кнопка «⏹ Остановить» под сообщениями «запрос ещё выполняется» — вместо набора /stop. */
60
65
  const stopMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.stop', lang), callback_data: 'ui:stop' }]] });
61
66
  /** Кнопка «Сессии» — вместо набора /sessions. */
@@ -132,6 +137,7 @@ const COMMANDS = [
132
137
  { name: 'close', aliases: ['exit'], menu: true, button: true, run: closeCommand },
133
138
  { name: 'topics', menu: () => topicsSupport.enabled, button: true, run: (st) => handleTopics(st) }, // в меню — если у бота включены темы
134
139
  { name: 'language', aliases: ['lang'], menu: true, button: true, run: languageCommand },
140
+ { name: 'help', menu: true, run: helpCommand },
135
141
  { name: 'start', menu: true, run: (st) => sendStart(st) },
136
142
  ];
137
143
 
@@ -268,6 +274,7 @@ async function setupCommands() {
268
274
  await tg('setMyCommands', { scope: { type: 'default' }, language_code: code, commands: menuFor(code, false) });
269
275
  await tg('setMyCommands', { scope: { type: 'chat', chat_id: ADMIN_ID }, language_code: code, commands: menuFor(code, true) });
270
276
  }
277
+ await tg('setChatMenuButton', { menu_button: docsMenuButton() });
271
278
  }
272
279
 
273
280
  async function handleUpdate(u) {
@@ -466,7 +473,7 @@ async function main() {
466
473
  ? `темы в личном чате включены (режим «диалоги», /topics)${topicsSupport.usersCreate ? '' : ' — пользователи не могут создавать темы сами, только через /new'}`
467
474
  : 'темы в личном чате выключены — режим «диалоги» недоступен',
468
475
  );
469
- await setupCommands().catch((e) => log('setMyCommands:', e.message));
476
+ await setupCommands().catch((e) => log('настройка меню:', e.message));
470
477
  // пропускаем накопившиеся до запуска обновления
471
478
  const old = await tg('getUpdates', { offset: -1, timeout: 0 });
472
479
  let offset = old.length ? old[old.length - 1].update_id + 1 : 0;
package/src/i18n.mjs CHANGED
@@ -99,6 +99,7 @@ const M = {
99
99
  'menu.close': { en: 'Close the session and free the slot', ru: 'Закрыть сессию и освободить слот', uk: 'Закрити сесію та звільнити слот' },
100
100
  'menu.language': { en: 'Choose the interface language', ru: 'Выбрать язык интерфейса', uk: 'Обрати мову інтерфейсу' },
101
101
  'menu.start': { en: 'Welcome and the current project', ru: 'Приветствие и текущий проект', uk: 'Привітання та поточний проєкт' },
102
+ 'menu.help': { en: 'Documentation with AI chat', ru: 'Документация с ИИ-чатом', uk: 'Документація з AI-чатом' },
102
103
  'menu.active': { en: 'Active sessions: who holds the slots', ru: 'Активные сессии: кто занимает слоты', uk: 'Активні сесії: хто займає слоти' },
103
104
  'menu.users': { en: 'Users with access: levels and revocation', ru: 'Сотрудники с доступом: уровни и отзыв', uk: 'Співробітники з доступом: рівні та відкликання' },
104
105
  'menu.usage': { en: 'Usage: requests and tokens by user', ru: 'Расход: запросы и токены по сотрудникам', uk: 'Витрати: запити й токени по співробітниках' },
@@ -130,6 +131,10 @@ const M = {
130
131
  'help.active': { en: '/active — active sessions', ru: '/active — активные сессии', uk: '/active — активні сесії' },
131
132
  'help.usage': { en: '/usage — requests and tokens by user', ru: '/usage — запросы и токены по сотрудникам', uk: '/usage — запити й токени по співробітниках' },
132
133
  'help.invite': { en: '/invite — invite a user', ru: '/invite — пригласить сотрудника', uk: '/invite — запросити співробітника' },
134
+ 'help.help': { en: '/help — full documentation with an AI chat', ru: '/help — полная документация с ИИ-чатом', uk: '/help — повна документація з AI-чатом' },
135
+ 'help.text': { en: '📖 Full documentation with an AI chat: {url}\n\nAsk a question and get an answer with links to the right section.', ru: '📖 Полная документация с ИИ-чатом: {url}\n\nЗадайте вопрос — ответ придёт со ссылкой на нужный раздел.', uk: '📖 Повна документація з AI-чатом: {url}\n\nЗадайте запитання — відповідь буде з посиланням на потрібний розділ.' },
136
+ 'help.btn.browser': { en: 'Open in browser', ru: 'Открыть в браузере', uk: 'Відкрити у браузері' },
137
+ 'help.btn.app': { en: 'Open mini app', ru: 'Открыть мини-приложение', uk: 'Відкрити мінізастосунок' },
133
138
 
134
139
  // ---------- уровни доступа ----------
135
140
  'level.read.label': { en: 'Read-only', ru: 'Чтение', uk: 'Читання' },
package/src/service.mjs CHANGED
@@ -146,10 +146,12 @@ const run = (cmd, args, { dry = false, secretAt = -1, quiet = false, timeout = 3
146
146
 
147
147
  const WINGET_LINKS = process.env.LOCALAPPDATA ? [join(process.env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links')] : [];
148
148
 
149
- /** nssm: NSSM_PATH, затем PATH (поиск средствами Node — `where` портит пути с кириллицей), затем ссылки WinGet. */
150
- function findNssm() {
151
- if (process.env.NSSM_PATH && existsSync(process.env.NSSM_PATH)) return process.env.NSSM_PATH;
152
- return findOnPath('nssm', { exists: existsSync, exts: ['.exe'], extra: WINGET_LINKS });
149
+ /** nssm: NSSM_PATH, каталог установки bin\, затем PATH (поиск средствами Node — `where` портит пути с кириллицей) и ссылки WinGet. */
150
+ export function findNssm({ env = process.env, homeDir = HOME_DIR, extra = WINGET_LINKS } = {}) {
151
+ if (env.NSSM_PATH && existsSync(env.NSSM_PATH)) return env.NSSM_PATH;
152
+ const privateNssm = join(homeDir, 'bin', 'nssm.exe');
153
+ if (existsSync(privateNssm)) return privateNssm;
154
+ return findOnPath('nssm', { exists: existsSync, exts: ['.exe'], pathVar: env.PATH ?? env.Path ?? '', extra });
153
155
  }
154
156
 
155
157
  const isWinAdmin = () => spawnSync('net', ['session'], { windowsHide: true, stdio: 'ignore' }).status === 0;
package/src/ui.mjs CHANGED
@@ -4,6 +4,14 @@ import { DEFAULT_LANG, LOCALES, plural, t } from './i18n.mjs';
4
4
  import { RICH_LIMIT, balanceMarkdown, escHtml } from './telegram.mjs';
5
5
  import { splitCode } from './files.mjs';
6
6
 
7
+ export const DOCS_URL = 'https://alexey-seleznev.pro/acpgram/docs/';
8
+
9
+ export const helpMarkup = (lang = DEFAULT_LANG) => ({
10
+ inline_keyboard: [[{ text: t('help.btn.browser', lang), url: DOCS_URL }, { text: t('help.btn.app', lang), web_app: { url: DOCS_URL } }]],
11
+ });
12
+
13
+ export const docsMenuButton = () => ({ type: 'web_app', text: '📖 Docs', web_app: { url: DOCS_URL } });
14
+
7
15
  // Rich-разметка Telegram превращает теги <tg-button> в настоящие кнопки с callback_data — в любом месте текста,
8
16
  // в любом регистре, и без <tg-button-row>. Текст агента (а в него попадает содержимое файлов и веб-страниц) не должен
9
17
  // уметь рисовать кнопки бота: иначе нажатие «Продолжить» в ответе могло бы выполнить adm:… от имени администратора.
@@ -739,6 +747,7 @@ const button = (text, data) => `<tg-button type="callback_data" data="${data}">$
739
747
  export function startView({ level, project, engine, model, isAdmin, note, topics = null, lang = DEFAULT_LANG }) {
740
748
  const cmd = (key) => t(`help.${key}`, lang);
741
749
  const commands = [
750
+ cmd('help'),
742
751
  cmd('project'),
743
752
  cmd('files'),
744
753
  cmd('git'),
package/src/winsvc.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  // • значения состояний (RUNNING, STOP_PENDING…) и формат «число (0xHEX)» зашиты в sc.exe;
8
8
  // • ключи и значения реестра (DeleteFlag), столбцы CSV tasklist.
9
9
  // Текст вывода используется только для показа пользователю.
10
- import { win32 } from 'node:path';
10
+ import { join, win32 } from 'node:path';
11
11
  import { tc } from './cli-i18n.mjs';
12
12
 
13
13
  /** Код Windows «служба не существует» (ERROR_SERVICE_DOES_NOT_EXIST) — его возвращает sc.exe как код выхода. */
@@ -116,9 +116,14 @@ export const parseOemCp = (output) => Number(/OEMCP\s+REG_SZ\s+(\d+)/.exec(outpu
116
116
  * @param {{pathVar?: string, exts?: string[], exists: (p: string) => boolean, extra?: string[]}} o
117
117
  */
118
118
  export function findOnPath(cmd, { pathVar = process.env.PATH ?? process.env.Path ?? '', exts = ['.exe', '.cmd', '.bat'], exists, extra = [] } = {}) {
119
- const dirs = [...pathVar.split(';').map((d) => d.trim().replace(/^"|"$/g, '')).filter(Boolean), ...extra];
119
+ const windowsStyle = /^[A-Za-z]:[\\/]/.test(pathVar) || pathVar.includes('\\') || pathVar.includes(';');
120
+ const pathJoin = windowsStyle ? win32.join : join;
121
+ const dirs = [...pathVar.split(windowsStyle ? ';' : ':').map((d) => d.trim().replace(/^"|"$/g, '')).filter(Boolean), ...extra];
120
122
  // имя уже с расширением («gemini.cmd», «codex-acp.cmd») — проверяем как есть, иначе получилось бы «codex-acp.cmd.cmd»
121
123
  const hasExt = exts.some((e) => cmd.toLowerCase().endsWith(e));
122
- for (const dir of dirs) for (const ext of hasExt ? [''] : exts) if (exists(win32.join(dir, cmd + ext))) return win32.join(dir, cmd + ext);
124
+ for (const dir of dirs) for (const ext of hasExt ? [''] : exts) {
125
+ const file = pathJoin(dir, cmd + ext);
126
+ if (exists(file)) return file;
127
+ }
123
128
  return null;
124
129
  }