acpgram 1.20.2 → 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 +14 -0
- package/README.ru.md +14 -0
- package/package.json +1 -1
- package/src/admin.mjs +14 -5
- package/src/asks.mjs +107 -0
- package/src/bot.mjs +66 -14
- package/src/db.mjs +8 -0
- package/src/diff.mjs +81 -0
- package/src/files.mjs +7 -1
- package/src/i18n.mjs +36 -0
- package/src/incoming.mjs +44 -0
- package/src/modelUi.mjs +59 -14
- package/src/sessionsUi.mjs +87 -32
- package/src/state.mjs +11 -1
- package/src/telegram.mjs +3 -0
- package/src/tools.mjs +12 -0
- package/src/turn.mjs +92 -9
- package/src/ui.mjs +44 -3
- package/src/widgetHost.mjs +60 -0
- package/src/widgets.mjs +150 -0
- package/src/widgetsUi.mjs +43 -0
package/README.md
CHANGED
|
@@ -38,6 +38,12 @@ 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
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`).
|
|
@@ -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
|
|
|
@@ -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
|
@@ -37,6 +37,12 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
37
37
|
- как пошёл ответ — последний шаг и сам ответ.
|
|
38
38
|
- **Итоговый ответ** в rich-форматировании: заголовки, списки, таблицы, блоки кода. В конце свёрнутый блок «Ход работы · N шагов» со всеми шагами и подвал: движок, реальная модель, уровень рассуждений, токены, стоимость (Claude Code и OpenCode), проект и время ответа — например `🤖 Claude · claude-haiku-5-5 · 🔢 36.8k ток. · 💲0.0046 · 📁 проект · ⏱ 4 с`. Если Telegram отклонит разметку, ответ уходит обычным текстом.
|
|
39
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
|
|
|
@@ -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 права сотрудников на движки и модели, каталоги моделей, применение выбора к сессии
|
package/package.json
CHANGED
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; // повторный запрос доступа от одного человека — не чаще раза в час
|
|
@@ -80,8 +80,8 @@ export async function adminCommand(chatId, command) {
|
|
|
80
80
|
reply_markup: { inline_keyboard: LEVEL_KEYS.map((key) => [{ text: `${levelName(key, al)} — ${levelHint(key, al)}`, callback_data: `adm:i:${key}` }]) },
|
|
81
81
|
});
|
|
82
82
|
}
|
|
83
|
-
if (command === '/active' || command === '/users') {
|
|
84
|
-
const v = command === '/active' ? activeView() : usersView();
|
|
83
|
+
if (command === '/active' || command === '/users' || command === '/usage') {
|
|
84
|
+
const v = command === '/active' ? activeView() : command === '/usage' ? usageScreen(1) : usersView();
|
|
85
85
|
return say(chatId, v.text, { reply_markup: v.markup });
|
|
86
86
|
}
|
|
87
87
|
}
|
|
@@ -103,6 +103,10 @@ const ownerName = (id) => (id === ADMIN_ID ? t('active.owner', adminLang()) : db
|
|
|
103
103
|
/** Активные сессии: кто занимает слоты, с кнопками точечного завершения (для сотрудников). */
|
|
104
104
|
const activeView = () => activeSessionsView({ sessions: activeSessions(), adminId: ADMIN_ID, maxAgents: MAX_AGENTS, nameOf: ownerName, projectOf: (p) => showPath(p, adminLang()), lang: adminLang() });
|
|
105
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
|
+
|
|
106
110
|
/** Движки сотрудника для карточки: все движки реестра, отметка выданных. */
|
|
107
111
|
const engineList = (userId) => {
|
|
108
112
|
const granted = grantedEngines(userId);
|
|
@@ -145,7 +149,7 @@ export async function onAdminCallback(cb) {
|
|
|
145
149
|
const chatId = cb.message?.chat?.id;
|
|
146
150
|
const messageId = cb.message?.message_id;
|
|
147
151
|
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text } : {}) }).catch(() => {});
|
|
148
|
-
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));
|
|
149
153
|
const id = Number(a);
|
|
150
154
|
|
|
151
155
|
// ссылка-приглашение
|
|
@@ -192,6 +196,11 @@ export async function onAdminCallback(cb) {
|
|
|
192
196
|
const v = activeView();
|
|
193
197
|
return edit(v.text, v.markup);
|
|
194
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
|
+
}
|
|
195
204
|
const user = db.getUser(id);
|
|
196
205
|
if (!user || user.status !== 'active') {
|
|
197
206
|
await ack(t('adm.ackNoUser', al));
|
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
|
+
}
|
package/src/bot.mjs
CHANGED
|
@@ -19,7 +19,9 @@ import { downloadFile, sendRich, tg } from './telegram.mjs';
|
|
|
19
19
|
import { MAX_FILE_BYTES, IMAGE_BLOCK_MAX, cleanupFiles, describeAttachment, isImageMime, saveUpload, uploadsDir } from './files.mjs';
|
|
20
20
|
import { archiveKind, extractArchiveAsync } from './archive.mjs';
|
|
21
21
|
import { createAlbumBuffer } from './albums.mjs';
|
|
22
|
-
import { onPermissionCallback, runTurn } from './turn.mjs';
|
|
22
|
+
import { dropQueue, enqueue, onAskCallback, onPermissionCallback, onQueueCallback, runTurn } from './turn.mjs';
|
|
23
|
+
import { nearCommand, quoteOf, unsupportedKind } from './incoming.mjs';
|
|
24
|
+
import { onWidgetQuery } from './widgetsUi.mjs';
|
|
23
25
|
import { startView } from './ui.mjs';
|
|
24
26
|
|
|
25
27
|
if (!process.env.TELEGRAM_BOT_TOKEN || !ADMIN_ID) {
|
|
@@ -49,7 +51,12 @@ const sendStart = (st) => {
|
|
|
49
51
|
return sendRich(st.to, startView({ level: levelLabel(st.userId), project: showPath(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));
|
|
50
52
|
};
|
|
51
53
|
|
|
52
|
-
/**
|
|
54
|
+
/** Кнопка «⏹ Остановить» под сообщениями «запрос ещё выполняется» — вместо набора /stop. */
|
|
55
|
+
const stopMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.stop', lang), callback_data: 'ui:stop' }]] });
|
|
56
|
+
/** Кнопка «Сессии» — вместо набора /sessions. */
|
|
57
|
+
const sessionsMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.sessions', lang), callback_data: 'ui:sessions' }]] });
|
|
58
|
+
|
|
59
|
+
/** Кнопки экрана /start и служебных сообщений (ui:<команда>) работают как соответствующие команды. */
|
|
53
60
|
async function onUiCallback(st, cb) {
|
|
54
61
|
const name = (cb.data || '').slice('ui:'.length);
|
|
55
62
|
await tg('answerCallbackQuery', { callback_query_id: cb.id }).catch(() => {});
|
|
@@ -77,7 +84,8 @@ function languageCommand(st, arg) {
|
|
|
77
84
|
}
|
|
78
85
|
|
|
79
86
|
function stopCommand(st) {
|
|
80
|
-
|
|
87
|
+
const queued = dropQueue(st); // «стоп» отменяет и сообщение, которое ждало своей очереди
|
|
88
|
+
if (!st.busy) return queued ? undefined : say(st.to, t('stop.none', langOf(st.userId)));
|
|
81
89
|
st.agent?.cancel();
|
|
82
90
|
dropPermissions(st);
|
|
83
91
|
}
|
|
@@ -85,13 +93,13 @@ function stopCommand(st) {
|
|
|
85
93
|
function closeCommand(st) {
|
|
86
94
|
const lang = langOf(st.userId);
|
|
87
95
|
if (!closeSession(st, 'close')) return say(st.to, t('close.none', lang));
|
|
88
|
-
return say(st.to, t('close.done', lang, { slot: isAdmin(st.userId) ? '' : t('close.slot', lang) }));
|
|
96
|
+
return say(st.to, t('close.done', lang, { slot: isAdmin(st.userId) ? '' : t('close.slot', lang) }), { reply_markup: sessionsMarkup(lang) });
|
|
89
97
|
}
|
|
90
98
|
|
|
91
99
|
function newCommand(st) {
|
|
92
100
|
const lang = langOf(st.userId);
|
|
93
101
|
if (topicsOn(st.userId)) return newTopic(st); // режим «диалоги»: новый диалог — новая тема, текущий остаётся как есть
|
|
94
|
-
if (st.busy) return say(st.to, t('busy.stop', lang));
|
|
102
|
+
if (st.busy) return say(st.to, t('busy.stop', lang), { reply_markup: stopMarkup(lang) });
|
|
95
103
|
endAgent(st, 'new');
|
|
96
104
|
return say(st.to, t('new.done', lang, { engine: engineOf(st).label, project: showPath(st.project, lang) }));
|
|
97
105
|
}
|
|
@@ -107,12 +115,13 @@ const COMMANDS = [
|
|
|
107
115
|
{ name: 'active', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/active') },
|
|
108
116
|
{ name: 'users', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/users') },
|
|
109
117
|
{ name: 'invite', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/invite') },
|
|
118
|
+
{ name: 'usage', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/usage') },
|
|
110
119
|
{ name: 'project', menu: true, button: true, run: (st, arg) => handleProject(st, arg) },
|
|
111
120
|
{ name: 'engine', menu: true, button: true, run: (st, arg) => handleEngine(st, arg) },
|
|
112
121
|
{ name: 'model', menu: true, button: true, run: (st, arg) => handleModel(st, arg) },
|
|
113
122
|
{ name: 'new', menu: true, button: true, run: newCommand },
|
|
114
123
|
{ name: 'sessions', menu: true, button: true, run: (st) => handleSessions(st) },
|
|
115
|
-
{ name: 'stop', menu: true, run: stopCommand },
|
|
124
|
+
{ name: 'stop', menu: true, button: true, run: stopCommand },
|
|
116
125
|
{ name: 'close', aliases: ['exit'], menu: true, button: true, run: closeCommand },
|
|
117
126
|
{ name: 'topics', menu: () => topicsSupport.enabled, button: true, run: (st) => handleTopics(st) }, // в меню — если у бота включены темы
|
|
118
127
|
{ name: 'language', aliases: ['lang'], menu: true, button: true, run: languageCommand },
|
|
@@ -122,8 +131,16 @@ const COMMANDS = [
|
|
|
122
131
|
/** Имена всех команд бота с псевдонимами: только они переносятся из темы, созданной Telegram, в General. */
|
|
123
132
|
const BOT_COMMANDS = new Set(COMMANDS.flatMap((c) => [c.name, ...(c.aliases ?? [])]));
|
|
124
133
|
|
|
125
|
-
/**
|
|
126
|
-
|
|
134
|
+
/** Запрос агенту: если диалог занят — в очередь (уйдёт следующим), иначе сразу. */
|
|
135
|
+
const sendToAgent = (st, text, opts = {}) => (st.busy ? enqueue(st, text, opts) : runTurn(st, text, opts));
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Текст пользователя: команды или запрос к агенту. Неизвестная команда («/что-то») уходит агенту как обычный запрос —
|
|
139
|
+
* у агентов есть свои команды («/compact»); но если она на одну правку отличается от команды бота и агент такой
|
|
140
|
+
* команды не объявлял, это, скорее всего, опечатка: спрашиваем, а не тратим запрос.
|
|
141
|
+
* @param {{quote?: string|null}} [opts] quote — фрагмент прошлого сообщения, на который отвечает пользователь
|
|
142
|
+
*/
|
|
143
|
+
async function handleText(st, text, { quote = null } = {}) {
|
|
127
144
|
const m = /^\/(\w+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(text);
|
|
128
145
|
const name = m?.[1]?.toLowerCase();
|
|
129
146
|
const command = name ? COMMANDS.find((c) => c.name === name || c.aliases?.includes(name)) : null;
|
|
@@ -132,8 +149,26 @@ async function handleText(st, text) {
|
|
|
132
149
|
if (command.admin && !isAdmin(st.userId)) return say(st.to, t('admin.only', lang));
|
|
133
150
|
return command.run(st, m[2]);
|
|
134
151
|
}
|
|
135
|
-
if (
|
|
136
|
-
|
|
152
|
+
if (name && !st.agent?.commands?.has(name)) {
|
|
153
|
+
const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
|
|
154
|
+
if (guess) {
|
|
155
|
+
st.rawCommand = text; // «Отправить агенту как есть» (cmd:raw)
|
|
156
|
+
return say(st.to, t('cmd.typo', lang, { cmd: name, guess }), {
|
|
157
|
+
reply_markup: { inline_keyboard: [[{ text: `/${guess}`, callback_data: `ui:${guess}` }], [{ text: t('cmd.sendAsIs', lang), callback_data: 'cmd:raw' }]] },
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return sendToAgent(st, text, { quote });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Кнопка «Отправить агенту как есть» под вопросом об опечатке в команде. */
|
|
165
|
+
async function onRawCommandCallback(st, cb) {
|
|
166
|
+
const text = st.rawCommand;
|
|
167
|
+
st.rawCommand = null;
|
|
168
|
+
if (!text) return tg('answerCallbackQuery', { callback_query_id: cb.id, text: t('cmd.stale', langOf(st.userId)) }).catch(() => {});
|
|
169
|
+
await tg('answerCallbackQuery', { callback_query_id: cb.id }).catch(() => {});
|
|
170
|
+
await tg('editMessageReplyMarkup', { chat_id: cb.message?.chat?.id ?? st.chatId, message_id: cb.message?.message_id, reply_markup: { inline_keyboard: [] } }).catch(() => {});
|
|
171
|
+
return sendToAgent(st, text);
|
|
137
172
|
}
|
|
138
173
|
|
|
139
174
|
/**
|
|
@@ -182,12 +217,12 @@ async function receiveFile(st, meta, lang) {
|
|
|
182
217
|
*/
|
|
183
218
|
async function processAttachments(st, msgs) {
|
|
184
219
|
const lang = langOf(st.userId);
|
|
185
|
-
if (st.busy) return say(st.to, t('busy.running', lang));
|
|
220
|
+
if (st.busy) return say(st.to, t('busy.running', lang), { reply_markup: stopMarkup(lang) });
|
|
186
221
|
const received = await Promise.all(msgs.map((m) => describeAttachment(m)).filter(Boolean).map((meta) => receiveFile(st, meta, lang)));
|
|
187
222
|
const files = received.filter(Boolean);
|
|
188
223
|
if (!files.length) return;
|
|
189
224
|
// пока качался альбом, пользователь мог отправить текст и занять агента
|
|
190
|
-
if (st.busy) return say(st.to, t('busy.running', lang));
|
|
225
|
+
if (st.busy) return say(st.to, t('busy.running', lang), { reply_markup: stopMarkup(lang) });
|
|
191
226
|
const caption = msgs.map((m) => m.caption?.trim()).find(Boolean) ?? '';
|
|
192
227
|
return runTurn(st, caption, { files });
|
|
193
228
|
}
|
|
@@ -233,6 +268,13 @@ async function handleUpdate(u) {
|
|
|
233
268
|
return;
|
|
234
269
|
}
|
|
235
270
|
|
|
271
|
+
// запрос от виджета (выбор модели, сессии): доступ проверяется так же, как для сообщений и кнопок
|
|
272
|
+
if (u.widget_query) {
|
|
273
|
+
const q = u.widget_query;
|
|
274
|
+
if (!q.from || q.from.is_bot || (q.chat && q.chat.type !== 'private') || !hasAccess(q.from.id)) return;
|
|
275
|
+
return onWidgetQuery(q);
|
|
276
|
+
}
|
|
277
|
+
|
|
236
278
|
const msg = u.message;
|
|
237
279
|
const cb = u.callback_query;
|
|
238
280
|
const from = msg?.from || cb?.from;
|
|
@@ -270,6 +312,14 @@ async function handleUpdate(u) {
|
|
|
270
312
|
if (data.startsWith('tpl:')) return onTopicListCallback(st, cb);
|
|
271
313
|
if (data.startsWith('nav:')) return onNavCallback(st, cb);
|
|
272
314
|
if (data.startsWith('perm:')) return onPermissionCallback(st, cb);
|
|
315
|
+
if (data.startsWith('ask:')) return onAskCallback(st, cb);
|
|
316
|
+
if (data.startsWith('q:')) return onQueueCallback(st, cb);
|
|
317
|
+
if (data === 'cmd:raw') return onRawCommandCallback(st, cb);
|
|
318
|
+
if (data === 'wid:model' || data === 'wid:sessions') {
|
|
319
|
+
// «Обычное меню» под виджетом: тот же экран сообщением с кнопками
|
|
320
|
+
await tg('answerCallbackQuery', { callback_query_id: cb.id }).catch(() => {});
|
|
321
|
+
return data === 'wid:model' ? handleModel(st, '', { classic: true }) : handleSessions(st, { classic: true });
|
|
322
|
+
}
|
|
273
323
|
if (data.startsWith('ses:')) return onSessionCallback(st, cb);
|
|
274
324
|
if (data.startsWith('eng:')) return onEngineCallback(st, cb);
|
|
275
325
|
if (data.startsWith('mdl:')) return onModelCallback(st, cb);
|
|
@@ -277,8 +327,10 @@ async function handleUpdate(u) {
|
|
|
277
327
|
if (data.startsWith('lang:')) return onLangCallback(st, cb);
|
|
278
328
|
return;
|
|
279
329
|
}
|
|
280
|
-
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text);
|
|
330
|
+
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg) });
|
|
281
331
|
if (msg?.photo || msg?.document) return handleAttachment(getState(from.id, chatId, threadId), msg);
|
|
332
|
+
// голосовое, видео, стикер и т. п.: раньше бот на них молчал
|
|
333
|
+
if (msg && unsupportedKind(msg)) return say(getState(from.id, chatId, threadId).to, t('msg.unsupported', langOf(from.id)));
|
|
282
334
|
}
|
|
283
335
|
|
|
284
336
|
/**
|
|
@@ -377,7 +429,7 @@ async function main() {
|
|
|
377
429
|
let updates;
|
|
378
430
|
try {
|
|
379
431
|
// длинный опрос 30 с + запас: если соединение тихо оборвалось, через 45 с переподключаемся (а не через ~5 минут)
|
|
380
|
-
updates = await tg('getUpdates', { offset, timeout: 30, allowed_updates: ['message', 'callback_query', 'stopped_message_generation'] }, { timeoutMs: 45_000 });
|
|
432
|
+
updates = await tg('getUpdates', { offset, timeout: 30, allowed_updates: ['message', 'callback_query', 'stopped_message_generation', 'widget_query'] }, { timeoutMs: 45_000 });
|
|
381
433
|
} catch (e) {
|
|
382
434
|
log('getUpdates:', e.message);
|
|
383
435
|
await new Promise((r) => setTimeout(r, 3000));
|
package/src/db.mjs
CHANGED
|
@@ -212,6 +212,12 @@ export function openDb(path = 'data/bot.db') {
|
|
|
212
212
|
),
|
|
213
213
|
addPermission: db.prepare('INSERT INTO permissions (request_id, tool_call_id, title, options, asked_at) VALUES (?,?,?,?,?)'),
|
|
214
214
|
answerPermission: db.prepare('UPDATE permissions SET chosen_option = ?, outcome = ?, answered_at = ? WHERE id = ?'),
|
|
215
|
+
// расход по пользователям с момента since: запросы, токены, стоимость (что прислали агенты)
|
|
216
|
+
usageSummary: db.prepare(
|
|
217
|
+
`SELECT s.user_id AS user_id, COUNT(r.id) AS requests, COALESCE(SUM(r.total_tokens), 0) AS tokens, SUM(r.cost_usd) AS cost
|
|
218
|
+
FROM requests r JOIN sessions s ON s.id = r.session_id
|
|
219
|
+
WHERE r.started_at >= ? GROUP BY s.user_id ORDER BY tokens DESC, requests DESC`,
|
|
220
|
+
),
|
|
215
221
|
getTopic: db.prepare('SELECT * FROM topics WHERE user_id = ? AND thread_id = ?'),
|
|
216
222
|
insertTopic: db.prepare('INSERT OR IGNORE INTO topics (user_id, thread_id, created_at, updated_at) VALUES (?,?,?,?)'),
|
|
217
223
|
updateTopic: db.prepare(
|
|
@@ -255,6 +261,8 @@ export function openDb(path = 'data/bot.db') {
|
|
|
255
261
|
setRequestStatus: safe((id, status) => q.setRequestStatus.run(status, now(), id)),
|
|
256
262
|
// --- сессии ---
|
|
257
263
|
listSessions: (userId, cwd, limit = 10) => safe(() => q.listSessions.all(userId, cwd, limit))() ?? [],
|
|
264
|
+
/** Расход по пользователям с момента since (ISO): [{user_id, requests, tokens, cost}], cost — null, если агент её не присылал. */
|
|
265
|
+
usageSummary: (since) => safe(() => q.usageSummary.all(since))() ?? [],
|
|
258
266
|
// --- прочее ---
|
|
259
267
|
getSetting: safe((key) => q.getSetting.get(key)?.value ?? null),
|
|
260
268
|
setSetting: safe((key, value) => q.setSetting.run(key, value)),
|
package/src/diff.mjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Построчный дифф для запроса разрешения на правку файла: пользователь видит, что именно изменит агент,
|
|
2
|
+
// а не только путь. Без зависимостей: наибольшая общая подпоследовательность строк, для больших текстов — упрощённо.
|
|
3
|
+
|
|
4
|
+
/** Произведение числа строк, выше которого точный дифф не считается (таблица LCS — память и время). */
|
|
5
|
+
const LCS_LIMIT = 250_000;
|
|
6
|
+
|
|
7
|
+
const linesOf = (s) => (s ? String(s).replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n') : []);
|
|
8
|
+
|
|
9
|
+
/** Операции построчного сравнения: [' ' | '-' | '+', строка][]. */
|
|
10
|
+
function ops(a, b) {
|
|
11
|
+
// общие начало и конец не участвуют в таблице: правка обычно в середине файла
|
|
12
|
+
let start = 0;
|
|
13
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
14
|
+
let endA = a.length;
|
|
15
|
+
let endB = b.length;
|
|
16
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
17
|
+
endA--;
|
|
18
|
+
endB--;
|
|
19
|
+
}
|
|
20
|
+
const head = a.slice(0, start).map((l) => [' ', l]);
|
|
21
|
+
const tail = a.slice(endA).map((l) => [' ', l]);
|
|
22
|
+
const x = a.slice(start, endA);
|
|
23
|
+
const y = b.slice(start, endB);
|
|
24
|
+
let mid;
|
|
25
|
+
if (x.length * y.length > LCS_LIMIT) {
|
|
26
|
+
mid = [...x.map((l) => ['-', l]), ...y.map((l) => ['+', l])]; // слишком большой кусок: «всё удалено, всё добавлено»
|
|
27
|
+
} else {
|
|
28
|
+
const w = y.length + 1;
|
|
29
|
+
const table = new Uint32Array((x.length + 1) * w);
|
|
30
|
+
for (let i = x.length - 1; i >= 0; i--) {
|
|
31
|
+
for (let j = y.length - 1; j >= 0; j--) {
|
|
32
|
+
table[i * w + j] = x[i] === y[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
mid = [];
|
|
36
|
+
let i = 0;
|
|
37
|
+
let j = 0;
|
|
38
|
+
while (i < x.length && j < y.length) {
|
|
39
|
+
if (x[i] === y[j]) {
|
|
40
|
+
mid.push([' ', x[i]]);
|
|
41
|
+
i++;
|
|
42
|
+
j++;
|
|
43
|
+
} else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) mid.push(['-', x[i++]]);
|
|
44
|
+
else mid.push(['+', y[j++]]);
|
|
45
|
+
}
|
|
46
|
+
while (i < x.length) mid.push(['-', x[i++]]);
|
|
47
|
+
while (j < y.length) mid.push(['+', y[j++]]);
|
|
48
|
+
}
|
|
49
|
+
return [...head, ...mid, ...tail];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Дифф двух текстов в привычном виде: строки с «-» и «+», вокруг изменений — context строк без изменений,
|
|
54
|
+
* пропуски отмечены «…». Не длиннее maxLines строк (дальше — «… ещё N»). Пустая строка — изменений нет.
|
|
55
|
+
* @returns {{text: string, added: number, removed: number}}
|
|
56
|
+
*/
|
|
57
|
+
export function lineDiff(oldText, newText, { context = 2, maxLines = 40 } = {}) {
|
|
58
|
+
const all = ops(linesOf(oldText), linesOf(newText));
|
|
59
|
+
const added = all.filter(([k]) => k === '+').length;
|
|
60
|
+
const removed = all.filter(([k]) => k === '-').length;
|
|
61
|
+
if (!added && !removed) return { text: '', added, removed };
|
|
62
|
+
const keep = new Array(all.length).fill(false);
|
|
63
|
+
all.forEach(([k], i) => {
|
|
64
|
+
if (k === ' ') return;
|
|
65
|
+
for (let d = Math.max(0, i - context); d <= Math.min(all.length - 1, i + context); d++) keep[d] = true;
|
|
66
|
+
});
|
|
67
|
+
const out = [];
|
|
68
|
+
let gap = false;
|
|
69
|
+
all.forEach(([k, line], i) => {
|
|
70
|
+
if (!keep[i]) {
|
|
71
|
+
gap = true;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (gap && out.length) out.push('…');
|
|
75
|
+
gap = false;
|
|
76
|
+
out.push(`${k}${line}`);
|
|
77
|
+
});
|
|
78
|
+
const shown = out.slice(0, maxLines);
|
|
79
|
+
if (out.length > maxLines) shown.push(`… +${out.length - maxLines}`);
|
|
80
|
+
return { text: shown.join('\n'), added, removed };
|
|
81
|
+
}
|
package/src/files.mjs
CHANGED
|
@@ -122,8 +122,9 @@ const NO_TEXT_PROMPT = 'The user sent the attached file(s) without a message. Lo
|
|
|
122
122
|
/**
|
|
123
123
|
* Блоки промпта ACP: текст пользователя, изображения (если агент принимает image) и служебная заметка со списком файлов
|
|
124
124
|
* и правилами отправки. files: [{path, name, mime, size, data?}] — data (Buffer) только у изображений.
|
|
125
|
+
* quote — фрагмент прошлого сообщения, на который отвечает пользователь; notes — другие подсказки агенту (кнопки ответа).
|
|
125
126
|
*/
|
|
126
|
-
export function buildPromptBlocks({ text, files = [], caps, outbox }) {
|
|
127
|
+
export function buildPromptBlocks({ text, files = [], caps, outbox, quote = null, notes = [] }) {
|
|
127
128
|
const blocks = [{ type: 'text', text: text?.trim() || (files.length ? NO_TEXT_PROMPT : '') }];
|
|
128
129
|
const imageOk = Boolean(caps?.promptCapabilities?.image);
|
|
129
130
|
for (const f of files) {
|
|
@@ -132,6 +133,10 @@ export function buildPromptBlocks({ text, files = [], caps, outbox }) {
|
|
|
132
133
|
}
|
|
133
134
|
}
|
|
134
135
|
const note = [];
|
|
136
|
+
if (quote) {
|
|
137
|
+
note.push('[AcpGram] The user is replying to this fragment of an earlier message in this chat:');
|
|
138
|
+
for (const line of String(quote).split(/\r?\n/)) note.push(`> ${line}`);
|
|
139
|
+
}
|
|
135
140
|
if (files.length) {
|
|
136
141
|
note.push('[AcpGram] The user attached files (saved on the server, open them with your file tools when needed):');
|
|
137
142
|
for (const f of files) {
|
|
@@ -146,6 +151,7 @@ export function buildPromptBlocks({ text, files = [], caps, outbox }) {
|
|
|
146
151
|
}
|
|
147
152
|
}
|
|
148
153
|
if (outbox) note.push(outboxNote(outbox));
|
|
154
|
+
note.push(...notes);
|
|
149
155
|
if (note.length) blocks.push({ type: 'text', text: note.join('\n') });
|
|
150
156
|
return blocks;
|
|
151
157
|
}
|