acpgram 1.25.0 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/README.ru.md +17 -0
- package/package.json +1 -1
- package/src/bot.mjs +14 -4
- package/src/files.mjs +11 -0
- package/src/filesUi.mjs +293 -0
- package/src/i18n.mjs +34 -0
- package/src/projectFiles.mjs +168 -0
- package/src/projectsUi.mjs +5 -0
- package/src/turn.mjs +2 -2
- package/src/ui.mjs +2 -1
package/README.md
CHANGED
|
@@ -50,6 +50,7 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
|
|
|
50
50
|
- **Dialogs mode (topics)** — if topics in private chats are turned on for the bot (@BotFather), each topic of the chat is a separate dialog with the agent, with its own project, engine and history. You can work in several topics at once and come back to a topic later to continue where you left off: the agent session resumes by itself. `/new` creates a new topic, and the agent names it after the first answer (with a short project name in front); General works as a regular dialog, and `/project` there shows the dialogs of the chosen project as buttons that open the topic. A command sent from the chat list rather than from inside a topic (Telegram creates a new topic for such a message by itself) runs in General, and the empty topic is deleted. A topic stays in its own project. Everyone picks the mode with `/topics`: "Dialogs" or "One chat". A teammate runs up to `MAX_AGENTS_PER_USER` agents at once (2), the admin up to `ADMIN_MAX_AGENTS` (4); when there is no room, the user's own oldest idle agent is unloaded, and that dialog continues when the user comes back to it.
|
|
51
51
|
- **Language** — the bot talks to each user in their Telegram language (`ru`, `uk` or `en`; any other falls back to `DEFAULT_LANG`, English by default). `/language` changes it and takes priority over the Telegram language. The `acpgram` terminal commands (setup wizard, service, update, help) speak the system language: Russian, Ukrainian, otherwise English; on Windows the system UI language is used, not the regional format.
|
|
52
52
|
- **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
|
|
53
|
+
- **Project files, bypassing the agent** — `/files` lists the project files, creates a file from a message, uploads a file from your device and deletes files. The contents never go into a model request, which is how secrets (`.env`, keys) get into a project.
|
|
53
54
|
- **Personal workspaces** — with `USER_WORKSPACES=1` each teammate gets their own folder inside the projects root and chooses projects only there; a new project is created with the "➕ New project" button.
|
|
54
55
|
- **Sessions** — `/sessions` resumes a previous conversation (in the engine it was created in), even after a restart; `/new` starts fresh; `/close` unloads the agent process.
|
|
55
56
|
- **Team access** — invite links and access requests; per-user access levels, engines and model restrictions; `/active` shows who is working and lets the admin end any session.
|
|
@@ -184,6 +185,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
|
|
|
184
185
|
| `/engine [gemini, claude, agy, codex, opencode]` | everyone | choose the engine |
|
|
185
186
|
| `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
|
|
186
187
|
| `/new` | everyone | new session |
|
|
188
|
+
| `/files` | everyone | project files: list, create, upload and delete — bypassing the agent |
|
|
187
189
|
| `/sessions` | everyone | resume a previous session in this project |
|
|
188
190
|
| `/stop` | everyone | stop the running request |
|
|
189
191
|
| `/close`, `/exit` | everyone | close the session and unload the agent process |
|
|
@@ -207,6 +209,19 @@ OpenCode has only two modes (`plan` and `build`); what the agent may do is set b
|
|
|
207
209
|
|
|
208
210
|
New teammates get only the default engine; the admin grants other engines and can restrict models per user and per engine. At most `MAX_AGENTS` (3) teammate agents run at once across all engines (the admin is not counted); idle sessions close after `IDLE_MINUTES` (30).
|
|
209
211
|
|
|
212
|
+
### Project files and secrets
|
|
213
|
+
|
|
214
|
+
Everything a user types to the bot or sends as a file goes to the agent, and therefore into a model request. That is wrong for passwords, tokens and keys: free models may use requests for training. The `/files` command puts a file straight into the project folder, bypassing the agent.
|
|
215
|
+
|
|
216
|
+
- **List.** `/files` shows the files and folders of the current project (including hidden ones such as `.env`; without `.git`, `node_modules` and links); folders are browsed with buttons.
|
|
217
|
+
- **"📝 Create file".** The bot asks for a name (a subfolder is allowed: `config/.env`) and then for the contents in one message (up to 3500 characters). The message with the contents is deleted from the chat right away; it is not written to the database or the logs.
|
|
218
|
+
- **"⬆️ Upload file".** The next file you send (or an album) is saved to the open project folder under its own name, and the message with it is deleted from the chat. The wait is one-off and expires in 10 minutes. Without pressing the button, files and images go to the agent as before.
|
|
219
|
+
- **Delete** — from the file card, with a confirmation. An existing file is replaced only after a "Replace?" question.
|
|
220
|
+
- **Who can change files:** the administrator; a teammate inside their personal workspace, and in a shared root with the "Normal" or "Full" level. Anyone can view the list.
|
|
221
|
+
- **Inside the project only.** The bot never writes or deletes outside the project folder and does not follow links: a link planted in the project cannot make it overwrite someone else's file.
|
|
222
|
+
|
|
223
|
+
What this gives and what it does not. The secret does not get into a model request *from the user*. The file itself stays available to the agent — otherwise the applications it writes and runs could not use it. So that the agent does not read the values into the conversation by itself, the bot regularly reminds it: do not open or print files with secrets, refer to settings by name, and send the user to `/files` for a missing value. This is an instruction, not a ban: for especially sensitive data use a model from a provider that does not train on requests.
|
|
224
|
+
|
|
210
225
|
### Personal workspaces
|
|
211
226
|
|
|
212
227
|
By default all teammates browse the same projects root. `USER_WORKSPACES=1` (together with `PROJECTS_ROOT`) gives each teammate a folder of their own: `<root>/<Telegram ID>`. The folder is created when the teammate first talks to the bot.
|
|
@@ -302,7 +317,8 @@ src/
|
|
|
302
317
|
state.mjs per-user state: agent process, engine, project, limits, idle reaper
|
|
303
318
|
admin.mjs invites, access requests, /users, /active
|
|
304
319
|
projects.mjs project paths (inside the root or anywhere), recent projects, search
|
|
305
|
-
*Ui.mjs /project, /sessions, /engine, /model screens
|
|
320
|
+
*Ui.mjs /project, /files, /sessions, /engine, /model screens
|
|
321
|
+
projectFiles.mjs project files bypassing the agent: safe writes and deletes inside the project, no links
|
|
306
322
|
ui.mjs rendering: drafts, steps, final message, screens
|
|
307
323
|
telegram.mjs Bot API calls, rich messages, long text splitting, file download and upload
|
|
308
324
|
sandbox.mjs agent sandbox (Linux, bubblewrap): what a teammate's agent can see, the startup check
|
package/README.ru.md
CHANGED
|
@@ -53,6 +53,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
53
53
|
- с `PROJECTS_ROOT` (командный сервер, например `C:\scripts`) — только папки внутри корня;
|
|
54
54
|
- с `PROJECTS_ROOT` и `USER_WORKSPACES=1` (личные пространства) — у каждого сотрудника своя папка в корне, чужие папки он не видит и выбрать не может; новый проект создаётся кнопкой «➕ Новый проект» (см. «Личные пространства»);
|
|
55
55
|
- без `PROJECTS_ROOT` (личная установка) — любая существующая папка, по умолчанию домашняя.
|
|
56
|
+
- **Файлы проекта в обход агента** (`/files`): список файлов проекта по папкам, создание файла из сообщения, загрузка файла с устройства и удаление. Содержимое таких файлов не попадает в запрос к модели — так в проект кладут секреты (`.env`, ключи), которые нельзя показывать бесплатным моделям. См. «Файлы проекта и секреты».
|
|
56
57
|
- **Возврат к прошлой сессии** (`/sessions`): агент помнит весь диалог, сессию можно возобновить даже после перезапуска бота. У каждой сессии метка движка; сессия возобновляется в том движке, где была создана.
|
|
57
58
|
- **Доступ для сотрудников**: администратор выдаёт и забирает доступ, выбирая уровень, движки и модели.
|
|
58
59
|
- **База работы бота** (SQLite): сессии, запросы пользователей с моделью, токенами и стоимостью, вызовы инструментов, разрешения, ответы модели.
|
|
@@ -66,6 +67,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
66
67
|
| `/engine [gemini, claude, agy, codex, opencode]` | все | выбор движка кнопками или по названию |
|
|
67
68
|
| `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
|
|
68
69
|
| `/new` | все | новая сессия агента |
|
|
70
|
+
| `/files` | все | файлы проекта: список, создание, загрузка и удаление — в обход агента |
|
|
69
71
|
| `/sessions` | все | список прошлых сессий в текущем проекте и возврат в выбранную |
|
|
70
72
|
| `/stop` | все | остановить выполняющийся запрос |
|
|
71
73
|
| `/close`, `/exit` | все | закрыть сессию, выгрузить процесс агента и освободить слот |
|
|
@@ -97,6 +99,19 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
97
99
|
|
|
98
100
|
**Лимиты:** не более 3 одновременно работающих агентов сотрудников во всех движках вместе (администратор вне лимита), сессия закрывается через 30 минут простоя.
|
|
99
101
|
|
|
102
|
+
### Файлы проекта и секреты
|
|
103
|
+
|
|
104
|
+
Всё, что пользователь пишет боту или отправляет ему файлом, уходит агенту, а значит — в запрос к модели. Для паролей, токенов и ключей это не подходит: бесплатные модели могут использовать запросы для обучения. Команда `/files` кладёт файл прямо в папку проекта, минуя агента.
|
|
105
|
+
|
|
106
|
+
- **Список.** `/files` показывает файлы и папки текущего проекта (вместе со скрытыми вроде `.env`; без `.git`, `node_modules` и ссылок), по папкам можно ходить кнопками.
|
|
107
|
+
- **«📝 Создать файл».** Бот спрашивает имя (можно с подпапкой: `config/.env`), затем содержимое одним сообщением (до 3500 символов). Сообщение с содержимым сразу удаляется из чата; в базу и журналы оно не пишется.
|
|
108
|
+
- **«⬆️ Загрузить файл».** Следующий присланный файл (или альбом) сохраняется в открытую папку проекта под своим именем, а сообщение с ним удаляется из чата. Ожидание одноразовое и истекает через 10 минут. Без нажатия кнопки файлы и изображения, как и раньше, передаются агенту.
|
|
109
|
+
- **Удаление** — из карточки файла, с подтверждением. Существующий файл заменяется только после вопроса «Заменить?».
|
|
110
|
+
- **Кто может менять файлы:** администратор; сотрудник — в личном пространстве, а в общем корне — с уровнем «Обычный» или «Полный». Смотреть список может любой.
|
|
111
|
+
- **Только внутри проекта.** Бот не пишет и не удаляет за пределами папки проекта и не ходит по ссылкам: ссылка, подложенная в проект, не заставит его перезаписать чужой файл.
|
|
112
|
+
|
|
113
|
+
Что это даёт и чего не даёт. Секрет не попадает в запрос к модели *от пользователя*. Сам файл агенту доступен — иначе приложения, которые он пишет и запускает, не смогли бы им пользоваться. Чтобы агент не прочитал значения в диалог сам, бот регулярно напоминает ему: файлы с секретами не открывать и не выводить, ссылаться на настройки по именам, а за недостающим значением отправлять пользователя в `/files`. Это указание, а не запрет: для особо чувствительных данных используйте модель провайдера, который не обучается на запросах.
|
|
114
|
+
|
|
100
115
|
### Личные пространства
|
|
101
116
|
|
|
102
117
|
По умолчанию все сотрудники ходят по одному корню проектов. `USER_WORKSPACES=1` (вместе с `PROJECTS_ROOT`) даёт каждому сотруднику свою папку: `<корень>/<Telegram ID>`. Папка создаётся сама при первом обращении сотрудника к боту.
|
|
@@ -378,6 +393,8 @@ src/
|
|
|
378
393
|
admin.mjs приглашения, запросы доступа, /users, /active
|
|
379
394
|
projects.mjs пути проектов: с корнем — безопасно внутри него, без корня — любая папка; недавние, поиск
|
|
380
395
|
projectsUi.mjs команда /project и навигация кнопками
|
|
396
|
+
projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
|
|
397
|
+
filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
|
|
381
398
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
382
399
|
tools.mjs разбор событий вызовов инструментов агента
|
|
383
400
|
asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
|
package/package.json
CHANGED
package/src/bot.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from '.
|
|
|
11
11
|
import { LANGS, LANG_CODES, LANG_PICK, errText, normLang, t } from './i18n.mjs';
|
|
12
12
|
import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
|
|
13
13
|
import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
|
|
14
|
+
import { handleFiles, onFileInput, onFileUpload, onFilesCallback } from './filesUi.mjs';
|
|
14
15
|
import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
|
|
15
16
|
import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
16
17
|
import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
|
|
@@ -118,6 +119,7 @@ const COMMANDS = [
|
|
|
118
119
|
{ name: 'invite', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/invite') },
|
|
119
120
|
{ name: 'usage', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/usage') },
|
|
120
121
|
{ name: 'project', menu: true, button: true, run: (st, arg) => handleProject(st, arg) },
|
|
122
|
+
{ name: 'files', menu: true, button: true, run: (st) => handleFiles(st) },
|
|
121
123
|
{ name: 'engine', menu: true, button: true, run: (st, arg) => handleEngine(st, arg) },
|
|
122
124
|
{ name: 'model', menu: true, button: true, run: (st, arg) => handleModel(st, arg) },
|
|
123
125
|
{ name: 'new', menu: true, button: true, run: newCommand },
|
|
@@ -141,18 +143,20 @@ const sendToAgent = (st, text, opts = {}) => (st.busy ? enqueue(st, text, opts)
|
|
|
141
143
|
* команды не объявлял, это, скорее всего, опечатка: спрашиваем, а не тратим запрос.
|
|
142
144
|
* @param {{quote?: string|null}} [opts] quote — фрагмент прошлого сообщения, на который отвечает пользователь
|
|
143
145
|
*/
|
|
144
|
-
async function handleText(st, text, { quote = null } = {}) {
|
|
146
|
+
async function handleText(st, text, { quote = null, messageId = null } = {}) {
|
|
145
147
|
const m = /^\/(\w+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(text);
|
|
146
148
|
const name = m?.[1]?.toLowerCase();
|
|
147
149
|
const command = name ? COMMANDS.find((c) => c.name === name || c.aliases?.includes(name)) : null;
|
|
148
150
|
const lang = langOf(st.userId);
|
|
149
|
-
if (name) st.pendingInput = null; // любая команда отменяет ожидание названия нового проекта
|
|
150
151
|
if (command) {
|
|
152
|
+
st.pendingInput = null; // команда бота отменяет ожидание названия проекта, имени или содержимого файла
|
|
151
153
|
if (command.admin && !isAdmin(st.userId)) return say(st.to, t('admin.only', lang));
|
|
152
154
|
return command.run(st, m[2]);
|
|
153
155
|
}
|
|
154
156
|
// бот ждёт название папки нового проекта (кнопка «Новый проект» в /project): этот текст — оно, а не запрос агенту
|
|
155
157
|
if (await onProjectNameInput(st, text)) return;
|
|
158
|
+
// бот ждёт имя или содержимое файла проекта (/files): содержимое агенту не передаётся и удаляется из чата
|
|
159
|
+
if (await onFileInput(st, text, { messageId })) return;
|
|
156
160
|
if (name && !st.agent?.commands?.has(name)) {
|
|
157
161
|
const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
|
|
158
162
|
if (guess) {
|
|
@@ -315,6 +319,7 @@ async function handleUpdate(u) {
|
|
|
315
319
|
if (data.startsWith('tpc:')) return onTopicsCallback(st, cb);
|
|
316
320
|
if (data.startsWith('tpl:')) return onTopicListCallback(st, cb);
|
|
317
321
|
if (data.startsWith('nav:')) return onNavCallback(st, cb);
|
|
322
|
+
if (data.startsWith('fl:')) return onFilesCallback(st, cb);
|
|
318
323
|
if (data.startsWith('perm:')) return onPermissionCallback(st, cb);
|
|
319
324
|
if (data.startsWith('ask:')) return onAskCallback(st, cb);
|
|
320
325
|
if (data.startsWith('q:')) return onQueueCallback(st, cb);
|
|
@@ -331,8 +336,13 @@ async function handleUpdate(u) {
|
|
|
331
336
|
if (data.startsWith('lang:')) return onLangCallback(st, cb);
|
|
332
337
|
return;
|
|
333
338
|
}
|
|
334
|
-
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg) });
|
|
335
|
-
if (msg?.photo || msg?.document)
|
|
339
|
+
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg), messageId: msg.message_id });
|
|
340
|
+
if (msg?.photo || msg?.document) {
|
|
341
|
+
const st = getState(from.id, chatId, threadId);
|
|
342
|
+
// нажата «Загрузить файл» в /files: файл кладётся в проект, а не передаётся агенту
|
|
343
|
+
if (await onFileUpload(st, msg)) return;
|
|
344
|
+
return handleAttachment(st, msg);
|
|
345
|
+
}
|
|
336
346
|
// голосовое, видео, стикер и т. п.: раньше бот на них молчал
|
|
337
347
|
if (msg && unsupportedKind(msg)) return say(getState(from.id, chatId, threadId).to, t('msg.unsupported', langOf(from.id)));
|
|
338
348
|
}
|
package/src/files.mjs
CHANGED
|
@@ -117,6 +117,17 @@ export function outboxNote(outbox) {
|
|
|
117
117
|
);
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Подсказка агенту о секретах проекта. Пользователь кладёт их в проект сам, в обход чата (/files), чтобы значения не
|
|
122
|
+
* попадали в запросы к модели; агент не должен свести это на нет, прочитав файл в диалог. Доступ к файлам не закрыт:
|
|
123
|
+
* приложения, которые агент пишет и запускает, читают секреты во время работы. Служебный текст — на английском.
|
|
124
|
+
*/
|
|
125
|
+
export const SECRETS_NOTE =
|
|
126
|
+
'[AcpGram] Files such as .env, .Renviron, private keys and credentials in the project hold the user\'s secrets. ' +
|
|
127
|
+
'Do not open or print them and never show, quote or repeat their values in replies, commands or commits; refer to settings by name. ' +
|
|
128
|
+
'Code you write may load them at run time, that is what they are for. If a secret value is needed or missing, do not ask the user ' +
|
|
129
|
+
'to send it in the chat: tell them to put it into the project file themselves with the /files command of this bot.';
|
|
130
|
+
|
|
120
131
|
const NO_TEXT_PROMPT = 'The user sent the attached file(s) without a message. Look at them, briefly say what they contain and ask what to do with them.';
|
|
121
132
|
|
|
122
133
|
/**
|
package/src/filesUi.mjs
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// Команда /files: файлы проекта, которыми пользователь управляет сам, в обход агента — список, создание файла из
|
|
2
|
+
// сообщения, загрузка файла с устройства, удаление. Содержимое таких файлов не попадает в запрос к модели: так в проект
|
|
3
|
+
// кладут секреты (.env, ключи). Обычная отправка файла боту по-прежнему передаёт его агенту.
|
|
4
|
+
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
5
|
+
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
|
+
import { MAX_FILE_BYTES, describeAttachment, safeFileName } from './files.mjs';
|
|
7
|
+
import { LOCALES, errText, t } from './i18n.mjs';
|
|
8
|
+
import { FileError, deleteProjectFile, fmtSize, listProjectDir, projectFileInfo, relPath, resolveTarget, writeProjectFile } from './projectFiles.mjs';
|
|
9
|
+
import { insideRoot, isPersonalRoot, samePath } from './projects.mjs';
|
|
10
|
+
import { folderRows, pathToken, tokenPath } from './projectsUi.mjs';
|
|
11
|
+
import { isAdmin, rootOf, userPath } from './state.mjs';
|
|
12
|
+
import { dest, downloadFile, tg } from './telegram.mjs';
|
|
13
|
+
import { hCode, th } from './ui.mjs';
|
|
14
|
+
|
|
15
|
+
const PAGE = 20;
|
|
16
|
+
const HTML = { parse_mode: 'HTML' };
|
|
17
|
+
/** Сколько бот ждёт имя файла или сам файл; позже сообщения снова уходят агенту. */
|
|
18
|
+
export const FILE_WAIT_MS = 10 * 60_000;
|
|
19
|
+
/** Содержимое файла одним сообщением: длиннее Telegram делит текст на части, и вторая ушла бы агенту. */
|
|
20
|
+
export const INLINE_MAX = 3500;
|
|
21
|
+
/** Сколько после слишком длинного содержимого бот не передаёт текст агенту (части разбитого сообщения). */
|
|
22
|
+
const SWALLOW_MS = 5000;
|
|
23
|
+
/** Альбом из нескольких файлов приходит отдельными сообщениями: все они относятся к одной загрузке. */
|
|
24
|
+
const ALBUM_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Может ли пользователь сам класть и удалять файлы в проекте: администратор — всегда; сотрудник — в личном
|
|
28
|
+
* пространстве, а в общем корне — если его уровень разрешает агенту менять файлы («Обычный», «Полный»).
|
|
29
|
+
*/
|
|
30
|
+
export const canManageFiles = (userId) => isAdmin(userId) || isPersonalRoot(rootOf(userId)) || ['normal', 'full'].includes(db.getUser(userId)?.level);
|
|
31
|
+
|
|
32
|
+
/** Папка проекта диалога, если она доступна (существует и лежит в корне пользователя), иначе null. */
|
|
33
|
+
const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
34
|
+
|
|
35
|
+
/** Путь внутри проекта для показа: «config/.env»; сама папка проекта — «/». */
|
|
36
|
+
const relShow = (project, path) => relative(project, path).split(sep).join('/') || '/';
|
|
37
|
+
|
|
38
|
+
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'fl:x' }]] });
|
|
39
|
+
|
|
40
|
+
/** Текст причины отказа (FileError.code) на языке пользователя. */
|
|
41
|
+
const whyText = (e, lang) => (e instanceof FileError ? t(`files.err.${e.code}`, lang) : errText(e, lang));
|
|
42
|
+
|
|
43
|
+
/** Удаляет сообщение пользователя с содержимым или файлом: в чате не должно оставаться копии секрета. */
|
|
44
|
+
const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch((e) => log('files: сообщение не удалено:', e.message)) : null);
|
|
45
|
+
|
|
46
|
+
/** Экран папки проекта: папки, файлы с размером, «Вверх», «Создать файл» и «Загрузить файл». Текст — HTML. */
|
|
47
|
+
export function filesView(st, project, dir, page = 0, lang = langOf(st.userId)) {
|
|
48
|
+
const { dirs, files } = listProjectDir(project, dir);
|
|
49
|
+
const entries = [...dirs.map((name) => ({ name, dir: true })), ...files];
|
|
50
|
+
const pages = Math.max(1, Math.ceil(entries.length / PAGE));
|
|
51
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
52
|
+
const shown = entries.slice(page * PAGE, (page + 1) * PAGE);
|
|
53
|
+
const rows = [
|
|
54
|
+
...folderRows(shown.filter((e) => e.dir).map((e) => e.name)).map((row) => row.map((n) => ({ text: `📁 ${n}`, callback_data: `fl:o:${pathToken(join(dir, n))}:0` }))),
|
|
55
|
+
...shown.filter((e) => !e.dir).map((f) => [{ text: [...`📄 ${f.name} · ${fmtSize(f.size)}`].slice(0, 60).join(''), callback_data: `fl:f:${pathToken(join(dir, f.name))}` }]),
|
|
56
|
+
];
|
|
57
|
+
if (pages > 1) {
|
|
58
|
+
const nav = [];
|
|
59
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `fl:o:${pathToken(dir)}:${page - 1}` });
|
|
60
|
+
nav.push({ text: `${page + 1}/${pages}`, callback_data: 'nav:n' });
|
|
61
|
+
if (page < pages - 1) nav.push({ text: '▶', callback_data: `fl:o:${pathToken(dir)}:${page + 1}` });
|
|
62
|
+
rows.push(nav);
|
|
63
|
+
}
|
|
64
|
+
if (!samePath(dir, project)) rows.push([{ text: t('proj.up', lang), callback_data: `fl:o:${pathToken(dirname(dir))}:0` }]);
|
|
65
|
+
if (canManageFiles(st.userId)) {
|
|
66
|
+
rows.push([
|
|
67
|
+
{ text: t('files.create', lang), callback_data: `fl:n:${pathToken(dir)}` },
|
|
68
|
+
{ text: t('files.upload', lang), callback_data: `fl:u:${pathToken(dir)}` },
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
const head = th('files.head', lang, { p: hCode(userPath(st.userId, project, lang)), dir: hCode(relShow(project, dir)) });
|
|
72
|
+
const body = entries.length ? th('files.hint', lang) : `<i>${th('files.empty', lang)}</i>\n\n${th('files.hint', lang)}`;
|
|
73
|
+
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** /files — файлы текущего проекта. */
|
|
77
|
+
export async function handleFiles(st) {
|
|
78
|
+
const lang = langOf(st.userId);
|
|
79
|
+
const project = projectOf(st);
|
|
80
|
+
if (!project) return say(st.to, t('state.projectGone', lang));
|
|
81
|
+
const v = filesView(st, project, project, 0, lang);
|
|
82
|
+
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('files:', e.message));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Карточка файла: путь, размер, дата изменения, удаление. */
|
|
86
|
+
function fileCard(st, project, path, lang, { confirm = false } = {}) {
|
|
87
|
+
const info = projectFileInfo(project, path);
|
|
88
|
+
if (!info) return null;
|
|
89
|
+
const when = new Date(info.mtime).toLocaleString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
|
|
90
|
+
const tk = pathToken(path);
|
|
91
|
+
const back = { text: t('files.back', lang), callback_data: `fl:o:${pathToken(dirname(path))}:0` };
|
|
92
|
+
const rows = confirm
|
|
93
|
+
? [[{ text: t('files.deleteYes', lang), callback_data: `fl:D:${tk}` }, { text: t('btn.cancel', lang), callback_data: `fl:f:${tk}` }]]
|
|
94
|
+
: [...(canManageFiles(st.userId) ? [[{ text: t('files.delete', lang), callback_data: `fl:d:${tk}` }]] : []), [back]];
|
|
95
|
+
const text = th(confirm ? 'files.deleteAsk' : 'files.card', lang, { path: hCode(relShow(project, path)), size: fmtSize(info.size), when });
|
|
96
|
+
return { text, markup: { inline_keyboard: rows } };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
let replaceSeq = 0;
|
|
100
|
+
|
|
101
|
+
/** Спрашивает, заменить ли существующий файл; что именно писать — запоминается до ответа (st.replaces). */
|
|
102
|
+
function askReplace(st, project, job, lang) {
|
|
103
|
+
st.replaces ??= new Map();
|
|
104
|
+
if (st.replaces.size > 20) st.replaces.clear();
|
|
105
|
+
const id = ++replaceSeq;
|
|
106
|
+
st.replaces.set(id, job);
|
|
107
|
+
const path = join(job.dir, ...job.parts);
|
|
108
|
+
return say(st.to, th('files.existsAsk', lang, { path: hCode(relShow(project, path)) }), {
|
|
109
|
+
...HTML,
|
|
110
|
+
reply_markup: { inline_keyboard: [[{ text: t('files.replace', lang), callback_data: `fl:r:${id}` }, { text: t('btn.cancel', lang), callback_data: 'fl:x' }]] },
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Просит прислать содержимое файла следующим сообщением. */
|
|
115
|
+
function askContent(st, project, { dir, parts, replace = false }, lang) {
|
|
116
|
+
st.pendingInput = { kind: 'fileContent', dir, parts, replace, at: Date.now() };
|
|
117
|
+
return say(st.to, th('files.contentAsk', lang, { path: hCode(relShow(project, join(dir, ...parts))) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Скачивает присланный файл и кладёт его в проект. */
|
|
121
|
+
async function saveUpload(st, project, { dir, parts, meta, messageId }, lang, { replace = false } = {}) {
|
|
122
|
+
let data;
|
|
123
|
+
try {
|
|
124
|
+
data = await downloadFile(meta.id);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
log('files: скачивание:', e.message, '| пользователь', st.userId);
|
|
127
|
+
return say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang) }));
|
|
128
|
+
}
|
|
129
|
+
if (data.length > MAX_FILE_BYTES) return say(st.to, t('file.tooBig', lang));
|
|
130
|
+
try {
|
|
131
|
+
const r = writeProjectFile(project, dir, parts, data, { replace });
|
|
132
|
+
log('файл загружен в проект:', st.userId, r.path, `${r.size} Б`);
|
|
133
|
+
await dropMessage(st, messageId);
|
|
134
|
+
return say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
log('files: запись:', e.message, '| пользователь', st.userId);
|
|
137
|
+
return say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Кнопки экрана файлов: fl:o (папка), fl:f (файл), fl:d / fl:D (удаление), fl:n (создать), fl:u (загрузить), fl:r (заменить), fl:x (отмена). */
|
|
142
|
+
export async function onFilesCallback(st, cb) {
|
|
143
|
+
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
144
|
+
const lang = langOf(st.userId);
|
|
145
|
+
const chatId = cb.message?.chat?.id ?? st.chatId;
|
|
146
|
+
const messageId = cb.message?.message_id;
|
|
147
|
+
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
148
|
+
const edit = (v) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('files:', e.message));
|
|
149
|
+
|
|
150
|
+
if (action === 'x') {
|
|
151
|
+
st.pendingInput = null;
|
|
152
|
+
st.replaces?.clear();
|
|
153
|
+
await ack();
|
|
154
|
+
return edit({ text: th('files.cancelled', lang) });
|
|
155
|
+
}
|
|
156
|
+
const project = projectOf(st);
|
|
157
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
158
|
+
const manage = canManageFiles(st.userId);
|
|
159
|
+
|
|
160
|
+
if (action === 'r') {
|
|
161
|
+
const job = st.replaces?.get(Number(arg));
|
|
162
|
+
if (!job || !manage) return ack(t('proj.stale', lang));
|
|
163
|
+
st.replaces.delete(Number(arg));
|
|
164
|
+
await ack();
|
|
165
|
+
await edit({ text: th('files.replacing', lang, { path: hCode(relShow(project, join(job.dir, ...job.parts))) }) });
|
|
166
|
+
return job.meta ? saveUpload(st, project, job, lang, { replace: true }) : askContent(st, project, { ...job, replace: true }, lang);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// токены путей общие для всех пользователей: путь из кнопки каждый раз проверяется по проекту нажавшего
|
|
170
|
+
const path = tokenPath(arg);
|
|
171
|
+
if (!path) return ack(t('proj.stale', lang));
|
|
172
|
+
try {
|
|
173
|
+
if (action === 'o') {
|
|
174
|
+
const v = filesView(st, project, path, Number(pageStr) || 0, lang);
|
|
175
|
+
await ack();
|
|
176
|
+
return edit(v);
|
|
177
|
+
}
|
|
178
|
+
if (action === 'f' || action === 'd') {
|
|
179
|
+
const card = fileCard(st, project, path, lang, { confirm: action === 'd' && manage });
|
|
180
|
+
if (!card) return ack(t('files.err.missing', lang));
|
|
181
|
+
await ack();
|
|
182
|
+
return edit(card);
|
|
183
|
+
}
|
|
184
|
+
if (!manage) return ack(t('files.noRights', lang));
|
|
185
|
+
if (action === 'D') {
|
|
186
|
+
deleteProjectFile(project, path);
|
|
187
|
+
log('файл проекта удалён:', st.userId, path);
|
|
188
|
+
await ack(t('files.deleted', lang, { name: basename(path) }));
|
|
189
|
+
return edit(filesView(st, project, dirname(path), 0, lang));
|
|
190
|
+
}
|
|
191
|
+
if (action === 'n' || action === 'u') {
|
|
192
|
+
listProjectDir(project, path); // папка должна быть внутри проекта
|
|
193
|
+
await ack();
|
|
194
|
+
st.pendingInput = { kind: action === 'n' ? 'fileName' : 'fileUpload', dir: path, at: Date.now() };
|
|
195
|
+
return say(st.to, th(action === 'n' ? 'files.nameAsk' : 'files.uploadAsk', lang, { dir: hCode(relShow(project, path)) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
196
|
+
}
|
|
197
|
+
} catch (e) {
|
|
198
|
+
if (!(e instanceof FileError)) log('files:', e.message, '| пользователь', st.userId);
|
|
199
|
+
return ack(whyText(e, lang));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Текст пользователя, пока бот ждёт имя файла или его содержимое. Возвращает true, если текст обработан здесь:
|
|
205
|
+
* агенту он тогда не передаётся. Содержимое не пишется в журнал и базу, а сообщение с ним удаляется из чата.
|
|
206
|
+
* @param {{messageId?: number, now?: number}} [o]
|
|
207
|
+
*/
|
|
208
|
+
export async function onFileInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
209
|
+
const lang = langOf(st.userId);
|
|
210
|
+
// хвост слишком длинного содержимого, разбитого Telegram на несколько сообщений: агенту не передаём
|
|
211
|
+
if (st.swallowUntil && now < st.swallowUntil) {
|
|
212
|
+
await dropMessage(st, messageId);
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
const wait = st.pendingInput;
|
|
216
|
+
if (wait?.kind !== 'fileName' && wait?.kind !== 'fileContent') return false;
|
|
217
|
+
const expired = now - wait.at > FILE_WAIT_MS;
|
|
218
|
+
const project = projectOf(st);
|
|
219
|
+
|
|
220
|
+
if (wait.kind === 'fileContent') {
|
|
221
|
+
// это может быть секрет: что бы ни случилось, агенту текст не уходит, а сообщение удаляется
|
|
222
|
+
st.pendingInput = null;
|
|
223
|
+
await dropMessage(st, messageId);
|
|
224
|
+
if (expired || !project || !canManageFiles(st.userId)) return (await say(st.to, t('files.contentExpired', lang)), true);
|
|
225
|
+
if ([...text].length > INLINE_MAX) {
|
|
226
|
+
st.swallowUntil = now + SWALLOW_MS;
|
|
227
|
+
const markup = { inline_keyboard: [[{ text: t('files.upload', lang), callback_data: `fl:u:${pathToken(wait.dir)}` }]] };
|
|
228
|
+
return (await say(st.to, t('files.contentLong', lang, { max: INLINE_MAX }), { reply_markup: markup }), true);
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const r = writeProjectFile(project, wait.dir, wait.parts, text.endsWith('\n') ? text : `${text}\n`, { replace: wait.replace });
|
|
232
|
+
log('файл создан в проекте:', st.userId, r.path, `${r.size} Б`);
|
|
233
|
+
await say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
|
|
234
|
+
} catch (e) {
|
|
235
|
+
log('files: запись:', e.message, '| пользователь', st.userId);
|
|
236
|
+
await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
|
|
237
|
+
}
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// имя файла
|
|
242
|
+
if (expired) {
|
|
243
|
+
st.pendingInput = null;
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
if (!project || !canManageFiles(st.userId)) {
|
|
247
|
+
st.pendingInput = null;
|
|
248
|
+
return (await say(st.to, t('state.projectGone', lang)), true);
|
|
249
|
+
}
|
|
250
|
+
const parts = relPath(text);
|
|
251
|
+
if (!parts) return (await say(st.to, t('files.nameBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
252
|
+
let target;
|
|
253
|
+
try {
|
|
254
|
+
target = resolveTarget(project, wait.dir, parts);
|
|
255
|
+
} catch (e) {
|
|
256
|
+
return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), { ...HTML, reply_markup: cancelMarkup(lang) }), true);
|
|
257
|
+
}
|
|
258
|
+
st.pendingInput = null;
|
|
259
|
+
if (target.exists) await askReplace(st, project, { dir: wait.dir, parts }, lang);
|
|
260
|
+
else await askContent(st, project, { dir: wait.dir, parts }, lang);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Файл или фото от пользователя, пока бот ждёт загрузку в проект (кнопка «Загрузить файл»). Возвращает true, если
|
|
266
|
+
* файл сохранён в проект (или отклонён здесь): агенту он тогда не передаётся. Без ожидания — false: файл для агента.
|
|
267
|
+
*/
|
|
268
|
+
export async function onFileUpload(st, msg, now = Date.now()) {
|
|
269
|
+
const wait = st.pendingInput;
|
|
270
|
+
const waiting = wait?.kind === 'fileUpload' && now - wait.at <= FILE_WAIT_MS;
|
|
271
|
+
const album = msg.media_group_id && st.uploadGroup?.id === msg.media_group_id && now < st.uploadGroup.until;
|
|
272
|
+
if (!waiting && !album) return false;
|
|
273
|
+
const dir = waiting ? wait.dir : st.uploadGroup.dir;
|
|
274
|
+
if (waiting) st.pendingInput = null;
|
|
275
|
+
if (msg.media_group_id) st.uploadGroup = { id: msg.media_group_id, dir, until: now + ALBUM_MS };
|
|
276
|
+
const lang = langOf(st.userId);
|
|
277
|
+
const project = projectOf(st);
|
|
278
|
+
if (!project || !canManageFiles(st.userId)) return (await say(st.to, t('state.projectGone', lang)), true);
|
|
279
|
+
const meta = describeAttachment(msg);
|
|
280
|
+
if (!meta) return false;
|
|
281
|
+
if (meta.size > MAX_FILE_BYTES) return (await say(st.to, t('file.tooBig', lang)), true);
|
|
282
|
+
// имя — как у присланного файла (с точкой в начале, если она есть); непригодное заменяется безопасным
|
|
283
|
+
const parts = relPath(basename(String(meta.name).replace(/\\/g, '/'))) ?? relPath(safeFileName(meta.name));
|
|
284
|
+
if (!parts) return (await say(st.to, t('files.nameBad', lang)), true);
|
|
285
|
+
const job = { dir, parts, meta, messageId: msg.message_id };
|
|
286
|
+
try {
|
|
287
|
+
if (resolveTarget(project, dir, parts).exists) return (await askReplace(st, project, job, lang), true);
|
|
288
|
+
} catch (e) {
|
|
289
|
+
return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML), true);
|
|
290
|
+
}
|
|
291
|
+
await saveUpload(st, project, job, lang);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
package/src/i18n.mjs
CHANGED
|
@@ -242,6 +242,40 @@ const M = {
|
|
|
242
242
|
},
|
|
243
243
|
'proj.newFail': { en: '⚠️ Could not create the folder: {msg}', ru: '⚠️ Не удалось создать папку: {msg}', uk: '⚠️ Не вдалося створити папку: {msg}' },
|
|
244
244
|
'proj.newCancelled': { en: '✖ The project was not created.', ru: '✖ Проект не создан.', uk: '✖ Проєкт не створено.' },
|
|
245
|
+
// ---- /files: файлы проекта в обход агента ----
|
|
246
|
+
'menu.files': { en: "Project files: create, upload, delete (bypassing the agent)", ru: "Файлы проекта: создать, загрузить, удалить (в обход агента)", uk: "Файли проєкту: створити, завантажити, видалити (в обхід агента)" },
|
|
247
|
+
'help.files': { en: "/files — project files: create, upload or delete a file yourself, bypassing the agent", ru: "/files — файлы проекта: создать, загрузить или удалить файл самому, в обход агента", uk: "/files — файли проєкту: створити, завантажити або видалити файл самому, в обхід агента" },
|
|
248
|
+
'start.btn.files': { en: "📄 Files", ru: "📄 Файлы", uk: "📄 Файли" },
|
|
249
|
+
'files.head': { en: "📄 Project files: {p}\nFolder: {dir}", ru: "📄 Файлы проекта: {p}\nПапка: {dir}", uk: "📄 Файли проєкту: {p}\nПапка: {dir}" },
|
|
250
|
+
'files.hint': { en: "A file you create or upload here goes straight into the project folder — the agent does not get its contents in a message. Use it for secrets (.env, keys). To show a file to the agent, just send it to the chat as usual.", ru: "Файл, созданный или загруженный здесь, попадает прямо в папку проекта — агент не получает его содержимое в сообщении. Так передают секреты (.env, ключи). Чтобы показать файл агенту, просто отправьте его в чат, как обычно.", uk: "Файл, створений або завантажений тут, потрапляє прямо в папку проєкту — агент не отримує його вміст у повідомленні. Так передають секрети (.env, ключі). Щоб показати файл агенту, просто надішліть його в чат, як зазвичай." },
|
|
251
|
+
'files.empty': { en: "(no files here yet)", ru: "(файлов здесь пока нет)", uk: "(файлів тут поки немає)" },
|
|
252
|
+
'files.create': { en: "📝 Create file", ru: "📝 Создать файл", uk: "📝 Створити файл" },
|
|
253
|
+
'files.upload': { en: "⬆️ Upload file", ru: "⬆️ Загрузить файл", uk: "⬆️ Завантажити файл" },
|
|
254
|
+
'files.back': { en: "← Back to the list", ru: "← К списку", uk: "← До списку" },
|
|
255
|
+
'files.delete': { en: "🗑 Delete", ru: "🗑 Удалить", uk: "🗑 Видалити" },
|
|
256
|
+
'files.deleteYes': { en: "Yes, delete", ru: "Да, удалить", uk: "Так, видалити" },
|
|
257
|
+
'files.card': { en: "📄 {path}\nSize: {size}\nChanged: {when}", ru: "📄 {path}\nРазмер: {size}\nИзменён: {when}", uk: "📄 {path}\nРозмір: {size}\nЗмінено: {when}" },
|
|
258
|
+
'files.deleteAsk': { en: "🗑 Delete the file {path} ({size})? It cannot be restored.", ru: "🗑 Удалить файл {path} ({size})? Восстановить его будет нельзя.", uk: "🗑 Видалити файл {path} ({size})? Відновити його буде неможливо." },
|
|
259
|
+
'files.deleted': { en: "Deleted: {name}", ru: "Удалён: {name}", uk: "Видалено: {name}" },
|
|
260
|
+
'files.nameAsk': { en: "📝 Send the file name. It will be created in the folder {dir}. A subfolder is allowed: config/.env", ru: "📝 Отправьте имя файла. Он будет создан в папке {dir}. Можно с подпапкой: config/.env", uk: "📝 Надішліть ім’я файлу. Його буде створено в папці {dir}. Можна з підпапкою: config/.env" },
|
|
261
|
+
'files.nameBad': { en: "⚠️ This name will not work. Use a name like .env or config/settings.json: no “..”, no absolute paths, no characters < > : \" | ? *. Send another name.", ru: "⚠️ Такое имя не подойдёт. Нужно имя вроде .env или config/settings.json: без «..», без абсолютных путей и символов < > : \" | ? *. Отправьте другое имя.", uk: "⚠️ Таке ім’я не підійде. Потрібне ім’я на кшталт .env або config/settings.json: без «..», без абсолютних шляхів і символів < > : \" | ? *. Надішліть інше ім’я." },
|
|
262
|
+
'files.contentAsk': { en: "📝 Now send the contents of {path} in one message. It will not be passed to the agent, and the message will be deleted from the chat after saving.", ru: "📝 Теперь отправьте содержимое файла {path} одним сообщением. Агенту оно не передаётся, а сообщение после сохранения удалится из чата.", uk: "📝 Тепер надішліть вміст файлу {path} одним повідомленням. Агенту він не передається, а повідомлення після збереження видалиться з чату." },
|
|
263
|
+
'files.contentExpired': { en: "⚠️ The wait for the file contents has ended. Your message was deleted: nothing was saved and nothing was sent to the agent. Start again: /files", ru: "⚠️ Ожидание содержимого файла закончилось. Ваше сообщение удалено: ничего не сохранено и агенту не отправлено. Начните заново: /files", uk: "⚠️ Очікування вмісту файлу завершилося. Ваше повідомлення видалено: нічого не збережено й агенту не надіслано. Почніть знову: /files" },
|
|
264
|
+
'files.contentLong': { en: "⚠️ The text is longer than {max} characters — Telegram splits such a message into parts. It was deleted: nothing was saved and nothing was sent to the agent. Upload it as a file:", ru: "⚠️ Текст длиннее {max} символов — такое сообщение Telegram делит на части. Оно удалено: ничего не сохранено и агенту не отправлено. Загрузите его файлом:", uk: "⚠️ Текст довший за {max} символів — таке повідомлення Telegram ділить на частини. Його видалено: нічого не збережено й агенту не надіслано. Завантажте його файлом:" },
|
|
265
|
+
'files.uploadAsk': { en: "⬆️ Send the file as a document. It will be saved to the folder {dir} under its own name and will not be passed to the agent.", ru: "⬆️ Отправьте файл документом. Он сохранится в папку {dir} под своим именем и агенту передан не будет.", uk: "⬆️ Надішліть файл документом. Він збережеться в папку {dir} під своїм ім’ям і агенту переданий не буде." },
|
|
266
|
+
'files.saved': { en: "✅ Saved to the project: {path} ({size}). The agent did not receive the contents; your message was deleted from the chat.", ru: "✅ Сохранено в проект: {path} ({size}). Агент содержимое не получал; ваше сообщение удалено из чата.", uk: "✅ Збережено в проєкт: {path} ({size}). Агент вміст не отримував; ваше повідомлення видалено з чату." },
|
|
267
|
+
'files.saveFail': { en: "⚠️ The file was not saved: {why}", ru: "⚠️ Файл не сохранён: {why}", uk: "⚠️ Файл не збережено: {why}" },
|
|
268
|
+
'files.existsAsk': { en: "⚠️ The file {path} already exists. Replace it?", ru: "⚠️ Файл {path} уже есть. Заменить его?", uk: "⚠️ Файл {path} уже є. Замінити його?" },
|
|
269
|
+
'files.replace': { en: "Replace", ru: "Заменить", uk: "Замінити" },
|
|
270
|
+
'files.replacing': { en: "Replacing {path}", ru: "Заменяю {path}", uk: "Замінюю {path}" },
|
|
271
|
+
'files.cancelled': { en: "✖ Cancelled.", ru: "✖ Отменено.", uk: "✖ Скасовано." },
|
|
272
|
+
'files.noRights': { en: "Your access level does not allow changing project files.", ru: "Ваш уровень доступа не позволяет менять файлы проекта.", uk: "Ваш рівень доступу не дозволяє змінювати файли проєкту." },
|
|
273
|
+
'files.err.outside': { en: "the path is outside the project", ru: "путь лежит вне проекта", uk: "шлях розташований поза проєктом" },
|
|
274
|
+
'files.err.link': { en: "there is a link at this path — the bot does not write through links", ru: "по этому пути лежит ссылка — через ссылки бот не пишет", uk: "за цим шляхом лежить посилання — через посилання бот не пише" },
|
|
275
|
+
'files.err.notdir': { en: "a file is in the place of the folder", ru: "на месте папки лежит файл", uk: "на місці папки лежить файл" },
|
|
276
|
+
'files.err.isdir': { en: "there is a folder with this name", ru: "с таким именем уже есть папка", uk: "з таким ім’ям уже є папка" },
|
|
277
|
+
'files.err.exists': { en: "such a file already exists", ru: "такой файл уже есть", uk: "такий файл уже є" },
|
|
278
|
+
'files.err.missing': { en: "the file is no longer there", ru: "файла уже нет", uk: "файлу вже немає" },
|
|
245
279
|
'proj.notFound': { en: '⚠️ The folder was not found or is unavailable', ru: '⚠️ Папка не найдена или недоступна', uk: '⚠️ Папку не знайдено або вона недоступна' },
|
|
246
280
|
'proj.same': { en: '📁 Project already selected: {p}', ru: '📁 Проект уже выбран: {p}', uk: '📁 Проєкт уже обрано: {p}' },
|
|
247
281
|
'proj.set': { en: '📁 Project: {p}\nA new session starts with the next request.', ru: '📁 Проект: {p}\nНовая сессия начнётся со следующего запроса.', uk: '📁 Проєкт: {p}\nНова сесія почнеться з наступного запиту.' },
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Файлы проекта, которыми пользователь управляет сам, в обход агента (/files): список, создание, загрузка, удаление.
|
|
2
|
+
// Так в проект попадают секреты (.env, ключи): содержимое не проходит через запрос к модели.
|
|
3
|
+
//
|
|
4
|
+
// Все операции работают только внутри папки проекта и не ходят по ссылкам: агент пишет в ту же папку и мог бы подложить
|
|
5
|
+
// ссылку «.env → файл вне проекта», чтобы бот (он работает без песочницы) перезаписал чужой файл.
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { isWithin } from './projects.mjs';
|
|
10
|
+
|
|
11
|
+
/** Наибольшая длина одного имени в пути и наибольшая вложенность. */
|
|
12
|
+
export const NAME_MAX = 100;
|
|
13
|
+
export const DEPTH_MAX = 8;
|
|
14
|
+
|
|
15
|
+
// В эти папки бот не пишет и их не показывает: служебные данные git и тяжёлые каталоги зависимостей
|
|
16
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', 'renv', 'packrat', 'site-packages']);
|
|
17
|
+
|
|
18
|
+
/** Ошибка операции с файлом проекта: code — причина для сообщения пользователю (ключ files.err.<code>). */
|
|
19
|
+
export class FileError extends Error {
|
|
20
|
+
constructor(code, message = code) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.code = code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Относительный путь файла из текста пользователя: «.env», «config/.env», «docs\notes.txt».
|
|
28
|
+
* Возвращает части пути или null, если путь не подходит: абсолютный, с «..», с запрещёнными символами, в служебной папке.
|
|
29
|
+
* Имена с точки (.env, .Renviron) разрешены — ради них это и сделано.
|
|
30
|
+
*/
|
|
31
|
+
export function relPath(input) {
|
|
32
|
+
const raw = String(input ?? '').trim().replace(/\\/g, '/');
|
|
33
|
+
if (!raw || raw.startsWith('/') || /^[A-Za-z]:/.test(raw) || raw.startsWith('~')) return null;
|
|
34
|
+
const parts = raw.split('/').map((s) => s.trim());
|
|
35
|
+
if (parts.length > DEPTH_MAX) return null;
|
|
36
|
+
for (const p of parts) {
|
|
37
|
+
if (!p || p === '.' || p === '..' || [...p].length > NAME_MAX) return null;
|
|
38
|
+
// eslint-disable-next-line no-control-regex -- управляющие символы в имени файла недопустимы
|
|
39
|
+
if (/[\u0000-\u001f<>:"|?*]/.test(p) || /[. ]$/.test(p)) return null;
|
|
40
|
+
if (/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(p)) return null;
|
|
41
|
+
if (SKIP_DIRS.has(p.toLowerCase())) return null;
|
|
42
|
+
}
|
|
43
|
+
return parts;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const lstat = (p) => {
|
|
47
|
+
try {
|
|
48
|
+
return lstatSync(p);
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (e.code === 'ENOENT') return null;
|
|
51
|
+
throw e;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** Настоящий путь папки проекта; папка dir должна лежать в нём (иначе FileError 'outside'). */
|
|
56
|
+
function inProject(project, dir) {
|
|
57
|
+
let root;
|
|
58
|
+
let real;
|
|
59
|
+
try {
|
|
60
|
+
root = realpathSync.native(project);
|
|
61
|
+
real = realpathSync.native(dir);
|
|
62
|
+
} catch {
|
|
63
|
+
throw new FileError('outside');
|
|
64
|
+
}
|
|
65
|
+
if (!isWithin(real, root) || !lstatSync(real).isDirectory()) throw new FileError('outside');
|
|
66
|
+
return { root, real };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Куда ляжет файл: проходит по частям пути от папки dir, не заходя в ссылки. create — создавать недостающие папки.
|
|
71
|
+
* @returns {{path: string, dir: string, exists: boolean}} path — полный путь файла; exists — такой файл уже есть
|
|
72
|
+
*/
|
|
73
|
+
export function resolveTarget(project, dir, parts, { create = false } = {}) {
|
|
74
|
+
const { real } = inProject(project, dir);
|
|
75
|
+
let cur = real;
|
|
76
|
+
for (const name of parts.slice(0, -1)) {
|
|
77
|
+
cur = join(cur, name);
|
|
78
|
+
const st = lstat(cur);
|
|
79
|
+
if (!st) {
|
|
80
|
+
if (!create) return { path: join(real, ...parts), dir: null, exists: false };
|
|
81
|
+
mkdirSync(cur);
|
|
82
|
+
} else if (!st.isDirectory()) throw new FileError(st.isSymbolicLink() ? 'link' : 'notdir'); // ссылка или файл на месте папки
|
|
83
|
+
}
|
|
84
|
+
const path = join(cur, parts.at(-1));
|
|
85
|
+
const st = lstat(path);
|
|
86
|
+
if (st && !st.isFile()) throw new FileError(st.isSymbolicLink() ? 'link' : 'isdir');
|
|
87
|
+
return { path, dir: cur, exists: Boolean(st) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Записывает файл проекта. Содержимое пишется во временный файл рядом и переименованием встаёт на место: так ссылка,
|
|
92
|
+
* подложенная на месте файла, заменяется самим файлом, а не ведёт запись наружу. Существующий файл без replace не трогается.
|
|
93
|
+
* @param {string} project папка проекта
|
|
94
|
+
* @param {string} dir папка внутри проекта, от которой задан путь
|
|
95
|
+
* @param {string[]} parts части пути (relPath)
|
|
96
|
+
* @param {Buffer|string} data
|
|
97
|
+
* @returns {{path: string, size: number, replaced: boolean}}
|
|
98
|
+
*/
|
|
99
|
+
export function writeProjectFile(project, dir, parts, data, { replace = false } = {}) {
|
|
100
|
+
const { root } = inProject(project, dir);
|
|
101
|
+
const target = resolveTarget(project, dir, parts, { create: true });
|
|
102
|
+
if (target.exists && !replace) throw new FileError('exists');
|
|
103
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8');
|
|
104
|
+
const tmp = join(target.dir, `.acpgram-${randomBytes(6).toString('hex')}.tmp`);
|
|
105
|
+
const fd = openSync(tmp, 'wx', 0o600); // 'wx' не идёт по ссылке и не затирает существующее
|
|
106
|
+
try {
|
|
107
|
+
// папку могли подменить ссылкой между проверкой и открытием: файл должен лежать в проекте, иначе ничего не пишем
|
|
108
|
+
if (!isWithin(realpathSync.native(tmp), root)) throw new FileError('outside');
|
|
109
|
+
writeSync(fd, buf);
|
|
110
|
+
} catch (e) {
|
|
111
|
+
closeSync(fd);
|
|
112
|
+
try {
|
|
113
|
+
unlinkSync(tmp);
|
|
114
|
+
} catch {
|
|
115
|
+
/* временный файл уже исчез */
|
|
116
|
+
}
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
closeSync(fd);
|
|
120
|
+
renameSync(tmp, target.path);
|
|
121
|
+
return { path: target.path, size: buf.length, replaced: target.exists };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Удаляет файл проекта (только обычный файл, не папку и не ссылку). */
|
|
125
|
+
export function deleteProjectFile(project, path) {
|
|
126
|
+
const { root } = inProject(project, join(path, '..'));
|
|
127
|
+
const st = lstat(path);
|
|
128
|
+
if (!st) throw new FileError('missing');
|
|
129
|
+
if (!st.isFile()) throw new FileError(st.isSymbolicLink() ? 'link' : 'isdir');
|
|
130
|
+
if (!isWithin(realpathSync.native(path), root)) throw new FileError('outside');
|
|
131
|
+
unlinkSync(path);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Содержимое папки проекта: папки и файлы по алфавиту, со скрытыми файлами (.env), без ссылок и служебных папок.
|
|
136
|
+
* @returns {{dirs: string[], files: {name: string, size: number, mtime: number}[]}}
|
|
137
|
+
*/
|
|
138
|
+
export function listProjectDir(project, dir) {
|
|
139
|
+
const { real } = inProject(project, dir);
|
|
140
|
+
const dirs = [];
|
|
141
|
+
const files = [];
|
|
142
|
+
for (const d of readdirSync(real, { withFileTypes: true })) {
|
|
143
|
+
if (d.isSymbolicLink() || d.name.endsWith('.tmp') && d.name.startsWith('.acpgram-')) continue;
|
|
144
|
+
if (d.isDirectory()) {
|
|
145
|
+
if (!SKIP_DIRS.has(d.name.toLowerCase())) dirs.push(d.name);
|
|
146
|
+
} else if (d.isFile()) {
|
|
147
|
+
const st = lstat(join(real, d.name));
|
|
148
|
+
if (st) files.push({ name: d.name, size: st.size, mtime: st.mtimeMs });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const byName = (a, b) => a.localeCompare(b, 'ru');
|
|
152
|
+
return { dirs: dirs.sort(byName), files: files.sort((a, b) => byName(a.name, b.name)) };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Сведения о файле проекта для его карточки или null, если это не обычный файл внутри проекта. */
|
|
156
|
+
export function projectFileInfo(project, path) {
|
|
157
|
+
try {
|
|
158
|
+
const { root } = inProject(project, join(path, '..'));
|
|
159
|
+
const st = lstat(path);
|
|
160
|
+
if (!st?.isFile() || !isWithin(realpathSync.native(path), root)) return null;
|
|
161
|
+
return { size: st.size, mtime: st.mtimeMs };
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Размер для человека: «812 B», «3.4 KB», «1.2 MB». */
|
|
168
|
+
export const fmtSize = (n) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`);
|
package/src/projectsUi.mjs
CHANGED
|
@@ -49,6 +49,11 @@ function tok(p) {
|
|
|
49
49
|
return tk;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/** Токен пути для кнопок других экранов (/files). Путь из токена обязан проверять тот, кто его использует. */
|
|
53
|
+
export const pathToken = tok;
|
|
54
|
+
/** Путь по токену из кнопки или undefined, если кнопка устарела. */
|
|
55
|
+
export const tokenPath = (tk) => pathByTok.get(Number(tk));
|
|
56
|
+
|
|
52
57
|
/** Путь для показа пользователю диалога: относительно его корня (личное пространство — без пути на сервере). */
|
|
53
58
|
const pathFor = (st, p, lang) => showPath(p, lang, rootOf(st.userId));
|
|
54
59
|
|
package/src/turn.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Один запрос пользователя: черновик со стримингом, ход работы, запросы разрешений, итоговый ответ.
|
|
2
2
|
import { mkdirSync } from 'node:fs';
|
|
3
3
|
import { db, dbg, langOf, log, say } from './ctx.mjs';
|
|
4
|
-
import { FILE_PLACEHOLDER, attachFiles, buildPromptBlocks, extractSendMarks, outboxDir, stripSendMarks } from './files.mjs';
|
|
4
|
+
import { FILE_PLACEHOLDER, SECRETS_NOTE, attachFiles, buildPromptBlocks, extractSendMarks, outboxDir, stripSendMarks } from './files.mjs';
|
|
5
5
|
import { ModelAccessError, choiceName, getCatalog, syncSelection } from './access.mjs';
|
|
6
6
|
import { parseUsage, permissionOptions } from './engines.mjs';
|
|
7
7
|
import { SESSION_OPTION_ID, allowOnceOption, describeRule, permissionKeys, rulesAllow, withSessionOption } from './permRules.mjs';
|
|
@@ -343,7 +343,7 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
|
|
|
343
343
|
// (агент мог сжать контекст и забыть её), а не в каждом — она попадает в историю и тратит токены
|
|
344
344
|
const noteNow = (a.promptCount ?? 0) % OUTBOX_NOTE_EVERY === 0;
|
|
345
345
|
a.promptCount = (a.promptCount ?? 0) + 1;
|
|
346
|
-
const blocks = buildPromptBlocks({ text, files, caps: a.caps, outbox: noteNow ? outbox : null, quote, notes: noteNow ? [ASK_NOTE] : [] });
|
|
346
|
+
const blocks = buildPromptBlocks({ text, files, caps: a.caps, outbox: noteNow ? outbox : null, quote, notes: noteNow ? [ASK_NOTE, SECRETS_NOTE] : [] });
|
|
347
347
|
// новая тема без названия: агент начинает ответ строкой с названием, бот называет так тему
|
|
348
348
|
if (naming) blocks.push({ type: 'text', text: TITLE_NOTE });
|
|
349
349
|
const res = await a.prompt(blocks);
|
package/src/ui.mjs
CHANGED
|
@@ -740,6 +740,7 @@ export function startView({ level, project, engine, model, isAdmin, note, topics
|
|
|
740
740
|
const cmd = (key) => t(`help.${key}`, lang);
|
|
741
741
|
const commands = [
|
|
742
742
|
cmd('project'),
|
|
743
|
+
cmd('files'),
|
|
743
744
|
cmd('engine'),
|
|
744
745
|
cmd('model'),
|
|
745
746
|
cmd('new'),
|
|
@@ -754,7 +755,7 @@ export function startView({ level, project, engine, model, isAdmin, note, topics
|
|
|
754
755
|
`<tg-button-row>${button(t('start.btn.project', lang), 'ui:project')}${button(t('start.btn.new', lang), 'ui:new')}${button(t('start.btn.sessions', lang), 'ui:sessions')}</tg-button-row>`,
|
|
755
756
|
`<tg-button-row>${button(t('start.btn.engine', lang), 'ui:engine')}${button(t('start.btn.model', lang), 'ui:model')}${button(t('start.btn.close', lang), 'ui:close')}</tg-button-row>`,
|
|
756
757
|
// topics: 'on' | 'off' — режим «диалоги» (если у бота включены темы), null — кнопки нет
|
|
757
|
-
`<tg-button-row>${button(t('btn.language', lang), 'ui:language')}${topics ? button(t(topics === 'on' ? 'start.btn.topicsOn' : 'start.btn.topicsOff', lang), 'ui:topics') : ''}</tg-button-row>`,
|
|
758
|
+
`<tg-button-row>${button(t('start.btn.files', lang), 'ui:files')}${button(t('btn.language', lang), 'ui:language')}${topics ? button(t(topics === 'on' ? 'start.btn.topicsOn' : 'start.btn.topicsOff', lang), 'ui:topics') : ''}</tg-button-row>`,
|
|
758
759
|
];
|
|
759
760
|
if (isAdmin) rows.push(`<tg-button-row>${button(t('start.btn.users', lang), 'ui:users')}${button(t('start.btn.invite', lang), 'ui:invite')}${button(t('start.btn.active', lang), 'ui:active')}</tg-button-row>`);
|
|
760
761
|
return [
|