acpgram 1.31.4 → 1.31.7

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.31.4",
3
+ "version": "1.31.7",
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",
@@ -0,0 +1,127 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { closeSync, fstatSync, lstatSync, openSync, readFileSync, readSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { isWithin } from './projects.mjs';
5
+
6
+ export class AgentFileError extends Error {
7
+ constructor(code) {
8
+ super(code);
9
+ this.code = code;
10
+ }
11
+ }
12
+
13
+ const real = (p) => {
14
+ try {
15
+ return realpathSync.native(p);
16
+ } catch {
17
+ return null;
18
+ }
19
+ };
20
+
21
+ const lstat = (p) => {
22
+ try {
23
+ return lstatSync(p);
24
+ } catch (e) {
25
+ if (e.code === 'ENOENT') return null;
26
+ throw e;
27
+ }
28
+ };
29
+
30
+ export function openVerified(path, { allowed = () => true, maxBytes = Infinity, allowEmpty = false, noFollow = false } = {}) {
31
+ if (noFollow) {
32
+ const original = lstat(path);
33
+ if (!original) throw new AgentFileError('missing');
34
+ if (!original.isFile()) throw new AgentFileError(original.isSymbolicLink() ? 'link' : 'notfile');
35
+ }
36
+ const first = real(path);
37
+ if (!first) throw new AgentFileError('missing');
38
+ if (!allowed(first)) throw new AgentFileError('denied');
39
+ const st = lstat(first);
40
+ if (!st) throw new AgentFileError('missing');
41
+ if (!st.isFile()) throw new AgentFileError(st.isSymbolicLink() ? 'link' : 'notfile');
42
+ if (st.size === 0 && !allowEmpty) throw new AgentFileError('empty');
43
+ if (st.size > maxBytes) throw new AgentFileError('big');
44
+ let fd;
45
+ try {
46
+ fd = openSync(first, 'r');
47
+ const fst = fstatSync(fd);
48
+ if (!fst.isFile() || fst.size !== st.size) throw new AgentFileError('changed');
49
+ const second = real(path);
50
+ if (!second || !allowed(second)) throw new AgentFileError('changed');
51
+ const st2 = lstat(second);
52
+ if (second !== first || !st2 || st2.dev !== fst.dev || st2.ino !== fst.ino || st2.size !== fst.size) throw new AgentFileError('changed');
53
+ return { fd, path: first, size: fst.size, dev: fst.dev, ino: fst.ino };
54
+ } catch (e) {
55
+ if (fd != null) closeSync(fd);
56
+ throw e;
57
+ }
58
+ }
59
+
60
+ export function readFd(fd, size) {
61
+ const buf = Buffer.allocUnsafe(size);
62
+ let offset = 0;
63
+ while (offset < size) {
64
+ const n = readSync(fd, buf, offset, size - offset, offset);
65
+ if (n <= 0) break;
66
+ offset += n;
67
+ }
68
+ return offset === size ? buf : buf.subarray(0, offset);
69
+ }
70
+
71
+ export function readStable(path, opts = {}) {
72
+ let h;
73
+ try {
74
+ h = openVerified(path, opts);
75
+ const buffer = readFd(h.fd, h.size);
76
+ verifyStable(h.fd, h.path);
77
+ return { ok: true, path: h.path, size: h.size, buffer };
78
+ } catch (e) {
79
+ if (e instanceof AgentFileError) return { ok: false, reason: e.code };
80
+ throw e;
81
+ } finally {
82
+ if (h) closeSync(h.fd);
83
+ }
84
+ }
85
+
86
+ export function verifyStable(fd, path) {
87
+ const fst = fstatSync(fd);
88
+ const cur = lstat(path);
89
+ if (!cur || !cur.isFile() || cur.dev !== fst.dev || cur.ino !== fst.ino || cur.size !== fst.size) throw new AgentFileError('changed');
90
+ return real(path);
91
+ }
92
+
93
+ export function updateNoFollow(file, root, update) {
94
+ const top = real(root);
95
+ if (!top) throw new AgentFileError('outside');
96
+ const st = lstat(file);
97
+ let have = '';
98
+ if (st) {
99
+ if (!st.isFile()) throw new AgentFileError(st.isSymbolicLink() ? 'link' : 'notfile');
100
+ const target = real(file);
101
+ if (!target || !isWithin(target, top)) throw new AgentFileError('outside');
102
+ have = readFileSync(target, 'utf8');
103
+ }
104
+ const data = update(have);
105
+ if (data === have) return false;
106
+ const tmp = join(dirname(file), `.acpgram-${randomBytes(8).toString('hex')}.tmp`);
107
+ let fd;
108
+ try {
109
+ fd = openSync(tmp, 'wx', 0o600);
110
+ const realTmp = real(tmp);
111
+ if (!realTmp || !isWithin(realTmp, top)) throw new AgentFileError('outside');
112
+ const buf = Buffer.from(data, 'utf8');
113
+ let offset = 0;
114
+ while (offset < buf.length) offset += writeSync(fd, buf, offset, buf.length - offset);
115
+ } catch (e) {
116
+ if (fd != null) closeSync(fd);
117
+ try {
118
+ unlinkSync(tmp);
119
+ } catch {
120
+ void 0;
121
+ }
122
+ throw e;
123
+ }
124
+ closeSync(fd);
125
+ renameSync(tmp, file);
126
+ return true;
127
+ }
package/src/files.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  // Файлы агента — по метке [[send:путь]] в ответе: отправляются только из каталога исходящих и из папки проекта.
5
5
  import { existsSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
+ import { readStable } from './agentFiles.mjs';
7
8
  import { DATA_DIR, ENV_PATH, positiveEnv } from './app.mjs';
8
9
  import { isWithin } from './projects.mjs';
9
10
  import { PHOTO_MAX, mediaBlock } from './telegram.mjs';
@@ -268,7 +269,7 @@ export const MAX_EMBED_BYTES = 45 * 1024 * 1024;
268
269
  * доступный файл — блоком rich-сообщения (фото или документ), недоступный — строкой failText(имя, причина).
269
270
  * Файлы сверх maxBytes (суммарно) — в extra: уйдут отдельными сообщениями после ответа.
270
271
  * @param {{cwd: string, outbox: string, failText: (name: string, reason: string) => string, onSkip?: (path: string, reason: string) => void, maxBytes?: number}} o
271
- * @returns {{text: string, media: Object<string, {path: string, name: string, size: number, photo: boolean}>, extra: object[]}}
272
+ * @returns {{text: string, media: Object<string, {path: string, name: string, size: number, buffer: Buffer, photo: boolean}>, extra: object[]}}
272
273
  */
273
274
  export function attachFiles(text, paths, { cwd, outbox, failText, onSkip = () => {}, maxBytes = MAX_EMBED_BYTES }) {
274
275
  const media = {};
@@ -287,7 +288,7 @@ export function attachFiles(text, paths, { cwd, outbox, failText, onSkip = () =>
287
288
  onSkip(p, r.reason);
288
289
  return failText(basename(p), r.reason);
289
290
  }
290
- const file = { path: r.path, name: basename(r.path), size: r.size, photo: ['image/jpeg', 'image/png'].includes(imageMimeOf(r.path)) && r.size <= PHOTO_MAX };
291
+ const file = { path: r.path, name: r.name, size: r.size, buffer: r.buffer, photo: ['image/jpeg', 'image/png'].includes(imageMimeOf(r.path)) && r.size <= PHOTO_MAX };
291
292
  if (r.size > budget) {
292
293
  extra.push(file);
293
294
  return null;
@@ -351,22 +352,17 @@ export function isSecret(path) {
351
352
  /**
352
353
  * Проверка файла к отправке пользователю. Разрешено: каталог исходящих пользователя (outbox) и папка проекта (cwd),
353
354
  * без секретов, только обычные файлы до MAX_FILE_BYTES. Ссылки и «..» разрешаются до проверки.
354
- * @returns {{ok: true, path: string, size: number} | {ok: false, reason: 'missing'|'notfile'|'denied'|'empty'|'big'}}
355
+ * @returns {{ok: true, path: string, name: string, size: number, buffer: Buffer} | {ok: false, reason: 'missing'|'notfile'|'denied'|'changed'|'empty'|'big'}}
355
356
  */
356
357
  export function resolveSendable(p, { cwd, outbox, maxBytes = MAX_FILE_BYTES }) {
357
358
  const abs = isAbsolute(p) ? p : resolve(cwd, p);
358
- const file = real(abs);
359
- if (!file) return { ok: false, reason: 'missing' };
360
- const st = statSync(file);
361
- if (!st.isFile()) return { ok: false, reason: 'notfile' };
362
359
  const outboxReal = outbox && real(outbox);
363
360
  const cwdReal = cwd && real(cwd);
364
- const inOutbox = Boolean(outboxReal && isWithin(file, outboxReal));
365
- // в каталоге исходящих проверяется только имя внутри него (сам каталог лежит в данных бота): скопированный туда .env или ключ
366
- // не отправится; из проекта — ещё и каталог данных бота и его .env
367
- const allowed = inOutbox ? !isSecretName(join(sep, relative(outboxReal, file))) : Boolean(cwdReal && isWithin(file, cwdReal) && !isSecret(file));
368
- if (!allowed) return { ok: false, reason: 'denied' };
369
- if (st.size === 0) return { ok: false, reason: 'empty' };
370
- if (st.size > maxBytes) return { ok: false, reason: 'big' };
371
- return { ok: true, path: file, size: st.size };
361
+ const allowed = (file) => {
362
+ const inOutbox = Boolean(outboxReal && isWithin(file, outboxReal));
363
+ return inOutbox ? !isSecretName(join(sep, relative(outboxReal, file))) : Boolean(cwdReal && isWithin(file, cwdReal) && !isSecret(file));
364
+ };
365
+ const r = readStable(abs, { allowed, maxBytes });
366
+ if (!r.ok) return r;
367
+ return { ...r, name: basename(r.path) };
372
368
  }
package/src/git.mjs CHANGED
@@ -5,10 +5,10 @@
5
5
  // Поэтому: хуки отключены, общий и системный конфиги не читаются (где это возможно), вход передаётся только через
6
6
  // окружение процесса, а при включённой песочнице (AGENT_SANDBOX) git запускается в песочнице того же сотрудника.
7
7
  import { spawn } from 'node:child_process';
8
- import { appendFileSync, existsSync, readFileSync } from 'node:fs';
9
8
  import { devNull } from 'node:os';
10
9
  import { join } from 'node:path';
11
10
  import { checkCommand, killTree } from './acp.mjs';
11
+ import { AgentFileError, updateNoFollow } from './agentFiles.mjs';
12
12
  import { agentEnv } from './engines.mjs';
13
13
  import { isSecretName } from './files.mjs';
14
14
  import { resolveProgram } from './winsvc.mjs';
@@ -215,9 +215,10 @@ export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEA
215
215
 
216
216
  /**
217
217
  * Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
218
- * @returns {Promise<{committed: boolean, skipped: string[], tracked: string[]}>} committed — коммит создан (было что
219
- * коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы с секретами, которые уже
220
- * были в репозитории: их изменения в коммит не вошли
218
+ * @returns {Promise<{committed: boolean, skipped: string[], tracked: string[], ignoreWarning: boolean}>} committed —
219
+ * коммит создан (было что коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы
220
+ * с секретами, которые уже были в репозитории: их изменения в коммит не вошли; ignoreWarning — .gitignore
221
+ * подменён ссылкой или недоступен, правила туда не записаны
221
222
  */
222
223
  export async function commitAll(cwd, message, opts = {}) {
223
224
  await runGit(['add', '-A'], { cwd, ...opts });
@@ -228,19 +229,31 @@ export async function commitAll(cwd, message, opts = {}) {
228
229
  const secrets = staged.filter((f) => f.status !== 'D' && isSecretName(`/${f.name}`));
229
230
  const skipped = secrets.filter((f) => f.status === 'A').map((f) => f.name);
230
231
  const tracked = secrets.filter((f) => f.status !== 'A').map((f) => f.name);
232
+ const ignored = [];
233
+ let ignoreWarning = false;
231
234
  if (secrets.length) {
232
235
  await runGit(['reset', '-q', '--', ...secrets.map((f) => f.name)], { cwd, ...opts });
233
236
  if (skipped.length) {
234
237
  const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
235
238
  const file = join(top, '.gitignore');
236
- const have = existsSync(file) ? readFileSync(file, 'utf8') : '';
237
- const lines = skipped.map((n) => `/${n}`).filter((l) => !have.split(/\r?\n/).includes(l));
238
- if (lines.length) appendFileSync(file, `${have && !have.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n`);
239
- await runGit(['add', '--', '.gitignore'], { cwd: top, ...opts });
239
+ try {
240
+ let lines = [];
241
+ const changed = updateNoFollow(file, top, (have) => {
242
+ lines = skipped.map((n) => `/${n}`).filter((l) => !have.split(/\r?\n/).includes(l));
243
+ return lines.length ? `${have}${have && !have.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n` : have;
244
+ });
245
+ ignored.push(...lines.map((l) => l.slice(1)));
246
+ if (changed) await runGit(['add', '--', '.gitignore'], { cwd: top, ...opts });
247
+ } catch (e) {
248
+ if (e instanceof AgentFileError && ['link', 'notfile', 'outside', 'changed'].includes(e.code)) {
249
+ ignoreWarning = true;
250
+ await runGit(['reset', '-q', '--', '.gitignore'], { cwd: top, ...opts });
251
+ } else throw e;
252
+ }
240
253
  }
241
254
  }
242
255
  const left = (await runGit(['diff', '--cached', '--name-only'], { cwd, ...opts })).trim();
243
- if (!left) return { committed: false, skipped, tracked };
256
+ if (!left) return { committed: false, skipped: ignored, tracked, ignoreWarning };
244
257
  await runGit(['commit', '-q', '-m', message], { cwd, ...opts });
245
- return { committed: true, skipped, tracked };
258
+ return { committed: true, skipped: ignored, tracked, ignoreWarning };
246
259
  }
@@ -91,7 +91,11 @@ async function publish(st, project, lang, edit, h) {
91
91
  await pushRepo(project, opts);
92
92
  log('git: проект опубликован:', st.userId, project, '→', created.path);
93
93
  st.gitPublish = null;
94
- const note = first.skipped.length ? `\n${th('git.skipped', lang, { files: first.skipped.join(', ') })}` : '';
94
+ const note = [
95
+ ...(first.skipped.length ? [th('git.skipped', lang, { files: first.skipped.join(', ') })] : []),
96
+ ...(first.tracked.length ? [th('git.tracked', lang, { files: first.tracked.join(', ') })] : []),
97
+ ...(first.ignoreWarning ? [th('git.ignoreLink', lang)] : []),
98
+ ].map((s) => `\n${s}`).join('');
95
99
  const v = await h.view();
96
100
  const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
97
101
  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] } });
package/src/gitRepoUi.mjs CHANGED
@@ -2,17 +2,16 @@
2
2
  // ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
3
3
  // без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
4
4
  // Вызывается из gitUi.mjs, который передаёт сюда общие помощники (h): проект, репозиторий, запуск git.
5
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
6
- import { basename, join } from 'node:path';
5
+ import { basename } from 'node:path';
7
6
  import { log, say } from './ctx.mjs';
8
- import { isSecretName, outboxDir, safeFileName } from './files.mjs';
7
+ import { isSecretName, safeFileName } from './files.mjs';
9
8
  import { canManageFiles } from './filesUi.mjs';
10
9
  import { GitError, fetchRepo } from './git.mjs';
11
10
  import { recall, remember } from './gitKeys.mjs';
12
11
  import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
13
12
  import { errText, t } from './i18n.mjs';
14
13
  import { endAgent, userPath } from './state.mjs';
15
- import { escHtml, sendFile } from './telegram.mjs';
14
+ import { escHtml, sendBuffer } from './telegram.mjs';
16
15
  import { hCode, th } from './ui.mjs';
17
16
 
18
17
  /** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
@@ -84,16 +83,8 @@ async function showDiff(st, project, file, index, opts, lang, edit) {
84
83
  const diff = await fileDiff(project, file, opts);
85
84
  if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
86
85
  if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
87
- // большой diff — файлом через каталог исходящих пользователя; после отправки файл не нужен
88
- const dir = outboxDir(st.userId);
89
- mkdirSync(dir, { recursive: true });
90
- const path = join(dir, `${safeFileName(basename(file.path))}.diff`);
91
- writeFileSync(path, diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`);
92
- try {
93
- await sendFile(st.to, path);
94
- } finally {
95
- rmSync(path, { force: true });
96
- }
86
+ const content = diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`;
87
+ await sendBuffer(st.to, Buffer.from(content), `${safeFileName(basename(file.path))}.diff`);
97
88
  return edit({ text: th('git.diff.sent', lang, { path: hCode(file.path) }), markup: back });
98
89
  }
99
90
 
package/src/gitUi.mjs CHANGED
@@ -226,6 +226,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
226
226
  const r = await commitAll(project, message, opts);
227
227
  if (r.skipped.length) note += `\n${th('git.skipped', lang, { files: r.skipped.join(', ') })}`;
228
228
  if (r.tracked.length) note += `\n${th('git.tracked', lang, { files: r.tracked.join(', ') })}`;
229
+ if (r.ignoreWarning) note += `\n${th('git.ignoreLink', lang)}`;
229
230
  const after = await repoState(project, opts);
230
231
  if (!r.committed && !after?.ahead && after?.upstream) return await done(th('git.savedNothing', lang) + note);
231
232
  } else await edit({ text: th('git.pushing', lang) });
package/src/i18n.mjs CHANGED
@@ -344,6 +344,7 @@ const M = {
344
344
  'git.saved': { en: "✅ The changes were saved and pushed.", ru: "✅ Изменения сохранены и отправлены.", uk: "✅ Зміни збережено й надіслано." },
345
345
  'git.savedNothing': { en: "ℹ️ There are no changes — nothing to save.", ru: "ℹ️ Изменений нет — сохранять нечего.", uk: "ℹ️ Змін немає — зберігати нічого." },
346
346
  'git.skipped': { en: "Files with secrets were left out of the commit and added to .gitignore: {files}", ru: "Файлы с секретами в коммит не вошли и добавлены в .gitignore: {files}", uk: "Файли із секретами до коміту не ввійшли й додані в .gitignore: {files}" },
347
+ 'git.ignoreLink': { en: "⚠️ .gitignore is a shortcut or cannot be changed, so rules for files with secrets were not added. Fix .gitignore manually.", ru: "⚠️ .gitignore — это ссылка или его нельзя изменить: правила для файлов с секретами не добавлены. Исправьте .gitignore вручную.", uk: "⚠️ .gitignore — це посилання або його не можна змінити, тому правила для файлів із секретами не додано. Виправте .gitignore вручну." },
347
348
  'git.tracked': { en: "⚠️ Files with secrets are already in the repository; their changes were not pushed: {files}", ru: "⚠️ Файлы с секретами уже есть в репозитории, их изменения не отправлены: {files}", uk: "⚠️ Файли із секретами вже є в репозиторії, їхні зміни не надіслано: {files}" },
348
349
  'git.syncFail': { en: "⚠️ Could not check the server: {msg}", ru: "⚠️ Не удалось свериться с сервером: {msg}", uk: "⚠️ Не вдалося звіритися із сервером: {msg}" },
349
350
  'git.hostsBtn': { en: "⚙️ Own servers", ru: "⚙️ Свои серверы", uk: "⚙️ Свої сервери" },
@@ -555,6 +556,7 @@ const M = {
555
556
  'file.why.missing': { en: 'the file does not exist', ru: 'файл не найден', uk: 'файл не знайдено' },
556
557
  'file.why.notfile': { en: 'this is not a regular file', ru: 'это не обычный файл', uk: 'це не звичайний файл' },
557
558
  'file.why.denied': { en: 'the file is outside the allowed folders or is protected', ru: 'файл вне разрешённых папок или защищён', uk: 'файл поза дозволеними теками або захищений' },
559
+ 'file.why.changed': { en: 'the file changed while it was being checked', ru: 'файл изменился во время проверки', uk: 'файл змінився під час перевірки' },
558
560
  'file.why.empty': { en: 'the file is empty', ru: 'файл пустой', uk: 'файл порожній' },
559
561
  'file.why.big': { en: 'the file is larger than 20 MB', ru: 'файл больше 20 МБ', uk: 'файл більший за 20 МБ' },
560
562
  'file.why.error': { en: 'Telegram rejected the file ({msg})', ru: 'Telegram не принял файл ({msg})', uk: 'Telegram не прийняв файл ({msg})' },
@@ -6,6 +6,7 @@
6
6
  import { randomBytes } from 'node:crypto';
7
7
  import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
+ import { AgentFileError, openVerified, verifyStable } from './agentFiles.mjs';
9
10
  import { isWithin } from './projects.mjs';
10
11
 
11
12
  /** Наибольшая длина одного имени в пути и наибольшая вложенность. */
@@ -124,11 +125,21 @@ export function writeProjectFile(project, dir, parts, data, { replace = false }
124
125
  /** Удаляет файл проекта (только обычный файл, не папку и не ссылку). */
125
126
  export function deleteProjectFile(project, path) {
126
127
  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);
128
+ let handle;
129
+ try {
130
+ handle = openVerified(path, { allowed: (file) => isWithin(file, root), allowEmpty: true, noFollow: true });
131
+ verifyStable(handle.fd, path);
132
+ unlinkSync(path);
133
+ } catch (e) {
134
+ if (e instanceof AgentFileError) {
135
+ if (e.code === 'missing') throw new FileError('missing');
136
+ if (e.code === 'link' || e.code === 'notfile') throw new FileError(e.code === 'link' ? 'link' : 'isdir');
137
+ throw new FileError('outside');
138
+ }
139
+ throw e;
140
+ } finally {
141
+ if (handle) closeSync(handle.fd);
142
+ }
132
143
  }
133
144
 
134
145
  /**
package/src/telegram.mjs CHANGED
@@ -76,36 +76,43 @@ export async function downloadFile(file_id) {
76
76
 
77
77
  /**
78
78
  * Запрос с загрузкой файлов (multipart/form-data). fields — параметры метода (объекты передаются JSON),
79
- * files — {имя поля: {path, name?}}; файл читается с диска потоком, а не целиком в память.
79
+ * files — {имя поля: {path, name?} | {buffer, name}}; файл с диска читается потоком, buffer — из памяти.
80
80
  */
81
- function tgForm(method, fields, files = {}) {
81
+ function tgForm(method, fields, files = {}, opts = {}) {
82
82
  const makeInit = async () => {
83
83
  const form = new FormData();
84
84
  for (const [k, v] of Object.entries(fields)) if (v != null) form.append(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
85
- for (const [k, f] of Object.entries(files)) form.append(k, await openAsBlob(f.path), f.name ?? basename(f.path));
85
+ for (const [k, f] of Object.entries(files)) {
86
+ const blob = f.buffer ? new Blob([f.buffer]) : await openAsBlob(f.path);
87
+ form.append(k, blob, f.name ?? (f.buffer ? 'file' : basename(f.path)));
88
+ }
86
89
  return { body: form };
87
90
  };
88
- return callApi(method, makeInit, { timeoutMs: UPLOAD_TIMEOUT_MS });
91
+ return callApi(method, makeInit, { timeoutMs: UPLOAD_TIMEOUT_MS, ...opts });
89
92
  }
90
93
 
91
94
  /** Отправка файла пользователю отдельным сообщением. */
92
- const uploadFile = (method, field, to, path) => tgForm(method, dest(to), { [field]: { path } });
95
+ const uploadFile = (method, field, to, file, opts = {}) => tgForm(method, dest(to), { [field]: typeof file === 'string' ? { path: file } : file }, opts);
93
96
 
94
97
  /** Telegram принимает фото до 10 МБ; больше — только документом. */
95
98
  export const PHOTO_MAX = 10 * 1024 * 1024;
96
99
 
97
100
  /** Файл как документ; картинку (до 10 МБ) — как фото, а если Telegram отверг фото, то документом. */
98
- export async function sendFile(to, path, { photo = false, size = 0 } = {}) {
101
+ export async function sendFile(to, source, { photo = false, size = 0, ...opts } = {}) {
102
+ const file = typeof source === 'string' ? { path: source } : source;
99
103
  if (photo && size <= PHOTO_MAX) {
100
104
  try {
101
- return await uploadFile('sendPhoto', 'photo', to, path);
105
+ return await uploadFile('sendPhoto', 'photo', to, file, opts);
102
106
  } catch (e) {
103
107
  logError('sendPhoto не прошёл, отправляю документом:', e.message);
104
108
  }
105
109
  }
106
- return uploadFile('sendDocument', 'document', to, path);
110
+ return uploadFile('sendDocument', 'document', to, file, opts);
107
111
  }
108
112
 
113
+ /** Отправляет уже проверенный буфер без обращения к диску. */
114
+ export const sendBuffer = (to, buffer, name, opts = {}) => sendFile(to, { buffer, name, size: buffer.length }, { ...opts, size: buffer.length });
115
+
109
116
  /** Экранирует текст для вставки в HTML-теги rich-разметки. */
110
117
  export const escHtml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
111
118
 
package/src/turn.mjs CHANGED
@@ -220,7 +220,7 @@ async function nameTopic(st, title) {
220
220
  async function sendLooseFiles(st, files, lang) {
221
221
  for (const f of files) {
222
222
  try {
223
- await sendFile(st.to, f.path, { photo: f.photo, size: f.size });
223
+ await sendFile(st.to, f.buffer ? { buffer: f.buffer, name: f.name, size: f.size } : f.path, { photo: f.photo, size: f.size });
224
224
  log('файл отправлен пользователю отдельно', st.userId, f.path);
225
225
  } catch (e) {
226
226
  log('отправка файла:', e.message);