acpgram 1.24.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 +47 -3
- package/README.ru.md +47 -2
- package/package.json +1 -1
- package/src/access.mjs +6 -3
- package/src/bot.mjs +47 -5
- package/src/cli-i18n.mjs +17 -0
- package/src/engines.mjs +20 -3
- package/src/files.mjs +11 -0
- package/src/filesUi.mjs +293 -0
- package/src/i18n.mjs +39 -0
- package/src/projectFiles.mjs +168 -0
- package/src/projectsUi.mjs +5 -0
- package/src/sandbox.mjs +253 -0
- package/src/setup.mjs +13 -0
- package/src/state.mjs +22 -2
- package/src/turn.mjs +2 -2
- package/src/ui.mjs +2 -1
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Нова сесія почнеться з наступного запиту.' },
|
|
@@ -367,6 +401,11 @@ const M = {
|
|
|
367
401
|
ru: '⚠️ Папка проекта недоступна: её удалили или переместили. Выберите проект: /project',
|
|
368
402
|
uk: '⚠️ Папка проєкту недоступна: її видалили або перемістили. Оберіть проєкт: /project',
|
|
369
403
|
},
|
|
404
|
+
'state.sandboxFail': {
|
|
405
|
+
en: '⚠️ The agent could not be started in the sandbox for this project. Please tell the administrator.',
|
|
406
|
+
ru: '⚠️ Не удалось запустить агента в песочнице для этого проекта. Сообщите администратору.',
|
|
407
|
+
uk: '⚠️ Не вдалося запустити агента в пісочниці для цього проєкту. Повідомте адміністратора.',
|
|
408
|
+
},
|
|
370
409
|
// ---- режим «диалоги»: темы в личном чате с ботом ----
|
|
371
410
|
'menu.topics': { en: 'Dialogs mode: each chat topic is a separate dialog', ru: 'Режим «диалоги»: каждая тема чата — отдельный диалог', uk: 'Режим «діалоги»: кожна тема чату — окремий діалог' },
|
|
372
411
|
'help.topics': { en: '/topics — dialogs mode: each topic of this chat is a separate dialog with the agent', ru: '/topics — режим «диалоги»: каждая тема этого чата — отдельный диалог с агентом', uk: '/topics — режим «діалоги»: кожна тема цього чату — окремий діалог з агентом' },
|
|
@@ -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
|
|