acpgram 1.32.1 → 1.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.32.1",
3
+ "version": "1.33.1",
4
4
  "type": "module",
5
5
  "description": "Telegram gateway to AI coding agents (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) over the Agent Client Protocol",
6
6
  "license": "MIT",
package/src/acp.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  // Минимальный клиент Agent Client Protocol (JSON-RPC 2.0, построчный JSON по stdin/stdout)
2
2
  // для запуска ACP-агента (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) как подпроцесса. Движки — в engines.mjs.
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
- import readline from 'node:readline';
5
4
  import { i18nError } from './i18n.mjs';
6
5
  import { logError } from './log.mjs';
7
6
  import { resolveProgram } from './winsvc.mjs';
@@ -105,6 +104,61 @@ export function quietStderrFilter(line = null, block = null) {
105
104
  };
106
105
  }
107
106
 
107
+ /** Предел длины одной строки stdout/stderr агента: без него readline копил бы гигабайты до перевода строки. */
108
+ export const MAX_LINE_BYTES = 32 * 1024 * 1024;
109
+ const MAX_LINE_MB = Math.round(MAX_LINE_BYTES / 1024 / 1024);
110
+
111
+ /**
112
+ * Построчное чтение потока с жёстким пределом длины строки. После превышения остаток потока не накапливается
113
+ * (и не разбирается), а вызывается onOverflow — вызывающий решает, остановить агента или только написать в журнал.
114
+ */
115
+ export function readLines(stream, onLine, { maxBytes = MAX_LINE_BYTES, onOverflow } = {}) {
116
+ stream.setEncoding('utf8');
117
+ let buf = '';
118
+ let bytes = 0;
119
+ let overflowed = false;
120
+ const overflow = () => {
121
+ if (overflowed) return;
122
+ overflowed = true;
123
+ buf = '';
124
+ bytes = 0;
125
+ onOverflow?.(maxBytes);
126
+ };
127
+ const push = (part) => {
128
+ if (overflowed || !part) return;
129
+ const n = Buffer.byteLength(part);
130
+ if (bytes + n > maxBytes) return overflow();
131
+ buf += part;
132
+ bytes += n;
133
+ };
134
+ const emit = () => {
135
+ if (overflowed) return;
136
+ const line = buf.endsWith('\r') ? buf.slice(0, -1) : buf;
137
+ buf = '';
138
+ bytes = 0;
139
+ onLine?.(line);
140
+ };
141
+ stream.on('data', (chunk) => {
142
+ if (overflowed) return;
143
+ let rest = String(chunk);
144
+ for (;;) {
145
+ const i = rest.indexOf('\n');
146
+ if (i < 0) {
147
+ push(rest);
148
+ return;
149
+ }
150
+ push(rest.slice(0, i));
151
+ if (overflowed) return;
152
+ emit();
153
+ rest = rest.slice(i + 1);
154
+ }
155
+ });
156
+ stream.on('end', () => {
157
+ if (!overflowed && (buf || bytes)) emit();
158
+ });
159
+ stream.on('error', (e) => logError('[acp] поток агента:', e.message));
160
+ }
161
+
108
162
  export class AcpAgent {
109
163
  /**
110
164
  * @param {object} o
@@ -140,10 +194,18 @@ export class AcpAgent {
140
194
  // окружение задаётся целиком: с окружением бота не смешивается, иначе в него вернулся бы токен бота
141
195
  this.proc = spawnCommand(this.command, this.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], ...(this.env ? { env: this.env } : {}) });
142
196
  // ошибка разбора одной строки агента не должна ронять бота (обработчик асинхронный: без catch это необработанное отклонение)
143
- readline.createInterface({ input: this.proc.stdout }).on('line', (l) => this.#onLine(l).catch((e) => logError(`[${this.name}] строка агента не обработана:`, e.message)));
197
+ readLines(this.proc.stdout, (l) => this.#onLine(l).catch((e) => logError(`[${this.name}] строка агента не обработана:`, e.message)), {
198
+ onOverflow: () => {
199
+ logError(`[${this.name}] строка длиннее ${MAX_LINE_MB} МБ — агент завершён`);
200
+ killTree(this.proc);
201
+ this.#finish(null, () => i18nError(`${this.name}: строка агента больше ${MAX_LINE_MB} МБ`, 'err.agentLineTooLong', { engine: this.name, mb: MAX_LINE_MB }));
202
+ },
203
+ });
144
204
  const skip = quietStderrFilter(this.quietStderr, this.quietStderrBlock);
145
- readline.createInterface({ input: this.proc.stderr }).on('line', (l) => {
205
+ readLines(this.proc.stderr, (l) => {
146
206
  if (!skip(l)) logError(`[${this.name}:stderr]`, l);
207
+ }, {
208
+ onOverflow: () => logError(`[${this.name}:stderr] строка длиннее ${MAX_LINE_MB} МБ — дальнейший вывод игнорируется`),
147
209
  });
148
210
  // запись в уже завершившийся процесс (EPIPE) не должна ронять бота
149
211
  this.proc.stdin.on('error', (e) => logError('[acp] stdin:', e.message));
package/src/admin.mjs CHANGED
@@ -13,7 +13,25 @@ import { isNotModified, tg } from './telegram.mjs';
13
13
  const INVITE_TTL_MS = 24 * 3600_000;
14
14
  const REQUEST_COOLDOWN_MS = 3600_000; // повторный запрос доступа от одного человека — не чаще раза в час
15
15
  const NOTICE_COOLDOWN_MS = 10 * 60_000; // напоминание «запрос уже отправлен» — не чаще раза в 10 минут
16
+ const STRANGER_REPLY_COOLDOWN_MS = 5 * 60_000; // незнакомцу — не больше одного ответа за любое число попыток
17
+ const ADMIN_NOTICE_COOLDOWN_MS = 3600_000; // все запросы доступа за час складываются в одно уведомление администратору
16
18
  const lastNotice = new Map();
19
+ const lastStrangerReply = new Map();
20
+ let lastAdminNoticeAt = 0;
21
+
22
+ /** Чистит кэши времени ответов и уведомлений, чтобы они не росли вместе с числом обращений. */
23
+ export function sweepUnknownUsers(maxAgeMs = 24 * 3600_000) {
24
+ const until = Date.now() - maxAgeMs;
25
+ let n = 0;
26
+ for (const map of [lastNotice, lastStrangerReply]) {
27
+ for (const [id, at] of map) {
28
+ if (at > until) continue;
29
+ map.delete(id);
30
+ n++;
31
+ }
32
+ }
33
+ return n;
34
+ }
17
35
 
18
36
  /** Язык администратора: все его экраны и уведомления ему. */
19
37
  const adminLang = () => langOf(ADMIN_ID);
@@ -32,6 +50,9 @@ const grantedText = (level, lang, byAdmin) => t(byAdmin ? 'access.grantedByAdmin
32
50
 
33
51
  /** Сообщение от человека без доступа: подключение по приглашению или запрос доступа администратору. */
34
52
  export async function handleUnknownUser(from, chatId, text) {
53
+ const now = Date.now();
54
+ if (now - (lastStrangerReply.get(from.id) ?? 0) < STRANGER_REPLY_COOLDOWN_MS) return;
55
+ lastStrangerReply.set(from.id, now);
35
56
  const lang = langOf(from.id);
36
57
  const m = /^\/start(?:@\w+)?\s+(\S+)$/.exec(text || '');
37
58
  if (m) {
@@ -61,6 +82,8 @@ export async function handleUnknownUser(from, chatId, text) {
61
82
  const prev = db.getUser(from.id);
62
83
  const al = adminLang();
63
84
  await say(chatId, t('access.requestSent', lang));
85
+ if (Date.now() - lastAdminNoticeAt < ADMIN_NOTICE_COOLDOWN_MS) return;
86
+ lastAdminNoticeAt = Date.now();
64
87
  return say(ADMIN_ID, t('adm.reqNew', al, { who: who(from), id: from.id, note: prev?.status === 'revoked' ? t('adm.reqRevokedBefore', al) : '', msg: (text || '').slice(0, 200) }), {
65
88
  reply_markup: {
66
89
  inline_keyboard: [
@@ -160,6 +183,7 @@ export async function onAdminCallback(cb) {
160
183
  if (!isLevel(a)) return ack();
161
184
  const code = randomBytes(9).toString('base64url');
162
185
  db.createInvite(code, a, ADMIN_ID, new Date(Date.now() + INVITE_TTL_MS).toISOString());
186
+ log('приглашение создано: уровень', a, '| администратор', ADMIN_ID);
163
187
  await ack();
164
188
  return edit(t('adm.inviteMade', al, { level: levelName(a, al), bot: botInfo.username, code }));
165
189
  }
@@ -172,6 +196,7 @@ export async function onAdminCallback(cb) {
172
196
  const name = userName({ user_id: id, username: req.username, first_name: req.first_name });
173
197
  if (action === 'd') {
174
198
  db.setRequestStatus(id, 'rejected');
199
+ log('доступ отклонён:', id, '| администратор', ADMIN_ID);
175
200
  await ack();
176
201
  await say(id, t('access.rejectedByAdmin', langOf(id)));
177
202
  return edit(t('adm.reqRejected', al, { name }));
package/src/bot.mjs CHANGED
@@ -7,8 +7,8 @@ import { SANDBOX, checkInSandbox, probeSandbox } from './sandbox.mjs';
7
7
  import { handleEngine, onEngineCallback } from './engineUi.mjs';
8
8
  import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './access.mjs';
9
9
  import { handleModel, onModelCallback } from './modelUi.mjs';
10
- import { ADMIN_ID, DATA_DIR, HISTORY_KEEP_DAYS, IDLE_MINUTES, LEVEL_KEYS, LOGS_KEEP_DAYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
11
- import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from './admin.mjs';
10
+ import { ADMIN_ID, DATA_DIR, HISTORY_KEEP_DAYS, IDLE_MINUTES, LEVEL_KEYS, LOGS_KEEP_DAYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang, sweepLangCache } from './ctx.mjs';
11
+ import { adminCommand, handleUnknownUser, onAdminCallback, sweepUnknownUsers, welcomeNote } from './admin.mjs';
12
12
  import { LANGS, LANG_CODES, LANG_PICK, LOCALES, errText, normLang, t } from './i18n.mjs';
13
13
  import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
14
14
  import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
@@ -17,7 +17,7 @@ import { checkGit, gitCommand } from './git.mjs';
17
17
  import { GIT_AGENT_AUTH, tokenReminders } from './gitAccess.mjs';
18
18
  import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
19
19
  import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
20
- import { ADMIN_SANDBOX, dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
20
+ import { ADMIN_SANDBOX, dropPermissions, errorRootOf, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
21
21
  import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
22
22
  import { deleteTopic, isAutoTopicCommand, topicInfoOf } from './topics.mjs';
23
23
  import { setSyncKill } from './acp.mjs';
@@ -34,11 +34,14 @@ import { createQueue } from './queue.mjs';
34
34
  import { directorySize, fitsUpload, freeBytes } from './quota.mjs';
35
35
  import { forceStopAfter } from './forceStop.mjs';
36
36
  import { looksLikeSecret } from './pending.mjs';
37
- import { cleanupLogs } from './log.mjs';
37
+ import { cleanupLogs, logError } from './log.mjs';
38
38
  import { maybeNotifySafety } from './warnings.mjs';
39
39
 
40
40
  const UPLOADS_QUOTA_MB = positiveEnv('UPLOADS_QUOTA_MB', 0);
41
41
  const MIN_FREE_MB = positiveEnv('MIN_FREE_MB', 100);
42
+ const UPDATE_LIMIT = 20; // обновлений от одного пользователя в окне ниже: защита от зациклившегося клиента
43
+ const UPDATE_WINDOW_MS = 10_000;
44
+ const updateHits = new Map();
42
45
  const receiveQueue = createQueue(1);
43
46
  const reservedUploads = new Map();
44
47
 
@@ -50,6 +53,33 @@ if (!process.env.TELEGRAM_BOT_TOKEN || !ADMIN_ID) {
50
53
  /** Есть ли у пользователя доступ: администратор или активный сотрудник. */
51
54
  const hasAccess = (id) => isAdmin(id) || db.getUser(id)?.status === 'active';
52
55
 
56
+ /** Ограничение частоты обновлений: 20 событий за 10 секунд от одного пользователя. */
57
+ function tooManyUpdates(id) {
58
+ const now = Date.now();
59
+ const hits = (updateHits.get(id) ?? []).filter((at) => now - at < UPDATE_WINDOW_MS);
60
+ if (hits.length >= UPDATE_LIMIT) {
61
+ updateHits.set(id, hits);
62
+ return true;
63
+ }
64
+ hits.push(now);
65
+ updateHits.set(id, hits);
66
+ return false;
67
+ }
68
+
69
+ /** Чистит историю счётчиков, чтобы она не росла вместе с числом пользователей. */
70
+ function sweepUpdateLimits() {
71
+ const until = Date.now() - UPDATE_WINDOW_MS;
72
+ let n = 0;
73
+ for (const [id, hits] of updateHits) {
74
+ const fresh = hits.filter((at) => at > until);
75
+ if (!fresh.length) {
76
+ updateHits.delete(id);
77
+ n++;
78
+ } else updateHits.set(id, fresh);
79
+ }
80
+ return n;
81
+ }
82
+
53
83
  /** Модель пользователя для экрана /start: выбранная или «Авто» на его языке. */
54
84
  const modelLabel = (st) => {
55
85
  const engine = engineOf(st);
@@ -240,7 +270,7 @@ async function receiveFile(st, meta, lang) {
240
270
  data = await downloadFile(meta.id);
241
271
  } catch (e) {
242
272
  log('скачивание файла:', e.message, '| пользователь', st.userId);
243
- await say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang) }));
273
+ await say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }));
244
274
  return null;
245
275
  } finally {
246
276
  releaseUpload(st.userId, meta.size);
@@ -249,7 +279,7 @@ async function receiveFile(st, meta, lang) {
249
279
  await say(st.to, t('file.tooBig', lang));
250
280
  return null;
251
281
  }
252
- const path = saveUpload(dir, meta.name, data);
282
+ const path = await saveUpload(dir, meta.name, data);
253
283
  log('файл принят', st.userId, path, `${data.length} Б`);
254
284
  const file = { path, name: meta.name, mime: meta.mime, size: data.length };
255
285
  if (isImageMime(meta.mime) && data.length <= IMAGE_BLOCK_MAX) file.data = data;
@@ -326,6 +356,9 @@ async function setupCommands() {
326
356
  }
327
357
 
328
358
  async function handleUpdate(u) {
359
+ const actor = u.message?.from || u.callback_query?.from || u.widget_query?.from || (u.stopped_message_generation ? { id: u.stopped_message_generation.chat?.id ?? '?' } : null);
360
+ if (actor && tooManyUpdates(actor.id)) return;
361
+
329
362
  // пользователь нажал «стоп» на черновике
330
363
  if (u.stopped_message_generation) {
331
364
  const sg = u.stopped_message_generation;
@@ -477,6 +510,22 @@ ${probe.hint}`);
477
510
  setSandboxBroken(broken);
478
511
  }
479
512
 
513
+ /** При старте помечает оборванные перезапуском запросы и сообщает их авторам. */
514
+ function notifyInterrupted() {
515
+ const rows = db.unfinishedRequests() ?? [];
516
+ const n = db.interruptRequests('interrupted by bot restart') ?? 0;
517
+ if (!rows.length) return n;
518
+ const seen = new Set();
519
+ for (const r of rows) {
520
+ const key = `${r.user_id}:${r.chat_id ?? r.user_id}`;
521
+ if (seen.has(key)) continue;
522
+ seen.add(key);
523
+ say(r.chat_id ?? r.user_id, t('turn.restarted', langOf(r.user_id))).catch((e) => log('уведомление о перезапуске:', e.message, '| пользователь', r.user_id));
524
+ }
525
+ log(`запросов, прерванных перезапуском: ${n}; уведомлено диалогов: ${seen.size}`);
526
+ return n;
527
+ }
528
+
480
529
  async function main() {
481
530
  if (SANDBOX && !ROOT) {
482
531
  console.error('AGENT_SANDBOX=bwrap: задайте PROJECTS_ROOT — без корня сотрудник может выбрать проектом любую папку сервера');
@@ -527,15 +576,16 @@ async function main() {
527
576
  : 'темы в личном чате выключены — режим «диалоги» недоступен',
528
577
  );
529
578
  await setupCommands().catch((e) => log('настройка меню:', e.message));
579
+ notifyInterrupted();
530
580
  maybeNotifySafety();
531
581
  // пропускаем накопившиеся до запуска обновления
532
582
  const old = await tg('getUpdates', { offset: -1, timeout: 0 });
533
583
  let offset = old.length ? old[old.length - 1].update_id + 1 : 0;
534
584
  startIdleReaper();
535
585
  // принятые и исходящие файлы хранятся FILES_KEEP_DAYS дней: чистим при старте и раз в сутки
536
- const sweep = () => {
586
+ const sweep = async () => {
537
587
  try {
538
- const n = cleanupFiles();
588
+ const n = await cleanupFiles();
539
589
  if (n) log(`удалено старых файлов: ${n}`);
540
590
  } catch (e) {
541
591
  log('очистка файлов:', e.message);
@@ -544,6 +594,8 @@ async function main() {
544
594
  if (h) log(`удалено старых записей истории: ${h}`);
545
595
  const l = cleanupLogs(DATA_DIR, LOGS_KEEP_DAYS);
546
596
  if (l) log(`удалено старых файлов журнала: ${l}`);
597
+ const c = sweepUpdateLimits() + sweepUnknownUsers() + sweepLangCache();
598
+ if (c) log(`удалено старых записей кэша обновлений: ${c}`);
547
599
  };
548
600
  sweep();
549
601
  setInterval(sweep, 24 * 3600_000).unref();
@@ -580,7 +632,11 @@ async function main() {
580
632
  for (const u of updates) {
581
633
  offset = u.update_id + 1;
582
634
  // запросы разных пользователей не блокируют друг друга
583
- handleUpdate(u).catch((e) => log('handleUpdate:', e.message));
635
+ handleUpdate(u).catch((e) => {
636
+ const from = u.message?.from?.id ?? u.callback_query?.from?.id ?? u.widget_query?.from?.id ?? '?';
637
+ log('handleUpdate:', e.message, '| обновление', u.update_id, '| пользователь', from);
638
+ logError('handleUpdate, стек:', e.stack ?? e.message);
639
+ });
584
640
  }
585
641
  }
586
642
  }
package/src/cli.mjs CHANGED
@@ -50,7 +50,7 @@ export function route(argv) {
50
50
  * а не «успешно» (в `curl | bash` код выхода curl теряется).
51
51
  */
52
52
  export function updateCommand(platform = process.platform, env = process.env) {
53
- const base = `https://raw.githubusercontent.com/${REPO}/main`;
53
+ const base = `https://github.com/${REPO}/releases/latest/download`;
54
54
  if (platform !== 'win32') return ['sh', ['-c', `f="$(mktemp)" && curl -fsSL ${base}/install.sh -o "$f" && bash "$f"; r=$?; rm -f "$f"; exit $r`]];
55
55
  // Windows PowerShell — по полному пути: папки WindowsPowerShell может не быть в PATH, а терминал при этом открыт
56
56
  // из меню «Пуск» и работает (так было на ноутбуке: `acpgram update` молча завершался с кодом 1)
@@ -109,7 +109,7 @@ if (isMain()) {
109
109
  if (res.error) {
110
110
  console.error(tc('cli.spawnFail', { cmd, msg: res.error.message }));
111
111
  if (/EPERM|EACCES/.test(res.error.code ?? '')) console.error(tc('cli.blocked'));
112
- if (r.update) console.error(tc('cli.updateManual', { cmd: process.platform === 'win32' ? `irm https://raw.githubusercontent.com/${REPO}/main/install.ps1 | iex` : `curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | bash` }));
112
+ if (r.update) console.error(tc('cli.updateManual', { cmd: process.platform === 'win32' ? `irm https://github.com/${REPO}/releases/latest/download/install.ps1 | iex` : `curl -fsSL https://github.com/${REPO}/releases/latest/download/install.sh -o install.sh && bash install.sh` }));
113
113
  } else if (r.update) {
114
114
  const after = version();
115
115
  console.log(res.status === 0 ? tc('cli.updated', { before, after, same: before === after ? tc('cli.alreadyLatest') : '' }) : tc('cli.updateFailed', { code: res.status, after }));
package/src/ctx.mjs CHANGED
@@ -30,12 +30,14 @@ export const levelHint = (key, lang) => t(`level.${key}.hint`, lang);
30
30
  // В памяти — для всех, кто пишет боту (в том числе без доступа); в базу (tglang:<id>) — для пользователей с доступом,
31
31
  // чтобы бот знал язык и до первого сообщения после перезапуска (например, при уведомлении от администратора).
32
32
  const tgLangCache = new Map();
33
+ const tgLangAt = new Map(); // когда язык впервые замечен в этом запуске: для чистки кэша незнакомцев
33
34
  const tgLangSaved = new Map(); // что уже записано в базу в этом запуске: userId -> язык ('' — не поддерживается)
34
35
  const tgLang = (userId) => (tgLangCache.has(userId) ? tgLangCache.get(userId) : normLang(db.getSetting(`tglang:${userId}`)));
35
36
 
36
37
  /** Запоминает язык из Telegram (from.language_code). persist — писать в базу (только для пользователей с доступом). */
37
38
  export function noteTgLang(userId, code, persist = false) {
38
39
  const lang = normLang(code);
40
+ if (!tgLangCache.has(userId)) tgLangAt.set(userId, Date.now());
39
41
  tgLangCache.set(userId, lang);
40
42
  if (persist && tgLangSaved.get(userId) !== (lang ?? '')) {
41
43
  tgLangSaved.set(userId, lang ?? '');
@@ -50,6 +52,20 @@ export function noteTgLang(userId, code, persist = false) {
50
52
  export const langOf = (userId) => pickLang(db.getSetting(`lang:${userId}`), tgLang(userId));
51
53
  export const setLang = (userId, lang) => db.setSetting(`lang:${userId}`, lang);
52
54
 
55
+ /** Чистит языковой кэш давно не писавших пользователей (в первую очередь — незнакомцев без доступа). */
56
+ export function sweepLangCache(maxAgeMs = 24 * 3600_000) {
57
+ const until = Date.now() - maxAgeMs;
58
+ let n = 0;
59
+ for (const [id, at] of tgLangAt) {
60
+ if (at > until) continue;
61
+ tgLangCache.delete(id);
62
+ tgLangAt.delete(id);
63
+ tgLangSaved.delete(id);
64
+ n++;
65
+ }
66
+ return n;
67
+ }
68
+
53
69
  export const botInfo = { username: null }; // заполняется при старте
54
70
 
55
71
  export { log }; // журнал — log.mjs (им же пользуются acp, telegram и db)
package/src/db.mjs CHANGED
@@ -234,6 +234,14 @@ export function openDb(path = 'data/bot.db') {
234
234
  stop_reason = ?, answer = ?, error = ?, model = ?, effort = ?, input_tokens = ?, output_tokens = ?, cached_tokens = ?,
235
235
  thought_tokens = ?, total_tokens = ?, cost_usd = ? WHERE id = ?`,
236
236
  ),
237
+ unfinishedRequests: db.prepare(
238
+ `SELECT r.id, s.user_id, s.chat_id, r.user_text FROM requests r JOIN sessions s ON s.id = r.session_id
239
+ WHERE r.finished_at IS NULL ORDER BY r.id`,
240
+ ),
241
+ interruptRequests: db.prepare(
242
+ `UPDATE requests SET finished_at = ?, duration_ms = CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER),
243
+ stop_reason = 'interrupted', error = ? WHERE finished_at IS NULL`,
244
+ ),
237
245
  setUserEngines: db.prepare('UPDATE users SET engines = ? WHERE user_id = ?'),
238
246
  setUserModels: db.prepare('UPDATE users SET models = ? WHERE user_id = ?'),
239
247
  insertTool: db.prepare(
@@ -283,17 +291,25 @@ export function openDb(path = 'data/bot.db') {
283
291
  deleteGitAccountsByHost: db.prepare('DELETE FROM git_accounts WHERE host = ?'),
284
292
  };
285
293
 
286
- // Любая ошибка БД не должна ронять бота — журнал вторичен по отношению к работе.
287
- const safe = (fn) => (...a) => {
288
- try {
289
- return fn(...a);
290
- } catch (e) {
291
- logError('[db]', e.message);
292
- return null;
293
- }
294
- };
294
+ // Любая ошибка БД не должна ронять бота — журнал вторичен по отношению к работе. Имя операции добавляет
295
+ // обёртка named: по одному сообщению без имени невозможно понять, какой именно запрос упал.
296
+ const safe = (fn) => fn;
297
+ const named = (methods) =>
298
+ Object.fromEntries(
299
+ Object.entries(methods).map(([name, fn]) => [
300
+ name,
301
+ (...a) => {
302
+ try {
303
+ return fn(...a);
304
+ } catch (e) {
305
+ logError('[db]', name, e.message);
306
+ return null;
307
+ }
308
+ },
309
+ ]),
310
+ );
295
311
 
296
- return {
312
+ return named({
297
313
  // --- доступ сотрудников ---
298
314
  getUser: safe((id) => q.getUser.get(id) ?? null),
299
315
  listUsers: () => safe(() => q.listUsers.all())() ?? [],
@@ -333,6 +349,12 @@ export function openDb(path = 'data/bot.db') {
333
349
  return id && q.finishRequest.run(t, t, stopReason ?? null, answer ?? null, error ?? null, usage.model ?? null, usage.effort ?? null,
334
350
  n(usage.input), n(usage.output), n(usage.cachedRead), n(usage.thought), n(usage.total), n(usage.cost), id);
335
351
  }),
352
+ /** Запросы, оборванные перезапуском службы: их надо пометить и сообщить пользователям. */
353
+ unfinishedRequests: safe(() => q.unfinishedRequests.all() ?? []),
354
+ interruptRequests: safe((error) => {
355
+ const t = now();
356
+ return q.interruptRequests.run(t, t, error ?? 'bot restarted').changes;
357
+ }),
336
358
  setUserEngines: safe((id, list) => q.setUserEngines.run(list?.length ? JSON.stringify(list) : null, id)),
337
359
  setUserModels: safe((id, map) => q.setUserModels.run(map && Object.keys(map).length ? JSON.stringify(map) : null, id)),
338
360
  toolStarted: safe((requestId, t) =>
@@ -388,5 +410,5 @@ export function openDb(path = 'data/bot.db') {
388
410
  /** Удаляет аккаунты всех пользователей на сервисе (сервис убран администратором). Возвращает число удалённых. */
389
411
  deleteGitAccountsByHost: (host) => safe(() => Number(q.deleteGitAccountsByHost.run(host).changes))() ?? 0,
390
412
  close: () => db.close(),
391
- };
413
+ });
392
414
  }
package/src/files.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  // Файлы от пользователя сохраняются на диск (агент читает их своими инструментами по пути) — так работает любой
3
3
  // движок и любой формат; изображения дополнительно уходят блоком image, если агент это заявил (promptCapabilities).
4
4
  // Файлы агента — по метке [[send:путь]] в ответе: отправляются только из каталога исходящих и из папки проекта.
5
- import { existsSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
+ import { realpathSync } from 'node:fs';
6
+ import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
6
7
  import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
8
  import { readStable } from './agentFiles.mjs';
8
9
  import { DATA_DIR, ENV_PATH, positiveEnv } from './app.mjs';
@@ -62,13 +63,13 @@ const pad = (n) => String(n).padStart(2, '0');
62
63
  const stamp = (d) => `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
63
64
 
64
65
  /** Сохраняет файл в `dir` под именем «ГГГГММДД-ЧЧММСС_имя» (существующие файлы не перезаписываются). Возвращает путь. */
65
- export function saveUpload(dir, name, buffer, date = new Date()) {
66
- mkdirSync(dir, { recursive: true });
66
+ export async function saveUpload(dir, name, buffer, date = new Date()) {
67
+ await mkdir(dir, { recursive: true });
67
68
  const safe = safeFileName(name);
68
69
  for (let i = 0; ; i++) {
69
70
  const path = join(dir, `${stamp(date)}${i ? `-${i}` : ''}_${safe}`);
70
71
  try {
71
- writeFileSync(path, buffer, { flag: 'wx' });
72
+ await writeFile(path, buffer, { flag: 'wx' });
72
73
  return path;
73
74
  } catch (e) {
74
75
  if (e.code !== 'EEXIST' || i > 99) throw e;
@@ -77,31 +78,37 @@ export function saveUpload(dir, name, buffer, date = new Date()) {
77
78
  }
78
79
 
79
80
  /** Удаляет файлы старше maxAgeMs в каталогах пользователей внутри `root` (root/<id>/файл). Возвращает число удалённых. */
80
- export function cleanupOldFiles(root, maxAgeMs, now = Date.now()) {
81
+ export async function cleanupOldFiles(root, maxAgeMs, now = Date.now()) {
81
82
  let removed = 0;
82
- if (!existsSync(root)) return 0;
83
- for (const dir of readdirSync(root, { withFileTypes: true })) {
84
- if (!dir.isDirectory()) continue;
83
+ let dirs;
84
+ try {
85
+ dirs = await readdir(root, { withFileTypes: true });
86
+ } catch {
87
+ return 0;
88
+ }
89
+ await Promise.all(dirs.map(async (dir) => {
90
+ if (!dir.isDirectory()) return;
85
91
  const full = join(root, dir.name);
86
- for (const f of readdirSync(full, { withFileTypes: true })) {
92
+ const entries = await readdir(full, { withFileTypes: true }).catch(() => []);
93
+ await Promise.all(entries.map(async (f) => {
87
94
  const p = join(full, f.name);
88
95
  try {
89
- if (now - statSync(p).mtimeMs > maxAgeMs) {
90
- rmSync(p, { recursive: true, force: true });
96
+ if (now - (await stat(p)).mtimeMs > maxAgeMs) {
97
+ await rm(p, { recursive: true, force: true });
91
98
  removed++;
92
99
  }
93
100
  } catch {
94
101
  /* файл исчез или занят — пропускаем */
95
102
  }
96
- }
97
- }
103
+ }));
104
+ }));
98
105
  return removed;
99
106
  }
100
107
 
101
108
  /** Чистка загрузок и исходящих файлов старше KEEP_DAYS. */
102
- export function cleanupFiles(base = FILES_BASE) {
109
+ export async function cleanupFiles(base = FILES_BASE) {
103
110
  const age = KEEP_DAYS * 24 * 3600_000;
104
- return cleanupOldFiles(uploadsRoot(base), age) + cleanupOldFiles(outboxRoot(base), age);
111
+ return (await cleanupOldFiles(uploadsRoot(base), age)) + (await cleanupOldFiles(outboxRoot(base), age));
105
112
  }
106
113
 
107
114
  const UNPACKED_LIST = 50; // сколько файлов распакованного архива перечислять агенту
package/src/filesUi.mjs CHANGED
@@ -8,7 +8,7 @@ import { LOCALES, errText, t } from './i18n.mjs';
8
8
  import { FileError, deleteProjectFile, fmtSize, listProjectDir, projectFileInfo, relPath, resolveTarget, writeProjectFile } from './projectFiles.mjs';
9
9
  import { insideRoot, isPersonalRoot, samePath } from './projects.mjs';
10
10
  import { folderRows, pathToken, tokenPath } from './projectsUi.mjs';
11
- import { isAdmin, rootOf, userPath } from './state.mjs';
11
+ import { errorRootOf, isAdmin, rootOf, userPath } from './state.mjs';
12
12
  import { dest, downloadFile, tg } from './telegram.mjs';
13
13
  import { hCode, th } from './ui.mjs';
14
14
 
@@ -38,14 +38,14 @@ const relShow = (project, path) => relative(project, path).split(sep).join('/')
38
38
  const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'fl:x' }]] });
39
39
 
40
40
  /** Текст причины отказа (FileError.code) на языке пользователя. */
41
- const whyText = (e, lang) => (e instanceof FileError ? t(`files.err.${e.code}`, lang) : errText(e, lang));
41
+ const whyText = (e, lang, userId) => (e instanceof FileError ? t(`files.err.${e.code}`, lang) : errText(e, lang, errorRootOf(userId)));
42
42
 
43
43
  /** Удаляет сообщение пользователя с содержимым или файлом: в чате не должно оставаться копии секрета. */
44
44
  const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch((e) => log('files: сообщение не удалено:', e.message)) : null);
45
45
 
46
46
  /** Экран папки проекта: папки, файлы с размером, «Вверх», «Создать файл» и «Загрузить файл». Текст — HTML. */
47
- export function filesView(st, project, dir, page = 0, lang = langOf(st.userId)) {
48
- const { dirs, files } = listProjectDir(project, dir, { hideConfig: !canManageFiles(st.userId) });
47
+ export async function filesView(st, project, dir, page = 0, lang = langOf(st.userId)) {
48
+ const { dirs, files } = await listProjectDir(project, dir, { hideConfig: !canManageFiles(st.userId) });
49
49
  const entries = [...dirs.map((name) => ({ name, dir: true })), ...files];
50
50
  const pages = Math.max(1, Math.ceil(entries.length / PAGE));
51
51
  page = Math.min(Math.max(page, 0), pages - 1);
@@ -78,7 +78,7 @@ export async function handleFiles(st) {
78
78
  const lang = langOf(st.userId);
79
79
  const project = projectOf(st);
80
80
  if (!project) return say(st.to, t('state.projectGone', lang));
81
- const v = filesView(st, project, project, 0, lang);
81
+ const v = await filesView(st, project, project, 0, lang);
82
82
  return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('files:', e.message));
83
83
  }
84
84
 
@@ -124,7 +124,7 @@ async function saveUpload(st, project, { dir, parts, meta, messageId }, lang, {
124
124
  data = await downloadFile(meta.id);
125
125
  } catch (e) {
126
126
  log('files: скачивание:', e.message, '| пользователь', st.userId);
127
- return say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang) }));
127
+ return say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }));
128
128
  }
129
129
  if (data.length > MAX_FILE_BYTES) return say(st.to, t('file.tooBig', lang));
130
130
  try {
@@ -134,7 +134,7 @@ async function saveUpload(st, project, { dir, parts, meta, messageId }, lang, {
134
134
  return say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
135
135
  } catch (e) {
136
136
  log('files: запись:', e.message, '| пользователь', st.userId);
137
- return say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
137
+ return say(st.to, th('files.saveFail', lang, { why: whyText(e, lang, st.userId) }), HTML);
138
138
  }
139
139
  }
140
140
 
@@ -171,7 +171,7 @@ export async function onFilesCallback(st, cb) {
171
171
  if (!path) return ack(t('proj.stale', lang));
172
172
  try {
173
173
  if (action === 'o') {
174
- const v = filesView(st, project, path, Number(pageStr) || 0, lang);
174
+ const v = await filesView(st, project, path, Number(pageStr) || 0, lang);
175
175
  await ack();
176
176
  return edit(v);
177
177
  }
@@ -186,17 +186,17 @@ export async function onFilesCallback(st, cb) {
186
186
  deleteProjectFile(project, path);
187
187
  log('файл проекта удалён:', st.userId, path);
188
188
  await ack(t('files.deleted', lang, { name: basename(path) }));
189
- return edit(filesView(st, project, dirname(path), 0, lang));
189
+ return edit(await filesView(st, project, dirname(path), 0, lang));
190
190
  }
191
191
  if (action === 'n' || action === 'u') {
192
- listProjectDir(project, path, { hideConfig: !canManageFiles(st.userId) }); // папка должна быть внутри проекта
192
+ await listProjectDir(project, path, { hideConfig: !canManageFiles(st.userId) }); // папка должна быть внутри проекта
193
193
  await ack();
194
194
  st.pendingInput = { kind: action === 'n' ? 'fileName' : 'fileUpload', dir: path, at: Date.now() };
195
195
  return say(st.to, th(action === 'n' ? 'files.nameAsk' : 'files.uploadAsk', lang, { dir: hCode(relShow(project, path)) }), { ...HTML, reply_markup: cancelMarkup(lang) });
196
196
  }
197
197
  } catch (e) {
198
198
  if (!(e instanceof FileError)) log('files:', e.message, '| пользователь', st.userId);
199
- return ack(whyText(e, lang));
199
+ return ack(whyText(e, lang, st.userId));
200
200
  }
201
201
  }
202
202
 
@@ -235,7 +235,7 @@ export async function onFileInput(st, text, { messageId, now = Date.now() } = {}
235
235
  await say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
236
236
  } catch (e) {
237
237
  log('files: запись:', e.message, '| пользователь', st.userId);
238
- await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
238
+ await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang, st.userId) }), HTML);
239
239
  }
240
240
  return true;
241
241
  }
@@ -255,7 +255,7 @@ export async function onFileInput(st, text, { messageId, now = Date.now() } = {}
255
255
  try {
256
256
  target = resolveTarget(project, wait.dir, parts);
257
257
  } catch (e) {
258
- return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), { ...HTML, reply_markup: cancelMarkup(lang) }), true);
258
+ return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang, st.userId) }), { ...HTML, reply_markup: cancelMarkup(lang) }), true);
259
259
  }
260
260
  st.pendingInput = null;
261
261
  if (target.exists) await askReplace(st, project, { dir: wait.dir, parts }, lang);
@@ -289,7 +289,7 @@ export async function onFileUpload(st, msg, now = Date.now()) {
289
289
  try {
290
290
  if (resolveTarget(project, dir, parts).exists) return (await askReplace(st, project, job, lang), true);
291
291
  } catch (e) {
292
- return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML), true);
292
+ return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang, st.userId) }), HTML), true);
293
293
  }
294
294
  await saveUpload(st, project, job, lang);
295
295
  return true;
package/src/gitCtx.mjs CHANGED
@@ -3,7 +3,7 @@ import { db } from './ctx.mjs';
3
3
  import { accountsOf, hostFor, identityOf } from './gitAccess.mjs';
4
4
  import { authConfig, HostError } from './gitHosts.mjs';
5
5
  import { gitCommand, gitEnv, GitConfigError, GitError, repoState } from './git.mjs';
6
- import { errText } from './i18n.mjs';
6
+ import { errText, maskErrorPaths } from './i18n.mjs';
7
7
  import { insideRoot, isPersonalRoot, ROOT } from './projects.mjs';
8
8
  import { agentSandbox } from './sandbox.mjs';
9
9
  import { rootOf, sandboxed } from './state.mjs';
@@ -38,10 +38,12 @@ export async function repoOf(st, project) {
38
38
  return { state, host, account };
39
39
  }
40
40
 
41
- export const failText = (e, lang, host = null) => {
41
+ export const failText = (e, lang, host = null, root = null) => {
42
+ const mask = (s) => (root ? maskErrorPaths(s, root, lang) : s);
42
43
  if (e instanceof GitConfigError) return th('git.unsafeConfig', lang, { keys: e.keys.join(', ') });
43
- if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
44
- return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
44
+ if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: mask(e.message) });
45
+ const msg = e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang, root);
46
+ return th('git.opFail', lang, { msg: mask(msg) });
45
47
  };
46
48
 
47
49
  const gitLocks = new Map();
@@ -1,7 +1,7 @@
1
1
  // Git: что изменилось и какие есть ветки — для экранов «Изменения» и «Ветки» в /git.
2
2
  // Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
3
3
  // безопасными настройками и, при включённой песочнице, внутри неё.
4
- import { lstatSync, readFileSync } from 'node:fs';
4
+ import { lstat, readFile } from 'node:fs/promises';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { assertPlainConfig, GitError, runGit } from './git.mjs';
7
7
  import { samePath } from './projects.mjs';
@@ -56,12 +56,12 @@ export function parseNumstat(text) {
56
56
  }
57
57
 
58
58
  /** Число строк нового файла (которого git ещё не знает) или null, если он велик, двоичный или не читается. */
59
- function countLines(file) {
59
+ async function countLines(file) {
60
60
  try {
61
61
  // файл лежит в папке, куда пишет агент: ссылку не читаем (она может вести на любой файл сервера)
62
- const st = lstatSync(file);
62
+ const st = await lstat(file);
63
63
  if (!st.isFile() || st.size > COUNT_MAX_BYTES) return null;
64
- const buf = readFileSync(file);
64
+ const buf = await readFile(file);
65
65
  if (buf.includes(0)) return null;
66
66
  if (!buf.length) return 0;
67
67
  let n = 0;
@@ -81,11 +81,11 @@ export async function changedFiles(cwd, opts = {}) {
81
81
  const all = parseChanges(await runGit(['status', '--porcelain=v1', '-z', '--untracked-files=all'], { cwd, ...opts }));
82
82
  // в репозитории без коммитов сравнивать не с чем — тогда без числа строк
83
83
  const counts = await runGit(['diff', '--numstat', '-z', 'HEAD'], { cwd, ...opts }).then(parseNumstat, () => new Map());
84
- const files = all.slice(0, CHANGES_MAX).map((f) => {
84
+ const files = await Promise.all(all.slice(0, CHANGES_MAX).map(async (f) => {
85
85
  const c = counts.get(f.path);
86
86
  if (c) return { ...f, ...c };
87
- return { ...f, added: f.kind === 'new' ? countLines(join(top, f.path)) : null, deleted: f.kind === 'new' ? 0 : null };
88
- });
87
+ return { ...f, added: f.kind === 'new' ? await countLines(join(top, f.path)) : null, deleted: f.kind === 'new' ? 0 : null };
88
+ }));
89
89
  return { files, total: all.length };
90
90
  }
91
91
 
@@ -14,7 +14,7 @@ import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visib
14
14
  import { HostError, showRemote } from './gitHosts.mjs';
15
15
  import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
16
16
  import { t } from './i18n.mjs';
17
- import { userPath } from './state.mjs';
17
+ import { errorRootOf, userPath } from './state.mjs';
18
18
  import { hCode, th } from './ui.mjs';
19
19
 
20
20
  /** Действия кнопок этого модуля (gt:<действие>:<аргумент>). */
@@ -98,7 +98,7 @@ async function publish(st, project, lang, edit, view) {
98
98
  return await edit({ text: `${th('git.pb.done', lang, { address: hCode(showRemote(created.url)) })}${note}\n\n${v.text}`, markup: { inline_keyboard: [...open, ...v.markup.inline_keyboard] } });
99
99
  } catch (e) {
100
100
  log('git: публикация:', e.message, '| пользователь', st.userId);
101
- return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
101
+ return await edit({ text: failText(e, lang, host, errorRootOf(st.userId)), markup: { inline_keyboard: [backRow(lang)] } });
102
102
  } finally {
103
103
  releaseGitLock(st, lock);
104
104
  }
@@ -117,7 +117,7 @@ async function mergeRequest(st, project, title, lang, edit) {
117
117
  return await edit({ text, markup: { inline_keyboard: [[{ text: t('git.open', lang), url: r.url }], backRow(lang)] } });
118
118
  } catch (e) {
119
119
  log('git: запрос на слияние:', e.message, '| пользователь', st.userId);
120
- return await edit({ text: failText(e, lang, repo.host), markup: { inline_keyboard: [backRow(lang)] } });
120
+ return await edit({ text: failText(e, lang, repo.host, errorRootOf(st.userId)), markup: { inline_keyboard: [backRow(lang)] } });
121
121
  }
122
122
  }
123
123
 
@@ -203,7 +203,7 @@ export async function onPublishCallback(st, cb, h) {
203
203
  } catch (e) {
204
204
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
205
205
  await ack();
206
- return edit({ text: failText(e, lang, accountOf(st, st.gitPublish)?.host), markup: { inline_keyboard: [backRow(lang)] } });
206
+ return edit({ text: failText(e, lang, accountOf(st, st.gitPublish)?.host, errorRootOf(st.userId)), markup: { inline_keyboard: [backRow(lang)] } });
207
207
  }
208
208
  }
209
209
 
@@ -236,7 +236,7 @@ export async function onPublishInput(st, text, h) {
236
236
  return (await send(summaryView(st, project, lang)), true);
237
237
  } catch (e) {
238
238
  log('git: публикация (ввод):', e.message, '| пользователь', st.userId);
239
- await say(st.to, failText(e, lang, accountOf(st, st.gitPublish)?.host), HTML);
239
+ await say(st.to, failText(e, lang, accountOf(st, st.gitPublish)?.host, errorRootOf(st.userId)), HTML);
240
240
  return true;
241
241
  }
242
242
  }
package/src/gitRepoUi.mjs CHANGED
@@ -11,7 +11,7 @@ import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf }
11
11
  import { recall, remember } from './gitKeys.mjs';
12
12
  import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
13
13
  import { t } from './i18n.mjs';
14
- import { endAgent, userPath } from './state.mjs';
14
+ import { endAgent, errorRootOf, userPath } from './state.mjs';
15
15
  import { escHtml, sendBuffer } from './telegram.mjs';
16
16
  import { hCode, th } from './ui.mjs';
17
17
 
@@ -197,7 +197,7 @@ export async function onRepoCallback(st, cb, h) {
197
197
  } catch (e) {
198
198
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
199
199
  await ack();
200
- return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
200
+ return edit({ text: failText(e, lang, null, errorRootOf(st.userId)), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
201
201
  } finally {
202
202
  releaseGitLock(st, lock);
203
203
  }
@@ -232,7 +232,7 @@ export async function onBranchInput(st, text, h) {
232
232
  await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
233
233
  } catch (e) {
234
234
  log('git: новая ветка:', e.message, '| пользователь', st.userId);
235
- await say(st.to, failText(e, lang), html);
235
+ await say(st.to, failText(e, lang, null, errorRootOf(st.userId)), html);
236
236
  } finally {
237
237
  releaseGitLock(st, lock);
238
238
  }
package/src/gitUi.mjs CHANGED
@@ -16,7 +16,7 @@ import { HostError, customHost, fetchProfile, listRepos, missingScopes, probeHos
16
16
  import { LOCALES, t } from './i18n.mjs';
17
17
  import { folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
18
18
  import { canCreateProject, selectProject } from './projectsUi.mjs';
19
- import { isAdmin, rootOf, userPath } from './state.mjs';
19
+ import { errorRootOf, isAdmin, rootOf, userPath } from './state.mjs';
20
20
  import { dest, tg } from './telegram.mjs';
21
21
  import { hCode, th } from './ui.mjs';
22
22
 
@@ -111,6 +111,7 @@ async function freshen(st) {
111
111
  export async function handleGit(st) {
112
112
  const lang = langOf(st.userId);
113
113
  if (!gitAvailable()) return say(st.to, t('git.none', lang));
114
+ if (st.gitBusy) return say(st.to, t('git.busy', lang));
114
115
  await freshen(st);
115
116
  const v = await gitView(st, lang, { sync: true });
116
117
  return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
@@ -179,7 +180,7 @@ async function cloneChosen(st, repo, host, account, lang, edit) {
179
180
  } catch (e) {
180
181
  log('git: клонирование:', e.message, '| пользователь', st.userId);
181
182
  cleanFailedClone(st, target, base);
182
- return edit({ text: failText(e, lang) });
183
+ return edit({ text: failText(e, lang, null, errorRootOf(st.userId)) });
183
184
  }
184
185
  const dir = insideRoot(target, rootOf(st.userId));
185
186
  if (!dir) return edit({ text: th('git.cloneBadName', lang) });
@@ -241,7 +242,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
241
242
  return await done(th(action === 'save' ? 'git.saved' : 'git.pushed', lang) + note);
242
243
  } catch (e) {
243
244
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
244
- return await done(failText(e, lang));
245
+ return await done(failText(e, lang, null, errorRootOf(st.userId)));
245
246
  } finally {
246
247
  releaseGitLock(st, lock);
247
248
  }
@@ -446,7 +447,7 @@ export async function onGitCallback(st, cb) {
446
447
  } catch (e) {
447
448
  log('git:', e.message, '| пользователь', st.userId);
448
449
  await ack();
449
- return edit({ text: failText(e, lang) });
450
+ return edit({ text: failText(e, lang, null, errorRootOf(st.userId)) });
450
451
  }
451
452
  }
452
453
 
@@ -519,7 +520,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
519
520
  try {
520
521
  await send(await reposView(st, host, account, { search: text.trim().slice(0, 60) }, lang));
521
522
  } catch (e) {
522
- await send({ text: failText(e, lang) });
523
+ await send({ text: failText(e, lang, null, errorRootOf(st.userId)) });
523
524
  }
524
525
  return true;
525
526
  }
package/src/i18n.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { relative, resolve, sep } from 'node:path';
2
+
1
3
  // Языки интерфейса бота: английский (по умолчанию), русский и украинский.
2
4
  // Все тексты, которые видит пользователь в Telegram, — здесь, по ключам: у каждого ключа есть перевод на каждый язык
3
5
  // (test/i18n.test.mjs это проверяет). Логи и сообщения в консоли остаются на русском — их читает администратор сервера.
@@ -61,8 +63,43 @@ export function t(key, lang = DEFAULT_LANG, vars = {}) {
61
63
  */
62
64
  export const i18nError = (message, key, vars = {}, extra = {}, opts = undefined) => Object.assign(new Error(message, opts), extra, { i18n: { key, vars } });
63
65
 
64
- /** Текст ошибки для пользователя на его языке; у ошибок без перевода (ответ агента, Telegram, система) — их message. */
65
- export const errText = (e, lang = DEFAULT_LANG) => (e?.i18n && M[e.i18n.key] ? t(e.i18n.key, lang, e.i18n.vars) : String(e?.message ?? e));
66
+ /** Нормализация пути для сравнения по правилам текущей ОС (без обращения к projects.mjs: этот модуль не зависит от состояния бота). */
67
+ const normFsPath = (p) => (process.platform === 'win32' || process.platform === 'darwin' ? p.toLowerCase() : p);
68
+
69
+ /**
70
+ * Заменяет абсолютные пути в тексте ошибки: внутри личного пространства — путём от папки сотрудника,
71
+ * остальные пути — нейтральной подстановкой, чтобы серверные каталоги не уходили пользователю.
72
+ */
73
+ export function maskErrorPaths(text, root, lang = DEFAULT_LANG) {
74
+ if (!root || !text) return text;
75
+ const rootN = normFsPath(resolve(root));
76
+ const within = (p) => {
77
+ const r = normFsPath(resolve(p));
78
+ return r === rootN || r.startsWith(`${rootN}${sep}`);
79
+ };
80
+ return String(text).replace(/(?<![\w])(?:[A-Za-z]:[\\/]|\\\\|\/)[^\s"'<>|]+/g, (m, offset, all) => {
81
+ if (all[offset - 1] === '/' || all[offset - 1] === ':') return m; // часть URL или схемы
82
+ let p = m;
83
+ let tail = '';
84
+ while (/[.,;:!?)}\]]$/.test(p)) {
85
+ tail = p.at(-1) + tail;
86
+ p = p.slice(0, -1);
87
+ }
88
+ let shown;
89
+ try {
90
+ shown = within(p) ? (normFsPath(resolve(p)) === rootN ? t('proj.myRoot', lang) : relative(resolve(root), resolve(p))) : t('err.serverPath', lang);
91
+ } catch {
92
+ return m;
93
+ }
94
+ return `${shown}${tail}`;
95
+ });
96
+ }
97
+
98
+ /** Текст ошибки для пользователя; root задан — абсолютные пути в нём маскируются (личные пространства сотрудников). */
99
+ export const errText = (e, lang = DEFAULT_LANG, root = null) => {
100
+ const text = e?.i18n && M[e.i18n.key] ? t(e.i18n.key, lang, e.i18n.vars) : String(e?.message ?? e);
101
+ return root ? maskErrorPaths(text, root, lang) : text;
102
+ };
66
103
 
67
104
  /** Выбор языка до того, как он сохранён: показываем сразу на трёх языках. */
68
105
  export const LANG_PICK = 'Choose your language:\nВыберите язык:\nОберіть мову:';
@@ -544,6 +581,10 @@ const M = {
544
581
  'err.agentExit': { en: '{engine} exited (code {code})', ru: '{engine} завершился (код {code})', uk: '{engine} завершився (код {code})' },
545
582
  'err.agentClosed': { en: '{engine}: the agent process has already exited', ru: '{engine}: процесс агента уже завершён', uk: '{engine}: процес агента вже завершено' },
546
583
  'err.agentNoReply': { en: '{engine}: no reply in {sec} s', ru: '{engine}: нет ответа за {sec} с', uk: '{engine}: немає відповіді за {sec} с' },
584
+ 'err.serverPath': { en: '<server path>', ru: '<путь на сервере>', uk: '<шлях на сервері>' },
585
+ 'err.agentLineTooLong': { en: '{engine}: a line longer than {mb} MB was received — the agent was stopped', ru: '{engine}: получена строка длиннее {mb} МБ — агент остановлен', uk: '{engine}: отримано рядок довший за {mb} МБ — агент зупинено' },
586
+ 'turn.truncated': { en: '⚠️ The reply was too long and was shortened.', ru: '⚠️ Ответ слишком длинный и был сокращён.', uk: '⚠️ Відповідь занадто довга й була скорочена.' },
587
+ 'turn.restarted': { en: '⚠️ The bot was restarted while your request was running. The request was interrupted — please try again.', ru: '⚠️ Бот перезапускался, пока выполнялся ваш запрос. Запрос прерван — повторите его.', uk: '⚠️ Бот перезапустився, поки виконувався ваш запит. Запит перервано — повторіть його.' },
547
588
  'err.tgTimeout': { en: 'Telegram {method}: no reply in {sec} s', ru: 'Telegram {method}: нет ответа за {sec} с', uk: 'Telegram {method}: немає відповіді за {sec} с' },
548
589
  'err.tgNoFilePath': { en: 'Telegram did not return the file path', ru: 'Telegram не вернул путь к файлу', uk: 'Telegram не повернув шлях до файлу' },
549
590
  'turn.error': { en: '⚠️ Error: {msg}', ru: '⚠️ Ошибка: {msg}', uk: '⚠️ Помилка: {msg}' },
@@ -4,7 +4,8 @@
4
4
  // Все операции работают только внутри папки проекта и не ходят по ссылкам: агент пишет в ту же папку и мог бы подложить
5
5
  // ссылку «.env → файл вне проекта», чтобы бот (он работает без песочницы) перезаписал чужой файл.
6
6
  import { randomBytes } from 'node:crypto';
7
- import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
7
+ import { closeSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
8
+ import { lstat as lstatAsync, readdir as readdirAsync } from 'node:fs/promises';
8
9
  import { join } from 'node:path';
9
10
  import { AgentFileError, openVerified, verifyStable } from './agentFiles.mjs';
10
11
  import { isWithin } from './projects.mjs';
@@ -150,21 +151,25 @@ export function deleteProjectFile(project, path) {
150
151
  * Содержимое папки проекта: папки и файлы по алфавиту, со скрытыми файлами (.env), без ссылок и служебных папок.
151
152
  * @returns {{dirs: string[], files: {name: string, size: number, mtime: number}[]}}
152
153
  */
153
- export function listProjectDir(project, dir, { hideConfig = false } = {}) {
154
+ export async function listProjectDir(project, dir, { hideConfig = false } = {}) {
154
155
  const { real } = inProject(project, dir);
155
- const dirs = [];
156
- const files = [];
157
- for (const d of readdirSync(real, { withFileTypes: true })) {
158
- if (d.isSymbolicLink() || d.name.endsWith('.tmp') && d.name.startsWith('.acpgram-')) continue;
156
+ const entries = await readdirAsync(real, { withFileTypes: true });
157
+ const listed = await Promise.all(entries.map(async (d) => {
158
+ if (d.isSymbolicLink() || d.name.endsWith('.tmp') && d.name.startsWith('.acpgram-')) return null;
159
159
  const lower = d.name.toLowerCase();
160
160
  if (d.isDirectory()) {
161
- if (!SKIP_DIRS.has(lower) && !(hideConfig && CONFIG_DIRS.has(lower))) dirs.push(d.name);
162
- } else if (d.isFile()) {
163
- if (hideConfig && CONFIG_FILES.has(lower)) continue;
164
- const st = lstat(join(real, d.name));
165
- if (st) files.push({ name: d.name, size: st.size, mtime: st.mtimeMs });
161
+ return !SKIP_DIRS.has(lower) && !(hideConfig && CONFIG_DIRS.has(lower)) ? { dir: d.name } : null;
166
162
  }
167
- }
163
+ if (!d.isFile() || hideConfig && CONFIG_FILES.has(lower)) return null;
164
+ try {
165
+ const st = await lstatAsync(join(real, d.name));
166
+ return { file: { name: d.name, size: st.size, mtime: st.mtimeMs } };
167
+ } catch {
168
+ return null; // файл исчез или занят — не срываем список папки
169
+ }
170
+ }));
171
+ const dirs = listed.filter((x) => x?.dir).map((x) => x.dir);
172
+ const files = listed.filter((x) => x?.file).map((x) => x.file);
168
173
  const byName = (a, b) => a.localeCompare(b, 'ru');
169
174
  return { dirs: dirs.sort(byName), files: files.sort((a, b) => byName(a.name, b.name)) };
170
175
  }
@@ -4,7 +4,7 @@ import { botInfo, db, langOf, log, say, who } from './ctx.mjs';
4
4
  import { ROOT, USER_WORKSPACES, canGoUp, createDir, findDirs, folderName, insideRoot, isPersonalRoot, listDirs, navStart, resolveAsPath, samePath, showPath } from './projects.mjs';
5
5
  import { gitAvailable } from './git.mjs';
6
6
  import { LOCALES, errText, t } from './i18n.mjs';
7
- import { endAgent, isAdmin, recentProjects, rootOf, saveProject, topicsOn } from './state.mjs';
7
+ import { endAgent, errorRootOf, isAdmin, recentProjects, rootOf, saveProject, topicsOn } from './state.mjs';
8
8
  import { topicLink } from './topics.mjs';
9
9
  import { newTopic } from './topicsUi.mjs';
10
10
  import { dest, tg } from './telegram.mjs';
@@ -237,7 +237,7 @@ export async function onProjectNameInput(st, text, now = Date.now()) {
237
237
  dir = canCreateProject(st.userId) ? createDir(wait.dir, text, rootOf(st.userId)) : null;
238
238
  } catch (e) {
239
239
  log('создание папки проекта:', e.message, '| пользователь', st.userId);
240
- await say(st.to, th('proj.newFail', lang, { msg: errText(e, lang) }), HTML);
240
+ await say(st.to, th('proj.newFail', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }), HTML);
241
241
  return true;
242
242
  }
243
243
  if (!dir) {
@@ -4,7 +4,7 @@ import { db, langOf, log, say } from './ctx.mjs';
4
4
  import { canUseEngine } from './access.mjs';
5
5
  import { ENGINES, getEngine, isAvailable } from './engines.mjs';
6
6
  import { LOCALES, errText, t } from './i18n.mjs';
7
- import { ClosedError, LimitError, ProjectError, endAgent, engineOf, ensureAgent, saveEngine, userPath } from './state.mjs';
7
+ import { ClosedError, LimitError, ProjectError, endAgent, engineOf, ensureAgent, errorRootOf, saveEngine, userPath } from './state.mjs';
8
8
  import { dest, escHtml, tg } from './telegram.mjs';
9
9
  import { drainQueue } from './turn.mjs';
10
10
  import { trunc } from './ui.mjs';
@@ -106,7 +106,7 @@ export async function resumeSession(st, item, engine, report) {
106
106
  await report(
107
107
  e instanceof LimitError || e instanceof ProjectError ? e.message
108
108
  : e instanceof ClosedError ? t('ses.cancelled', lang)
109
- : t('ses.failed', lang, { msg: errText(e, lang) }),
109
+ : t('ses.failed', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }),
110
110
  );
111
111
  } finally {
112
112
  st.busy = false;
package/src/state.mjs CHANGED
@@ -4,7 +4,7 @@ import { positiveEnv } from './app.mjs';
4
4
  import { t } from './i18n.mjs';
5
5
  import { canUseEngine, modelAllowed, parseJson } from './access.mjs';
6
6
  import { actualModelFromUpdate, DEFAULT_ENGINE, ENGINES, createAgent, engineCommand, engineMode, getEngine, modeAllowed, resolveEngine } from './engines.mjs';
7
- import { HOME, ROOT, insideRoot, isPersonalRoot, isWithin, pushRecent, samePath, showPath, userRoot } from './projects.mjs';
7
+ import { HOME, ROOT, USER_WORKSPACES, insideRoot, isPersonalRoot, isWithin, pushRecent, samePath, showPath, userRoot } from './projects.mjs';
8
8
  import { SANDBOX, agentSandbox } from './sandbox.mjs';
9
9
  import { GIT_AGENT_AUTH, agentGitEnv, refreshAccounts } from './gitAccess.mjs';
10
10
 
@@ -26,6 +26,9 @@ export const isAdmin = (id) => id === ADMIN_ID;
26
26
  */
27
27
  export const rootOf = (userId) => userRoot(userId, { admin: isAdmin(userId) });
28
28
 
29
+ /** Корень для маскировки путей в сообщениях об ошибках: только сотрудник с личным пространством. */
30
+ export const errorRootOf = (userId) => (USER_WORKSPACES && !isAdmin(userId) ? rootOf(userId) : null);
31
+
29
32
  /** Папка, с которой начинает пользователь: его корень, а без корня — домашняя папка. */
30
33
  export const defaultDirOf = (userId) => rootOf(userId) ?? HOME;
31
34
 
package/src/telegram.mjs CHANGED
@@ -33,19 +33,27 @@ export class TelegramError extends Error {
33
33
 
34
34
  /**
35
35
  * Вызов метода Bot API: тайм-аут на запрос и повтор после 429 (не больше retries раз).
36
- * После тайм-аута не повторяем: сообщение могло уже дойти, повтор продублировал бы его.
36
+ * С retryTransient — ещё и повтор при сетевой ошибке и 5xx (только для итоговой отправки: черновики и команды
37
+ * повторять бессмысленно). После тайм-аута не повторяем: сообщение могло уже дойти, повтор продублировал бы его.
37
38
  * @param {() => Promise<RequestInit>|RequestInit} makeInit тело запроса (для повтора собирается заново)
38
- * @param {{timeoutMs?: number, retries?: number, signal?: AbortSignal, fetchImpl?: typeof fetch}} [o]
39
+ * @param {{timeoutMs?: number, retries?: number, retryTransient?: boolean, signal?: AbortSignal, fetchImpl?: typeof fetch}} [o]
39
40
  */
40
- export async function callApi(method, makeInit, { timeoutMs = TIMEOUT_MS, retries = 2, signal, fetchImpl = fetch } = {}) {
41
+ export async function callApi(method, makeInit, { timeoutMs = TIMEOUT_MS, retries = 2, retryTransient = false, signal, fetchImpl = fetch } = {}) {
42
+ const backoff = (attempt) => sleep(200 * 2 ** attempt);
41
43
  for (let attempt = 0; ; attempt++) {
42
44
  const limit = AbortSignal.timeout(timeoutMs);
45
+ const init = await makeInit();
43
46
  let data;
44
47
  try {
45
- const res = await fetchImpl(`${BASE}/${method}`, { method: 'POST', ...(await makeInit()), signal: signal ? AbortSignal.any([signal, limit]) : limit });
48
+ const res = await fetchImpl(`${BASE}/${method}`, { method: 'POST', ...init, signal: signal ? AbortSignal.any([signal, limit]) : limit });
46
49
  data = await res.json();
47
50
  } catch (e) {
48
51
  if (limit.aborted && !signal?.aborted) throw i18nError(`Telegram ${method}: нет ответа за ${Math.round(timeoutMs / 1000)} с`, 'err.tgTimeout', { method, sec: Math.round(timeoutMs / 1000) }, {}, { cause: e });
52
+ if (retryTransient && attempt < retries) {
53
+ logError(`Telegram ${method}: сеть, повтор ${attempt + 1}/${retries}:`, e.message);
54
+ await backoff(attempt);
55
+ continue;
56
+ }
49
57
  throw e;
50
58
  }
51
59
  if (data.ok) return data.result;
@@ -54,6 +62,11 @@ export async function callApi(method, makeInit, { timeoutMs = TIMEOUT_MS, retrie
54
62
  await sleep(err.retryAfter * 1000 + 250);
55
63
  continue;
56
64
  }
65
+ if (retryTransient && err.code >= 500 && attempt < retries) {
66
+ logError(`Telegram ${method}: HTTP ${err.code}, повтор ${attempt + 1}/${retries}`);
67
+ await backoff(attempt);
68
+ continue;
69
+ }
57
70
  throw err;
58
71
  }
59
72
  }
@@ -220,12 +233,13 @@ export const stripMedia = (md) => md.replace(MEDIA_LINE, '').replace(/\n{3,}/g,
220
233
  const kindIn = (md, id) => new RegExp(`tg://(photo|document)\\?id=${id}\\)`).exec(md)?.[1] ?? 'document';
221
234
 
222
235
  /** Одно rich-сообщение с файлами; если Telegram отверг фото — повтор, где все фото идут документами. */
223
- async function sendRichMedia(to, md, ids, media) {
236
+ async function sendRichMedia(to, md, ids, media, opts = {}) {
224
237
  const send = (text) =>
225
238
  tgForm(
226
239
  'sendRichMessage',
227
240
  { ...dest(to), rich_message: { markdown: text, media: ids.map((id) => ({ id, media: { type: kindIn(text, id), media: `attach://${id}` } })) } },
228
241
  Object.fromEntries(ids.map((id) => [id, media[id]])),
242
+ opts,
229
243
  );
230
244
  try {
231
245
  return await send(md);
@@ -244,13 +258,14 @@ async function sendRichMedia(to, md, ids, media) {
244
258
  * Если Telegram отверг разметку — отправляем обычным текстом.
245
259
  * @returns {Promise<object[]>} файлы из media, которые не удалось вставить в сообщение
246
260
  */
247
- export async function sendRich(to, markdown, { media = {} } = {}) {
261
+ export async function sendRich(to, markdown, { media = {}, ...opts } = {}) {
262
+ const finalOpts = { retryTransient: true, ...opts }; // итоговый ответ повторяем при 5xx/сети; черновики — нет
248
263
  const leftover = [];
249
264
  for (let part of splitRich(markdown, RICH_LIMIT)) {
250
265
  const ids = mediaIdsOf(part).filter((id) => media[id]);
251
266
  if (ids.length) {
252
267
  try {
253
- await sendRichMedia(to, part, ids, media);
268
+ await sendRichMedia(to, part, ids, media, finalOpts);
254
269
  continue;
255
270
  } catch (e) {
256
271
  logError('rich-сообщение с файлами не прошло, файлы уйдут отдельно:', e.message);
@@ -260,10 +275,13 @@ export async function sendRich(to, markdown, { media = {} } = {}) {
260
275
  }
261
276
  }
262
277
  try {
263
- await tg('sendRichMessage', { ...dest(to), rich_message: { markdown: part } });
278
+ await tg('sendRichMessage', { ...dest(to), rich_message: { markdown: part } }, finalOpts);
264
279
  } catch (e) {
280
+ // обычным текстом отправляем только когда Telegram отверг именно разметку (400): при 5xx/сети сообщение
281
+ // могло дойти, и повтор в другом виде продублировал бы его в чате
282
+ if (!(e instanceof TelegramError && e.code === 400)) throw e;
265
283
  logError('sendRichMessage не прошёл, отправляю обычным текстом:', e.message);
266
- for (const plain of splitText(richToPlain(part), 4000)) await tg('sendMessage', { ...dest(to), text: plain });
284
+ for (const plain of splitText(richToPlain(part), 4000)) await tg('sendMessage', { ...dest(to), text: plain }, finalOpts);
267
285
  }
268
286
  }
269
287
  return leftover;
package/src/topicsUi.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // новая тема вместо сброса текущего диалога.
3
3
  import { botInfo, db, langOf, log, say } from './ctx.mjs';
4
4
  import { errText, t } from './i18n.mjs';
5
- import { engineOf, setTopicsMode, statesOf, stopUser, topicProject, topicsOn, topicsSupport, userPath } from './state.mjs';
5
+ import { engineOf, errorRootOf, setTopicsMode, statesOf, stopUser, topicProject, topicsOn, topicsSupport, userPath } from './state.mjs';
6
6
  import { tg } from './telegram.mjs';
7
7
  import { createTopic, topicLink, topicName } from './topics.mjs';
8
8
 
@@ -75,7 +75,7 @@ export async function newTopic(st, { project = st.project } = {}) {
75
75
  threadId = await createTopic(st.chatId, name);
76
76
  } catch (e) {
77
77
  log('создание темы:', e.message, '| пользователь', st.userId);
78
- return say(st.to, t('topics.createFail', lang, { msg: errText(e, lang) }));
78
+ return say(st.to, t('topics.createFail', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }));
79
79
  }
80
80
  const engine = engineOf(st);
81
81
  db.saveTopic(st.userId, threadId, { name, named: false, project, engine: engine.id });
package/src/turn.mjs CHANGED
@@ -6,7 +6,7 @@ import { ModelAccessError, choiceName, getCatalog, syncSelection } from './acces
6
6
  import { parseUsage, permissionOptions } from './engines.mjs';
7
7
  import { SESSION_OPTION_ID, allowOnceOption, describeRule, permissionKeys, rulesAllow, withSessionOption } from './permRules.mjs';
8
8
  import { errText, t } from './i18n.mjs';
9
- import { ClosedError, LimitError, ProjectError, dropPermissions, engineOf, ensureAgent, modeFor, setPermissionHandler, topicProject, userPath } from './state.mjs';
9
+ import { ClosedError, LimitError, ProjectError, dropPermissions, engineOf, ensureAgent, errorRootOf, modeFor, setPermissionHandler, topicProject, userPath } from './state.mjs';
10
10
  import { clipText } from './clip.mjs';
11
11
  import { positiveEnv } from './app.mjs';
12
12
  import { clearStopTimer, forceStopAfter } from './forceStop.mjs';
@@ -26,6 +26,9 @@ const DRAFT_WAIT_MS = 3000; // сколько итоговый ответ ждё
26
26
  const OUTBOX_NOTE_EVERY = 10; // подсказка об отправке файлов — в первом запросе сессии и затем раз в столько запросов
27
27
  const HEARTBEAT_MS = 8000; // черновик живёт 30 с — обновляем и без изменений
28
28
  const TURN_IDLE_MS = positiveEnv('TURN_IDLE_MINUTES', 0) * 60_000;
29
+ const MAX_ANSWER_CHARS = 1024 * 1024; // ответ длиннее всё равно не поместится в сообщения Telegram — ограничиваем память и черновик
30
+ const MAX_THOUGHT_BUF = 4096; // из заголовка мыслей нужна только последняя строка, лишнее не накапливаем
31
+ const MAX_STEPS = 5000;
29
32
 
30
33
  // ---- запрос разрешения: inline-кнопки (приходят самому пользователю, чей это запрос) ----
31
34
  const PERM_KINDS = ['allow_once', 'allow_always', 'reject_once', 'reject_always'];
@@ -228,11 +231,11 @@ async function nameTopic(st, title) {
228
231
  async function sendLooseFiles(st, files, lang) {
229
232
  for (const f of files) {
230
233
  try {
231
- await sendFile(st.to, f.buffer ? { buffer: f.buffer, name: f.name, size: f.size } : f.path, { photo: f.photo, size: f.size });
234
+ await sendFile(st.to, f.buffer ? { buffer: f.buffer, name: f.name, size: f.size } : f.path, { photo: f.photo, size: f.size, retryTransient: true });
232
235
  log('файл отправлен пользователю отдельно', st.userId, f.path);
233
236
  } catch (e) {
234
237
  log('отправка файла:', e.message);
235
- await say(st.to, t('file.sendFail', lang, { name: f.name, why: t('file.why.error', lang, { msg: errText(e, lang) }) }));
238
+ await say(st.to, t('file.sendFail', lang, { name: f.name, why: t('file.why.error', lang, { msg: errText(e, lang, errorRootOf(st.userId)) }) }));
236
239
  }
237
240
  }
238
241
  }
@@ -270,9 +273,18 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
270
273
  const draftId = (Date.now() % 2_000_000_000) + 1;
271
274
  const startedAt = Date.now();
272
275
  let answer = '';
276
+ let answerTruncated = false;
273
277
  let thoughtBuf = '';
274
278
  let thought = '';
275
279
  const steps = []; // ход работы: инструменты агента
280
+ let stepsTruncated = false;
281
+ const addAnswer = (part) => {
282
+ if (!part) return;
283
+ const room = MAX_ANSWER_CHARS - answer.length;
284
+ if (part.length <= room) return void (answer += part);
285
+ answer += part.slice(0, Math.max(0, room));
286
+ answerTruncated = true;
287
+ };
276
288
  let plan = []; // план агента (ACP plan): пункты с отметками выполнения
277
289
  let breakBeforeText = false;
278
290
  let dirty = true;
@@ -314,21 +326,25 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
314
326
  const kind = u.sessionUpdate;
315
327
  if (kind === 'agent_message_chunk' && u.content?.type === 'text') {
316
328
  // текст после вызова инструмента — новый абзац, иначе фразы склеиваются («…test.Команда…»)
317
- if (breakBeforeText && answer.trim()) answer += '\n\n';
329
+ if (breakBeforeText && answer.trim()) addAnswer('\n\n');
318
330
  breakBeforeText = false;
319
- answer += u.content.text;
331
+ addAnswer(u.content.text);
320
332
  dirty = true;
321
333
  } else if (kind === 'agent_thought_chunk' && u.content?.type === 'text') {
322
334
  // заголовок — **строка** без переводов строки, поэтому храним только незаконченную строку: раньше на каждом
323
335
  // фрагменте заново разбирались все рассуждения целиком (на длинных — квадратичная работа)
324
336
  const last = lastThoughtTitle(thoughtBuf + u.content.text);
325
337
  if (last.title) thought = last.title;
326
- thoughtBuf = last.rest;
338
+ thoughtBuf = last.rest.slice(-MAX_THOUGHT_BUF);
327
339
  dirty = true;
328
340
  } else if (kind === 'tool_call') {
329
341
  const tool = parseTool(u, engine);
330
342
  breakBeforeText = true;
331
- steps.push(tool);
343
+ if (steps.length < MAX_STEPS) steps.push(tool);
344
+ else if (!stepsTruncated) {
345
+ stepsTruncated = true;
346
+ log(`ход работы урезан до ${MAX_STEPS} шагов u${st.userId}`);
347
+ }
332
348
  db.toolStarted(requestId, tool);
333
349
  dirty = true;
334
350
  } else if (kind === 'plan' && Array.isArray(u.entries)) {
@@ -389,8 +405,9 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
389
405
  limited = true;
390
406
  answer = e.message; // понятное сообщение без пометки «Ошибка»
391
407
  } else {
392
- log('ошибка запроса:', e.message);
393
- answer += `\n\n${t('turn.error', lang, { msg: errText(e, lang) })}`;
408
+ log('ошибка запроса:', e.message, '| пользователь', st.userId, '| stopReason', stopReason);
409
+ dbg('ошибка запроса, стек:', e.stack);
410
+ addAnswer(`\n\n${t('turn.error', lang, { msg: errText(e, lang, errorRootOf(st.userId)) })}`);
394
411
  }
395
412
  if (!requestId) requestId = db.startRequest(st.agent?.dbSessionId ?? null, dbText);
396
413
  } finally {
@@ -424,6 +441,7 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
424
441
  }
425
442
  let final = answerText ? sent.text.trim() : sent.paths.length && !limited ? `${t('turn.files', lang)}\n\n${sent.text.trim()}` : t('turn.empty', lang);
426
443
  if (stopReason === 'cancelled') final += `\n\n${t('turn.stopped', lang)}`;
444
+ if (answerTruncated) final += `\n\n${t('turn.truncated', lang)}`;
427
445
  // файлы — прямо в ответе, на месте меток (Bot API 10.3); не поместившиеся по размеру — отдельно после ответа
428
446
  const placed = limited
429
447
  ? { text: final.replace(FILE_PLACEHOLDER, ''), media: {}, extra: [] }
@@ -446,8 +464,8 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
446
464
  });
447
465
  loose.push(...left);
448
466
  }
449
- const inAnswer = Object.keys(placed.media).length - loose.length;
450
- if (inAnswer > 0) log('файлы в ответе:', inAnswer, '| пользователь', st.userId);
467
+ const inAnswer = Object.entries(placed.media).filter(([, f]) => !loose.includes(f)).map(([, f]) => f.name ?? f.path);
468
+ if (inAnswer.length) log('файлы в ответе:', inAnswer.join(', '), '| пользователь', st.userId);
451
469
  if (loose.length || placed.extra.length) await sendLooseFiles(st, [...loose, ...placed.extra], lang);
452
470
  // агент попросил отправить или получить изменения: кнопка под ответом, без нажатия ничего не уходит
453
471
  if (!limited && gitted.actions.length) await offerGitActions(st, gitted.actions).catch((e) => log('git: предложение агента:', e.message));