acpgram 1.31.5 → 1.31.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -250,7 +250,7 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
250
250
 
251
251
  **Where the token lives.** By default only in the bot's database: the bot clones, pulls and pushes, while the agent works with the repository locally (status, diff, commits, branches, merges) and sends the user to `/git` when changes must be pushed. In the sandbox the token is not reachable by the agent at all. The administrator can choose another mode, `GIT_AGENT_AUTH=1`: the sign-in is also given to the agent process, which then pulls and pushes by itself. That is more convenient, but the token becomes visible to the agent and may end up in a model request; turn it on only if you trust the models your teammates use.
252
252
 
253
- **How the bot runs git.** The repository lives where the agent writes, and repository settings and hooks can run programs. So the bot runs git with hooks and credential helpers turned off, without the global and system config (on Linux and macOS), and, when the sandbox is on, inside the same teammate's sandbox. The sign-in is passed to the git process through its environment and only for the addresses of its own service; it is never written to the repository settings or the URL. Residual risk: the repository's own settings (filters) run during operations, and a deliberately malicious agent could capture the token while an operation runs.
253
+ **How the bot runs git.** The repository lives where the agent writes, and repository settings and hooks can run programs. So the bot runs git with hooks, credential helpers and password prompts turned off, without the global and system config (on Linux and macOS), over HTTPS only, and, when the sandbox is on, inside the same teammate's sandbox. Before operations with sign-in and commits, the local `.git/config` is checked: commands, external includes, filters (except Git LFS) and disabled TLS verification are rejected, and only setting names are shown in the reply. The sign-in is needed only for cloning, pulling, pushing, switching branches and creating a merge request; local commands run without it and it is never written to the repository settings or the URL. Only one git operation runs per repository folder, and a failed clone leaves no partial folder behind. Residual risk: on Windows the global and system config is still read, Git LFS filters run during operations, and without the sandbox a deliberately malicious agent could change the local config between the check and the command.
254
254
 
255
255
  Only HTTPS repositories from the listed services can be connected; a repository with an SSH address or from another server is shown, but the bot cannot pull from or push to it.
256
256
 
package/README.ru.md CHANGED
@@ -138,7 +138,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
138
138
 
139
139
  **Где лежит токен.** По умолчанию — только в базе бота: клонирование, получение и отправку делает бот, а агент работает с репозиторием локально (состояние, сравнение, коммиты, ветки, слияние) и на просьбу отправить изменения направляет пользователя в `/git`. В песочнице токен агенту недоступен совсем. Администратор может выбрать другой режим — `GIT_AGENT_AUTH=1`: вход передаётся и процессу агента, он сам получает и отправляет изменения. Это удобнее, но токен становится виден агенту и может попасть в запрос к модели; включайте его, только если доверяете моделям, с которыми работают сотрудники.
140
140
 
141
- **Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками и помощниками входа, без общего и системного конфига (на Linux и macOS), а при включённой песочнице — внутри песочницы того же сотрудника. Вход передаётся процессу git через окружение и только для адресов своего сервиса; в настройки репозитория и в адрес он не пишется. Остаточный риск: настройки самого репозитория (фильтры) выполняются при операциях, и намеренно вредоносный агент мог бы перехватить токен во время операции.
141
+ **Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками, помощниками входа и запросом пароля, без общего и системного конфига (на Linux и macOS), только по HTTPS, а при включённой песочнице — внутри песочницы того же сотрудника. Перед операциями со входом и коммитом проверяется локальный `.git/config`: команды, внешние include, фильтры (кроме Git LFS) и отключённая проверка TLS отклоняются, в ответе показываются только имена параметров. Вход нужен только для клонирования, получения, отправки, смены ветки и запроса на слияние; локальные команды запускаются без него и в настройки репозитория он не пишется. На одну папку репозитория одновременно работает одна операция, а неудавшийся клон не оставляет частичную папку. Остаточный риск: на Windows читается глобальный и системный конфиг, фильтры Git LFS выполняются при операциях, а без песочницы намеренно вредоносный агент мог бы изменить локальный конфиг между проверкой и командой.
142
142
 
143
143
  Подключаются только репозитории по HTTPS с перечисленных сервисов; репозиторий с адресом SSH или с другого сервера бот показывает, но получать и отправлять в него не может.
144
144
 
@@ -432,6 +432,7 @@ src/
432
432
  projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
433
433
  filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
434
434
  git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
435
+ gitCtx.mjs общие настройки запуска, выбор аккаунта и блокировки для экранов git
435
436
  gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
436
437
  gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
437
438
  gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.31.5",
3
+ "version": "1.31.8",
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';
@@ -54,7 +54,10 @@ export const SAFE_CONFIG = [
54
54
  ['core.hooksPath', devNull],
55
55
  ['core.fsmonitor', 'false'],
56
56
  ['credential.helper', ''],
57
+ ['protocol.allow', 'never'],
58
+ ['protocol.https.allow', 'always'],
57
59
  ['protocol.ext.allow', 'never'],
60
+ ['safe.bareRepository', 'explicit'],
58
61
  ['advice.detachedHead', 'false'],
59
62
  ['core.quotePath', 'false'], // имена файлов не латиницей — как есть, а не восьмеричными кодами
60
63
  ];
@@ -65,7 +68,7 @@ export const SAFE_CONFIG = [
65
68
  * На Linux и macOS общий и системный конфиги не читаются: в песочнице общий конфиг лежит в папке, куда пишет агент.
66
69
  */
67
70
  export function gitEnv({ identity = null, auth = [], base = process.env } = {}) {
68
- const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
71
+ const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_ASKPASS: '', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
69
72
  if (!IS_WIN) Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' });
70
73
  if (identity?.name && identity?.email) {
71
74
  Object.assign(env, { GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email, GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
@@ -83,6 +86,13 @@ export class GitError extends Error {
83
86
  }
84
87
  }
85
88
 
89
+ export class GitConfigError extends GitError {
90
+ constructor(keys) {
91
+ super(`небезопасные настройки репозитория: ${keys.join(', ')}`);
92
+ this.keys = keys;
93
+ }
94
+ }
95
+
86
96
  /**
87
97
  * Запускает git. Без оболочки: аргументы (описание коммита, имена файлов) передаются как есть.
88
98
  * @param {string[]} args
@@ -138,6 +148,28 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
138
148
  });
139
149
  }
140
150
 
151
+ const DENIED_CONFIG = (key) =>
152
+ ['core.sshcommand', 'core.askpass', 'gpg.program', 'core.alternaterefscommand'].includes(key) ||
153
+ key === 'include.path' ||
154
+ /^includeif\..*\.path$/.test(key) ||
155
+ /^remote\..+\.(uploadpack|receivepack)$/.test(key) ||
156
+ (/^filter\./.test(key) && !key.startsWith('filter.lfs.'));
157
+
158
+ const isFalse = (value) => /^(false|no|off|0)$/i.test(String(value).trim());
159
+
160
+ export async function assertPlainConfig(cwd, opts = {}) {
161
+ const raw = await runGit(['config', '--local', '--list', '-z'], { cwd, ...opts });
162
+ const bad = [];
163
+ for (const rec of raw.split('\0')) {
164
+ if (!rec) continue;
165
+ const cut = rec.indexOf('\n');
166
+ const key = (cut < 0 ? rec : rec.slice(0, cut)).toLowerCase();
167
+ const value = cut < 0 ? '' : rec.slice(cut + 1);
168
+ if (DENIED_CONFIG(key) || (/^http(\..+)?\.sslverify$/.test(key) && isFalse(value))) bad.push(key);
169
+ }
170
+ if (bad.length) throw new GitConfigError([...new Set(bad)]);
171
+ }
172
+
141
173
  /**
142
174
  * Разбор `git status --porcelain=v2 --branch`.
143
175
  * @returns {{branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}}
@@ -174,17 +206,26 @@ export async function repoState(cwd, opts = {}) {
174
206
  }
175
207
 
176
208
  /** Клонирует репозиторий url в папку dest (её ещё нет), запускается из её родительской папки cwd. Подмодули не тянутся. */
177
- export const cloneRepo = (url, dest, { cwd, ...opts }) => runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
209
+ export async function cloneRepo(url, dest, { cwd, ...opts }) {
210
+ await runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
211
+ await assertPlainConfig(join(cwd, dest), opts);
212
+ }
213
+
214
+ const fetchRaw = (cwd, opts) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
178
215
 
179
216
  /** Сверяется с сервером (git fetch): рабочие файлы не трогает, обновляет сведения о ветках сервера. */
180
- export const fetchRepo = (cwd, opts = {}) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
217
+ export async function fetchRepo(cwd, opts = {}) {
218
+ await assertPlainConfig(cwd, opts);
219
+ return fetchRaw(cwd, opts);
220
+ }
181
221
 
182
222
  /**
183
223
  * Получает изменения с сервера: fetch и перемотка вперёд, если это возможно без слияния.
184
224
  * @returns {Promise<'updated'|'uptodate'|'diverged'|'noupstream'>} diverged — истории разошлись, нужно слияние (его делает агент)
185
225
  */
186
226
  export async function pullRepo(cwd, opts = {}) {
187
- await fetchRepo(cwd, opts);
227
+ await assertPlainConfig(cwd, opts);
228
+ await fetchRaw(cwd, opts);
188
229
  const before = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
189
230
  if (!before.upstream) return 'noupstream';
190
231
  if (!before.behind) return 'uptodate';
@@ -211,15 +252,20 @@ export async function unpushedSecrets(cwd, opts = {}) {
211
252
  }
212
253
 
213
254
  /** Отправляет текущую ветку на сервер (и связывает её с веткой сервера). */
214
- export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
255
+ export async function pushRepo(cwd, opts = {}) {
256
+ await assertPlainConfig(cwd, opts);
257
+ return runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
258
+ }
215
259
 
216
260
  /**
217
261
  * Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
218
- * @returns {Promise<{committed: boolean, skipped: string[], tracked: string[]}>} committed — коммит создан (было что
219
- * коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы с секретами, которые уже
220
- * были в репозитории: их изменения в коммит не вошли
262
+ * @returns {Promise<{committed: boolean, skipped: string[], tracked: string[], ignoreWarning: boolean}>} committed —
263
+ * коммит создан (было что коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы
264
+ * с секретами, которые уже были в репозитории: их изменения в коммит не вошли; ignoreWarning — .gitignore
265
+ * подменён ссылкой или недоступен, правила туда не записаны
221
266
  */
222
267
  export async function commitAll(cwd, message, opts = {}) {
268
+ await assertPlainConfig(cwd, opts);
223
269
  await runGit(['add', '-A'], { cwd, ...opts });
224
270
  const staged = (await runGit(['diff', '--cached', '--name-status'], { cwd, ...opts }))
225
271
  .split(/\r?\n/)
@@ -228,19 +274,31 @@ export async function commitAll(cwd, message, opts = {}) {
228
274
  const secrets = staged.filter((f) => f.status !== 'D' && isSecretName(`/${f.name}`));
229
275
  const skipped = secrets.filter((f) => f.status === 'A').map((f) => f.name);
230
276
  const tracked = secrets.filter((f) => f.status !== 'A').map((f) => f.name);
277
+ const ignored = [];
278
+ let ignoreWarning = false;
231
279
  if (secrets.length) {
232
280
  await runGit(['reset', '-q', '--', ...secrets.map((f) => f.name)], { cwd, ...opts });
233
281
  if (skipped.length) {
234
282
  const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
235
283
  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 });
284
+ try {
285
+ let lines = [];
286
+ const changed = updateNoFollow(file, top, (have) => {
287
+ lines = skipped.map((n) => `/${n}`).filter((l) => !have.split(/\r?\n/).includes(l));
288
+ return lines.length ? `${have}${have && !have.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n` : have;
289
+ });
290
+ ignored.push(...lines.map((l) => l.slice(1)));
291
+ if (changed) await runGit(['add', '--', '.gitignore'], { cwd: top, ...opts });
292
+ } catch (e) {
293
+ if (e instanceof AgentFileError && ['link', 'notfile', 'outside', 'changed'].includes(e.code)) {
294
+ ignoreWarning = true;
295
+ await runGit(['reset', '-q', '--', '.gitignore'], { cwd: top, ...opts });
296
+ } else throw e;
297
+ }
240
298
  }
241
299
  }
242
300
  const left = (await runGit(['diff', '--cached', '--name-only'], { cwd, ...opts })).trim();
243
- if (!left) return { committed: false, skipped, tracked };
301
+ if (!left) return { committed: false, skipped: ignored, tracked, ignoreWarning };
244
302
  await runGit(['commit', '-q', '-m', message], { cwd, ...opts });
245
- return { committed: true, skipped, tracked };
303
+ return { committed: true, skipped: ignored, tracked, ignoreWarning };
246
304
  }
package/src/gitCtx.mjs ADDED
@@ -0,0 +1,68 @@
1
+ import { resolve } from 'node:path';
2
+ import { db } from './ctx.mjs';
3
+ import { accountsOf, hostFor, identityOf } from './gitAccess.mjs';
4
+ import { authConfig, HostError } from './gitHosts.mjs';
5
+ import { gitCommand, gitEnv, GitConfigError, GitError, repoState } from './git.mjs';
6
+ import { errText } from './i18n.mjs';
7
+ import { insideRoot, isPersonalRoot, ROOT } from './projects.mjs';
8
+ import { agentSandbox } from './sandbox.mjs';
9
+ import { rootOf, sandboxed } from './state.mjs';
10
+ import { th } from './ui.mjs';
11
+
12
+ export const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
13
+
14
+ const baseOpts = (st, cwd, account, auth, hide) => {
15
+ const root = rootOf(st.userId);
16
+ const wrap = sandboxed(st.userId)
17
+ ? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
18
+ : null;
19
+ return { env: gitEnv({ identity: identityOf(account), auth }), wrap, hide };
20
+ };
21
+
22
+ export function gitOpts(st, cwd, account = null) {
23
+ const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
24
+ return baseOpts(st, cwd, who, [], []);
25
+ }
26
+
27
+ export function gitNetOpts(st, cwd, { host, account }) {
28
+ const auth = host && account ? authConfig(host, account.token) : [];
29
+ const hide = account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [];
30
+ return baseOpts(st, cwd, account, auth, hide);
31
+ }
32
+
33
+ export async function repoOf(st, project) {
34
+ const state = await repoState(project, gitOpts(st, project));
35
+ if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
36
+ const host = hostFor(state.remote);
37
+ const account = host ? db.getGitAccount(st.userId, host.id) : null;
38
+ return { state, host, account };
39
+ }
40
+
41
+ export const failText = (e, lang, host = null) => {
42
+ 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) });
45
+ };
46
+
47
+ const gitLocks = new Map();
48
+ const lockKey = (cwd) => {
49
+ const p = resolve(String(cwd ?? ''));
50
+ return process.platform === 'win32' ? p.toLowerCase() : p;
51
+ };
52
+
53
+ export function acquireGitLock(st, cwd) {
54
+ const key = lockKey(cwd);
55
+ if (gitLocks.has(key)) return null;
56
+ const token = Symbol('git');
57
+ gitLocks.set(key, token);
58
+ st.gitBusy = true;
59
+ return { key, token };
60
+ }
61
+
62
+ export function releaseGitLock(st, lock) {
63
+ if (!lock) return;
64
+ if (gitLocks.get(lock.key) === lock.token) gitLocks.delete(lock.key);
65
+ st.gitBusy = false;
66
+ }
67
+
68
+ export const isGitLocked = (cwd) => gitLocks.has(lockKey(cwd));
@@ -3,7 +3,7 @@
3
3
  // безопасными настройками и, при включённой песочнице, внутри неё.
4
4
  import { lstatSync, readFileSync } from 'node:fs';
5
5
  import { join, resolve } from 'node:path';
6
- import { GitError, runGit } from './git.mjs';
6
+ import { assertPlainConfig, GitError, runGit } from './git.mjs';
7
7
  import { samePath } from './projects.mjs';
8
8
 
9
9
  /** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
@@ -158,12 +158,16 @@ export async function branchName(input, { cwd, ...opts }) {
158
158
  */
159
159
  export async function switchBranch(cwd, branch, opts = {}) {
160
160
  if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
161
+ await assertPlainConfig(cwd, opts);
161
162
  if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
162
163
  return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
163
164
  }
164
165
 
165
166
  /** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
166
- export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
167
+ export async function createBranch(cwd, name, opts = {}) {
168
+ await assertPlainConfig(cwd, opts);
169
+ return runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
170
+ }
167
171
 
168
172
  /**
169
173
  * Отменяет несохранённые изменения файлов (записи из changedFiles): изменённые и удалённые возвращаются к последнему
@@ -172,6 +176,7 @@ export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet
172
176
  */
173
177
  export async function discardFiles(cwd, files, opts = {}) {
174
178
  if (!files.length) return 0;
179
+ await assertPlainConfig(cwd, opts);
175
180
  const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
176
181
  const at = { cwd: top, ...opts };
177
182
  const paths = [...new Set(files.flatMap((f) => [f.path, f.from]).filter(Boolean))];
@@ -2,17 +2,18 @@
2
2
  // Публикация: папка, которая ещё не связана с сервером, становится репозиторием — пользователь выбирает сервис, место
3
3
  // (личное пространство, группа или организация), видимость и название; бот создаёт репозиторий, делает первый коммит
4
4
  // (без файлов с секретами) и отправляет. Запрос на слияние: из текущей ветки в основную ветку репозитория.
5
- // Вызывается из gitUi.mjs, который передаёт общие помощники (h).
5
+ // Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
6
6
  import { basename } from 'node:path';
7
7
  import { db, log, say } from './ctx.mjs';
8
8
  import { canManageFiles } from './filesUi.mjs';
9
- import { GitError, commitAll, pushRepo, repoState } from './git.mjs';
9
+ import { commitAll, pushRepo, repoState } from './git.mjs';
10
10
  import { accountsOf, findHost, hostFor } from './gitAccess.mjs';
11
+ import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
11
12
  import { recall, remember } from './gitKeys.mjs';
12
13
  import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visibilities } from './gitApi.mjs';
13
14
  import { HostError, showRemote } from './gitHosts.mjs';
14
15
  import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
15
- import { errText, t } from './i18n.mjs';
16
+ import { t } from './i18n.mjs';
16
17
  import { userPath } from './state.mjs';
17
18
  import { hCode, th } from './ui.mjs';
18
19
 
@@ -27,16 +28,10 @@ const VIS_MARK = { private: '🔒', internal: '🏢', public: '🌍' };
27
28
  const backRow = (lang) => [{ text: t('btn.back', lang), callback_data: 'gt:v' }];
28
29
  const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
29
30
 
30
- /** Текст ошибки: не хватило прав токена — отдельной подсказкой (нужен токен с правом api). */
31
- const failText = (e, lang, host) => {
32
- if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
33
- return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
34
- };
35
-
36
31
  /** Можно ли публиковать проект: это ещё не репозиторий с адресом сервера (свой репозиторий без origin — тоже можно). */
37
- export async function canPublish(st, project, h) {
32
+ export async function canPublish(st, project) {
38
33
  if (!canManageFiles(st.userId) || !accountsOf(st.userId).length) return false;
39
- const opts = h.gitOpts(st, project);
34
+ const opts = gitOpts(st, project);
40
35
  if (!(await isRepoRoot(project, opts))) return true;
41
36
  return !(await repoState(project, opts))?.remote;
42
37
  }
@@ -72,11 +67,13 @@ function summaryView(st, project, lang) {
72
67
  }
73
68
 
74
69
  /** Создаёт репозиторий на сервисе, делает первый коммит и отправляет. */
75
- async function publish(st, project, lang, edit, h) {
70
+ async function publish(st, project, lang, edit, view) {
76
71
  const pub = st.gitPublish;
77
72
  const { host, account } = accountOf(st, pub);
78
- const opts = h.gitOpts(st, project, { host, account });
79
- st.gitBusy = true;
73
+ const opts = gitOpts(st, project, account);
74
+ const net = gitNetOpts(st, project, { host, account });
75
+ const lock = acquireGitLock(st, project);
76
+ if (!lock) return edit({ text: t('git.busy', lang), markup: { inline_keyboard: [backRow(lang)] } });
80
77
  try {
81
78
  await edit({ text: th('git.pb.working', lang) });
82
79
  // сначала локальная часть: если публиковать нечего, репозиторий на сервере не создаётся
@@ -88,25 +85,29 @@ async function publish(st, project, lang, edit, h) {
88
85
  // адрес из ответа сервиса уходит в настройки репозитория: чужой адрес (или не адрес вовсе) не принимаем
89
86
  if (hostFor(created.url)?.id !== host.id) throw new HostError('http', `${host.label}: unexpected repository address`);
90
87
  await setRemote(project, created.url, opts);
91
- await pushRepo(project, opts);
88
+ await pushRepo(project, net);
92
89
  log('git: проект опубликован:', st.userId, project, '→', created.path);
93
90
  st.gitPublish = null;
94
- const note = first.skipped.length ? `\n${th('git.skipped', lang, { files: first.skipped.join(', ') })}` : '';
95
- const v = await h.view();
91
+ const note = [
92
+ ...(first.skipped.length ? [th('git.skipped', lang, { files: first.skipped.join(', ') })] : []),
93
+ ...(first.tracked.length ? [th('git.tracked', lang, { files: first.tracked.join(', ') })] : []),
94
+ ...(first.ignoreWarning ? [th('git.ignoreLink', lang)] : []),
95
+ ].map((s) => `\n${s}`).join('');
96
+ const v = await view();
96
97
  const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
97
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] } });
98
99
  } catch (e) {
99
100
  log('git: публикация:', e.message, '| пользователь', st.userId);
100
101
  return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
101
102
  } finally {
102
- st.gitBusy = false;
103
+ releaseGitLock(st, lock);
103
104
  }
104
105
  }
105
106
 
106
107
  /** Создаёт запрос на слияние текущей ветки в основную (или находит уже открытый) и даёт ссылку. */
107
- async function mergeRequest(st, project, title, lang, edit, h) {
108
+ async function mergeRequest(st, project, title, lang, edit) {
108
109
  const mr = st.gitMr;
109
- const repo = await h.repoOf(st, project);
110
+ const repo = await repoOf(st, project);
110
111
  if (!mr || !repo?.account) return edit({ text: th('git.diff.gone', lang), markup: { inline_keyboard: [backRow(lang)] } });
111
112
  st.gitMr = null;
112
113
  try {
@@ -120,9 +121,9 @@ async function mergeRequest(st, project, title, lang, edit, h) {
120
121
  }
121
122
  }
122
123
 
123
- /** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). h — помощники из gitUi. */
124
+ /** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). */
124
125
  export async function onPublishCallback(st, cb, h) {
125
- const { action, arg, lang, ack, edit, project } = h;
126
+ const { action, arg, lang, ack, edit, project, view } = h;
126
127
  if (!project) return ack(t('state.projectGone', lang));
127
128
  if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
128
129
  if (st.gitBusy) return ack(t('git.busy', lang));
@@ -130,14 +131,14 @@ export async function onPublishCallback(st, cb, h) {
130
131
  try {
131
132
  // ---- запрос на слияние ----
132
133
  if (action === 'mr') {
133
- const repo = await h.repoOf(st, project);
134
+ const repo = await repoOf(st, project);
134
135
  if (!repo?.account || !repo.state.branch) return ack(t('proj.stale', lang));
135
136
  await ack();
136
137
  const info = await repoInfo(repo.host, repo.account.token, repo.state.remote);
137
138
  const s = repo.state;
138
139
  if (s.branch === info.defaultBranch) return edit({ text: th('git.mr.onDefault', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }], backRow(lang)] } });
139
140
  if (!s.upstream || s.ahead) return edit({ text: th('git.mr.pushFirst', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.push', lang), callback_data: 'gt:push' }], backRow(lang)] } });
140
- const suggested = (await lastSubject(project, h.gitOpts(st, project, repo))) || s.branch;
141
+ const suggested = (await lastSubject(project, gitOpts(st, project, repo.account))) || s.branch;
141
142
  st.gitMr = { branch: s.branch, target: info.defaultBranch, suggested };
142
143
  st.pendingInput = { kind: 'gitMrTitle', at: Date.now() };
143
144
  const markup = { inline_keyboard: [[{ text: [...`«${suggested}»`].slice(0, 60).join(''), callback_data: 'gt:mrgo' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
@@ -146,10 +147,10 @@ export async function onPublishCallback(st, cb, h) {
146
147
  if (action === 'mrgo') {
147
148
  st.pendingInput = null;
148
149
  await ack();
149
- return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit, h);
150
+ return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit);
150
151
  }
151
152
  // ---- публикация ----
152
- if (!(await canPublish(st, project, h))) return ack(t('proj.stale', lang));
153
+ if (!(await canPublish(st, project))) return ack(t('proj.stale', lang));
153
154
  const accounts = accountsOf(st.userId);
154
155
  if (action === 'pb') {
155
156
  await ack();
@@ -196,7 +197,7 @@ export async function onPublishCallback(st, cb, h) {
196
197
  if (action === 'pbgo') {
197
198
  if (!pub.slug) return ack(t('git.pb.nameBad', lang));
198
199
  await ack();
199
- return await publish(st, project, lang, edit, h);
200
+ return await publish(st, project, lang, edit, view);
200
201
  }
201
202
  return ack(t('proj.stale', lang));
202
203
  } catch (e) {
@@ -208,7 +209,7 @@ export async function onPublishCallback(st, cb, h) {
208
209
 
209
210
  /**
210
211
  * Текст пользователя для публикации и запроса на слияние: строка поиска группы, название репозитория, заголовок запроса.
211
- * @param {object} h {wait, now, lang, project, send, repoOf, gitOpts, view}
212
+ * @param {object} h {wait, now, lang, project, send, view}
212
213
  * @returns {Promise<boolean>} true — текст обработан здесь
213
214
  */
214
215
  export async function onPublishInput(st, text, h) {
@@ -218,7 +219,7 @@ export async function onPublishInput(st, text, h) {
218
219
  if (wait.kind === 'gitMrTitle') {
219
220
  if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
220
221
  const title = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || st.gitMr?.suggested || '';
221
- await mergeRequest(st, project, title, lang, send, h);
222
+ await mergeRequest(st, project, title, lang, send);
222
223
  return true;
223
224
  }
224
225
  const pub = st.gitPublish;
package/src/gitRepoUi.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  // Экраны /git «Изменения» и «Ветки»: что изменено в проекте (список файлов, изменения по файлу, неотправленные и
2
2
  // ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
3
3
  // без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
4
- // Вызывается из gitUi.mjs, который передаёт сюда общие помощники (h): проект, репозиторий, запуск git.
5
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
6
- import { basename, join } from 'node:path';
4
+ // Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
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
- import { GitError, fetchRepo } from './git.mjs';
9
+ import { fetchRepo } from './git.mjs';
10
+ import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
11
11
  import { recall, remember } from './gitKeys.mjs';
12
12
  import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
13
- import { errText, t } from './i18n.mjs';
13
+ import { t } from './i18n.mjs';
14
14
  import { endAgent, userPath } from './state.mjs';
15
- import { escHtml, sendFile } from './telegram.mjs';
15
+ import { escHtml, sendBuffer } from './telegram.mjs';
16
16
  import { hCode, th } from './ui.mjs';
17
17
 
18
18
  /** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
@@ -24,7 +24,6 @@ export const DIFF_INLINE_MAX = 3200;
24
24
  const DIFF_FILE_MAX = 1024 * 1024;
25
25
  const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
26
26
 
27
- const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
28
27
  /** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
29
28
  const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
30
29
  const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
@@ -61,9 +60,20 @@ async function changesView(st, project, repo, opts, page, lang) {
61
60
  const isSecretFile = (f) => isSecretName(`/${f.path}`);
62
61
 
63
62
  /** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
64
- async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
63
+ async function branchesView(st, project, repo, opts, net, page, lang, { sync = false } = {}) {
65
64
  // ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
66
- if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
65
+ if (sync && repo.account && net && !st.busy && !st.gitBusy) {
66
+ const lock = acquireGitLock(st, project);
67
+ if (lock) {
68
+ try {
69
+ await fetchRepo(project, net);
70
+ } catch (e) {
71
+ log('git: сверка веток:', e.message, '| пользователь', st.userId);
72
+ } finally {
73
+ releaseGitLock(st, lock);
74
+ }
75
+ }
76
+ }
67
77
  const { current, branches } = await listBranches(project, opts);
68
78
  const pages = Math.max(1, Math.ceil(branches.length / PAGE));
69
79
  page = Math.min(Math.max(page, 0), pages - 1);
@@ -84,16 +94,8 @@ async function showDiff(st, project, file, index, opts, lang, edit) {
84
94
  const diff = await fileDiff(project, file, opts);
85
95
  if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
86
96
  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
- }
97
+ const content = diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`;
98
+ await sendBuffer(st.to, Buffer.from(content), `${safeFileName(basename(file.path))}.diff`);
97
99
  return edit({ text: th('git.diff.sent', lang, { path: hCode(file.path) }), markup: back });
98
100
  }
99
101
 
@@ -107,15 +109,19 @@ async function commitsView(project, opts, which, lang) {
107
109
 
108
110
  /**
109
111
  * Кнопки экранов «Изменения» и «Ветки».
110
- * @param {object} h помощники из gitUi: {action, arg, lang, ack, edit, project, repoOf, gitOpts}
112
+ * @param {object} h {action, arg, lang, ack, edit, project}
111
113
  */
112
114
  export async function onRepoCallback(st, cb, h) {
113
115
  const { action, arg, lang, ack, edit, project } = h;
114
116
  if (!project) return ack(t('state.projectGone', lang));
117
+ const mutating = ['dX', 'dA', 'bs'].includes(action);
118
+ const lock = mutating ? acquireGitLock(st, project) : null;
119
+ if (mutating && !lock) return ack(t('git.busy', lang));
115
120
  try {
116
- const repo = await h.repoOf(st, project);
121
+ const repo = await repoOf(st, project);
117
122
  if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
118
- const opts = h.gitOpts(st, project, repo);
123
+ const opts = gitOpts(st, project, repo.account);
124
+ const net = repo.account ? gitNetOpts(st, project, repo) : null;
119
125
  if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
120
126
  if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
121
127
  if (action === 'cf') {
@@ -126,10 +132,10 @@ export async function onRepoCallback(st, cb, h) {
126
132
  await ack();
127
133
  return await showDiff(st, project, file, arg, opts, lang, edit);
128
134
  }
129
- if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
135
+ if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, net, Number(arg) || 0, lang, { sync: true })));
130
136
  // ---- переключение и создание ветки меняют проект ----
131
137
  if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
132
- if (st.gitBusy) return ack(t('git.busy', lang));
138
+ if (!mutating && st.gitBusy) return ack(t('git.busy', lang));
133
139
  if (st.busy) return ack(t('git.agentBusy', lang));
134
140
  if (action === 'bn') {
135
141
  await ack();
@@ -139,16 +145,9 @@ export async function onRepoCallback(st, cb, h) {
139
145
  // ---- отмена изменений: необратимо, поэтому сначала вопрос, а список файлов берётся заново ----
140
146
  if (['dx', 'dX', 'da', 'dA'].includes(action)) {
141
147
  const fresh = (await changedFiles(project, opts)).files;
142
- const run = async (list) => {
143
- st.gitBusy = true;
144
- try {
145
- return await discardFiles(project, list, opts);
146
- } finally {
147
- st.gitBusy = false;
148
- }
149
- };
148
+ const run = async (list) => discardFiles(project, list, opts);
150
149
  const show = async (note) => {
151
- const v = await changesView(st, project, await h.repoOf(st, project), opts, 0, lang);
150
+ const v = await changesView(st, project, await repoOf(st, project), opts, 0, lang);
152
151
  return edit({ text: `${note}\n\n${v.text}`, markup: v.markup });
153
152
  };
154
153
  if (action === 'dx' || action === 'dX') {
@@ -189,51 +188,53 @@ export async function onRepoCallback(st, cb, h) {
189
188
  return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
190
189
  }
191
190
  await ack();
192
- st.gitBusy = true;
193
- try {
194
- await switchBranch(project, branch, opts);
195
- } finally {
196
- st.gitBusy = false;
197
- }
191
+ await switchBranch(project, branch, net ?? opts);
198
192
  // файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
199
193
  endAgent(st, 'branch');
200
194
  log('git: ветка переключена:', st.userId, project, '→', branch.name);
201
- const v = await branchesView(st, project, repo, opts, 0, lang);
195
+ const v = await branchesView(st, project, repo, opts, net, 0, lang);
202
196
  return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
203
197
  } catch (e) {
204
198
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
205
199
  await ack();
206
200
  return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
201
+ } finally {
202
+ releaseGitLock(st, lock);
207
203
  }
208
204
  }
209
205
 
210
206
  /**
211
207
  * Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
212
208
  * Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
213
- * @param {object} h {wait, now, lang, project, repoOf, gitOpts}
209
+ * @param {object} h {wait, now, lang, project}
214
210
  * @returns {Promise<boolean>} true — текст обработан здесь
215
211
  */
216
212
  export async function onBranchInput(st, text, h) {
217
- const { lang, project } = h;
213
+ const { wait, now, lang, project } = h;
218
214
  const html = { parse_mode: 'HTML' };
219
215
  if (!project || !canManageFiles(st.userId)) return false;
220
216
  if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
217
+ const lock = acquireGitLock(st, project);
218
+ if (!lock) return (await say(st.to, t('git.busy', lang), html), true);
221
219
  try {
222
- const repo = await h.repoOf(st, project);
220
+ const repo = await repoOf(st, project);
223
221
  if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
224
- const opts = h.gitOpts(st, project, repo);
222
+ const opts = gitOpts(st, project, repo.account);
223
+ const net = repo.account ? gitNetOpts(st, project, repo) : null;
225
224
  const name = await branchName(text, { cwd: project, ...opts });
226
225
  if (!name) {
227
- st.pendingInput = { ...h.wait, at: h.now }; // название не подошло — ждём другое
226
+ st.pendingInput = { ...wait, at: now }; // название не подошло — ждём другое
228
227
  return (await say(st.to, t('git.br.badName', lang), { reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } }), true);
229
228
  }
230
- await createBranch(project, name, opts);
229
+ await createBranch(project, name, net ?? opts);
231
230
  log('git: ветка создана:', st.userId, project, name);
232
231
  const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
233
232
  await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
234
233
  } catch (e) {
235
234
  log('git: новая ветка:', e.message, '| пользователь', st.userId);
236
235
  await say(st.to, failText(e, lang), html);
236
+ } finally {
237
+ releaseGitLock(st, lock);
237
238
  }
238
239
  return true;
239
240
  }
package/src/gitUi.mjs CHANGED
@@ -1,21 +1,22 @@
1
1
  // Команда /git: аккаунты GitHub и GitLab пользователя (вход по токену доступа), клонирование репозитория кнопками,
2
2
  // состояние репозитория проекта, «Получить», «Отправить», «Сохранить и отправить».
3
3
  // Токен вводится сообщением, которое не передаётся агенту и удаляется из чата; команды git с входом выполняет бот.
4
+ import { lstatSync, realpathSync, rmSync } from 'node:fs';
4
5
  import { join } from 'node:path';
5
6
  import { db, langOf, log, say } from './ctx.mjs';
6
7
  import { canManageFiles } from './filesUi.mjs';
7
- import { GitError, cloneRepo, commitAll, fetchRepo, gitAvailable, gitCommand, gitEnv, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
8
+ import { cloneRepo, commitAll, fetchRepo, gitAvailable, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
8
9
  import { DeviceError, deviceLogin, startDeviceLogin, waitDeviceLogin } from './gitDevice.mjs';
9
10
  import { recall, remember } from './gitKeys.mjs';
10
- import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, refreshAccounts, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
11
+ import { acquireGitLock, failText, gitNetOpts, gitOpts, projectOf, releaseGitLock, repoOf } from './gitCtx.mjs';
12
+ import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, refreshAccounts, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
11
13
  import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
12
14
  import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
13
- import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
14
- import { LOCALES, errText, t } from './i18n.mjs';
15
- import { ROOT, folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
15
+ import { HostError, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
16
+ import { LOCALES, t } from './i18n.mjs';
17
+ import { folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
16
18
  import { canCreateProject, selectProject } from './projectsUi.mjs';
17
- import { agentSandbox } from './sandbox.mjs';
18
- import { isAdmin, rootOf, sandboxed, userPath } from './state.mjs';
19
+ import { isAdmin, rootOf, userPath } from './state.mjs';
19
20
  import { dest, tg } from './telegram.mjs';
20
21
  import { hCode, th } from './ui.mjs';
21
22
 
@@ -26,32 +27,6 @@ export const GIT_WAIT_MS = 10 * 60_000;
26
27
  const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
27
28
  const dateOf = (iso, lang) => (iso ? new Date(iso).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' }) : '—');
28
29
 
29
- /** Папка проекта диалога, если она доступна, иначе null. */
30
- const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
31
-
32
- /**
33
- * Как запускать git для этого пользователя: окружение (автор коммитов, вход в сервис), песочница сотрудника
34
- * (если она включена) и строки, которые нужно вычистить из сообщений об ошибках.
35
- */
36
- function gitOpts(st, cwd, { host = null, account = null } = {}) {
37
- const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
38
- const auth = host && account ? authConfig(host, account.token) : [];
39
- const root = rootOf(st.userId);
40
- const wrap = sandboxed(st.userId)
41
- ? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
42
- : null;
43
- return { env: gitEnv({ identity: identityOf(who), auth }), wrap, hide: account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [] };
44
- }
45
-
46
- /** Репозиторий проекта и его сервис: {state, host, account} или null, если проект не репозиторий (или репозиторий выше корня пользователя). */
47
- async function repoOf(st, project) {
48
- const state = await repoState(project, gitOpts(st, project));
49
- if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
50
- const host = hostFor(state.remote);
51
- const account = host ? db.getGitAccount(st.userId, host.id) : null;
52
- return { state, host, account };
53
- }
54
-
55
30
  /**
56
31
  * Экран /git: состояние репозитория проекта, аккаунты, кнопки. Текст — HTML.
57
32
  * sync — сначала свериться с сервером (git fetch), чтобы «новых на сервере» было настоящим числом: при открытии экрана
@@ -67,12 +42,17 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
67
42
  let repo = await load();
68
43
  let syncError = null;
69
44
  if (sync && repo?.account && !st.busy && !st.gitBusy) {
70
- try {
71
- await fetchRepo(project, gitOpts(st, project, repo));
72
- repo = await load();
73
- } catch (e) {
74
- log('git: сверка с сервером:', e.message, '| пользователь', st.userId);
75
- syncError = e.message;
45
+ const lock = acquireGitLock(st, project);
46
+ if (lock) {
47
+ try {
48
+ await fetchRepo(project, gitNetOpts(st, project, repo));
49
+ repo = await load();
50
+ } catch (e) {
51
+ log('git: сверка с сервером:', e.message, '| пользователь', st.userId);
52
+ syncError = e.message;
53
+ } finally {
54
+ releaseGitLock(st, lock);
55
+ }
76
56
  }
77
57
  }
78
58
  if (repo) {
@@ -91,7 +71,7 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
91
71
  rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
92
72
  } else lines.push(th('git.noRepo', lang));
93
73
  // папку, которая ещё не связана с сервером, можно опубликовать: бот создаст для неё репозиторий
94
- const publishable = project && !repo?.state.remote ? await canPublish(st, project, { gitOpts }).catch(() => false) : false;
74
+ const publishable = project && !repo?.state.remote ? await canPublish(st, project).catch(() => false) : false;
95
75
  if (publishable) rows.push([{ text: t('git.pbBtn', lang), callback_data: 'gt:pb' }]);
96
76
  lines.push(accounts.length ? [t('git.accounts', lang), ...accounts.map(({ host, account }) => th('git.accLine', lang, { host: host.label, login: account.login }))].join('\n') : th('git.noAccounts', lang));
97
77
  if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
@@ -153,9 +133,6 @@ export async function offerGitActions(st, actions) {
153
133
  return say(st.to, t(actions.length > 1 ? 'git.offer.both' : `git.offer.${actions[0]}`, lang), { reply_markup: { inline_keyboard: [row] } });
154
134
  }
155
135
 
156
- /** Текст ошибки git или сервиса для пользователя. */
157
- const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
158
-
159
136
  /** Куда клонировать: личное пространство сотрудника, иначе — папка рядом с текущим проектом (или корень). */
160
137
  function cloneBase(st) {
161
138
  const root = rootOf(st.userId);
@@ -178,6 +155,17 @@ async function reposView(st, host, account, { page = 0, search = '' } = {}, lang
178
155
  return { text: items.length ? head : `${head}\n\n<i>${th('git.reposNone', lang)}</i>`, markup: { inline_keyboard: rows } };
179
156
  }
180
157
 
158
+ export function cleanFailedClone(st, target, base) {
159
+ try {
160
+ const info = lstatSync(target);
161
+ const real = realpathSync.native(target);
162
+ if (!info.isDirectory() || info.isSymbolicLink() || !insideRoot(real, base)) return;
163
+ rmSync(real, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
164
+ } catch (e) {
165
+ log('git: папка неудачного клона не убрана:', e.message, '| пользователь', st.userId);
166
+ }
167
+ }
168
+
181
169
  /** Клонирует выбранный репозиторий в пространство пользователя и выбирает его проектом. */
182
170
  async function cloneChosen(st, repo, host, account, lang, edit) {
183
171
  const base = cloneBase(st);
@@ -187,9 +175,10 @@ async function cloneChosen(st, repo, host, account, lang, edit) {
187
175
  if (insideRoot(target, rootOf(st.userId))) return edit({ text: th('git.cloneExists', lang, { name: hCode(name), dir: hCode(userPath(st.userId, base, lang)) }) });
188
176
  await edit({ text: th('git.cloning', lang, { name: hCode(repo.name) }) });
189
177
  try {
190
- await cloneRepo(repo.url, name, { cwd: base, ...gitOpts(st, base, { host, account }) });
178
+ await cloneRepo(repo.url, name, { cwd: base, ...gitNetOpts(st, base, { host, account }) });
191
179
  } catch (e) {
192
180
  log('git: клонирование:', e.message, '| пользователь', st.userId);
181
+ cleanFailedClone(st, target, base);
193
182
  return edit({ text: failText(e, lang) });
194
183
  }
195
184
  const dir = insideRoot(target, rootOf(st.userId));
@@ -205,18 +194,20 @@ async function cloneChosen(st, repo, host, account, lang, edit) {
205
194
  */
206
195
  async function repoAction(st, action, lang, edit, { message = null } = {}) {
207
196
  const project = projectOf(st);
208
- const repo = project ? await repoOf(st, project) : null;
209
- if (!repo?.account) return edit(await gitView(st, lang));
210
- const opts = gitOpts(st, project, repo);
197
+ const lock = acquireGitLock(st, project ?? st.userId);
198
+ if (!lock) return edit({ text: t('git.busy', lang) });
211
199
  const done = async (text) => {
212
200
  const v = await gitView(st, lang);
213
201
  return edit({ text: `${text}\n\n${v.text}`, markup: v.markup });
214
202
  };
215
- st.gitBusy = true;
216
203
  try {
204
+ const repo = project ? await repoOf(st, project) : null;
205
+ if (!repo?.account) return edit(await gitView(st, lang));
206
+ const opts = gitOpts(st, project, repo.account);
207
+ const net = gitNetOpts(st, project, repo);
217
208
  if (action === 'pull') {
218
209
  await edit({ text: th('git.pulling', lang) });
219
- const result = await pullRepo(project, opts);
210
+ const result = await pullRepo(project, net);
220
211
  log('git: получено:', st.userId, project, '|', result);
221
212
  return await done(th(`git.pull.${result}`, lang));
222
213
  }
@@ -226,6 +217,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
226
217
  const r = await commitAll(project, message, opts);
227
218
  if (r.skipped.length) note += `\n${th('git.skipped', lang, { files: r.skipped.join(', ') })}`;
228
219
  if (r.tracked.length) note += `\n${th('git.tracked', lang, { files: r.tracked.join(', ') })}`;
220
+ if (r.ignoreWarning) note += `\n${th('git.ignoreLink', lang)}`;
229
221
  const after = await repoState(project, opts);
230
222
  if (!r.committed && !after?.ahead && after?.upstream) return await done(th('git.savedNothing', lang) + note);
231
223
  } else await edit({ text: th('git.pushing', lang) });
@@ -240,7 +232,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
240
232
  const state = await repoState(project, opts);
241
233
  if (state?.upstream && !state.ahead) return await done(th('git.nothingToPush', lang) + note);
242
234
  try {
243
- await pushRepo(project, opts);
235
+ await pushRepo(project, net);
244
236
  } catch (e) {
245
237
  if (/rejected|non-fast-forward|fetch first/i.test(`${e.message} ${e.stderr ?? ''}`)) return await done(th('git.pushRejected', lang) + note);
246
238
  throw e;
@@ -251,7 +243,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
251
243
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
252
244
  return await done(failText(e, lang));
253
245
  } finally {
254
- st.gitBusy = false;
246
+ releaseGitLock(st, lock);
255
247
  }
256
248
  }
257
249
 
@@ -361,9 +353,9 @@ export async function onGitCallback(st, cb) {
361
353
  return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
362
354
  }
363
355
  // экраны «Изменения» и «Ветки» — gitRepoUi
364
- if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
356
+ if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st) });
365
357
  // «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
366
- if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
358
+ if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), view: () => gitView(st, lang) });
367
359
  const host = findHost(arg);
368
360
  const account = host ? db.getGitAccount(st.userId, host.id) : null;
369
361
  try {
@@ -424,13 +416,13 @@ export async function onGitCallback(st, cb) {
424
416
  const acc = h ? db.getGitAccount(st.userId, h.id) : null;
425
417
  if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
426
418
  if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
427
- if (st.gitBusy) return ack(t('git.busy', lang));
419
+ const lock = acquireGitLock(st, cloneBase(st) ?? st.userId);
420
+ if (!lock) return ack(t('git.busy', lang));
428
421
  await ack();
429
- st.gitBusy = true;
430
422
  try {
431
423
  return await cloneChosen(st, repo, h, acc, lang, edit);
432
424
  } finally {
433
- st.gitBusy = false;
425
+ releaseGitLock(st, lock);
434
426
  }
435
427
  }
436
428
  // ---- репозиторий проекта ----
@@ -498,8 +490,8 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
498
490
 
499
491
  st.pendingInput = null;
500
492
  if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
501
- if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
502
- if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
493
+ if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st) });
494
+ if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), view: () => gitView(st, lang) });
503
495
  // свои серверы: адрес нового сервера или новое название — только от администратора
504
496
  if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
505
497
  if (!isAdmin(st.userId)) return false;
package/src/i18n.mjs CHANGED
@@ -324,6 +324,7 @@ const M = {
324
324
  'git.cloneExists': { en: "⚠️ The folder {name} already exists in {dir}. Choose it in /project or rename it.", ru: "⚠️ Папка {name} уже есть в {dir}. Выберите её в /project или переименуйте.", uk: "⚠️ Папка {name} уже є в {dir}. Оберіть її в /project або перейменуйте." },
325
325
  'git.cloneBadName': { en: "⚠️ This repository cannot be cloned here: its name is not suitable for a folder.", ru: "⚠️ Этот репозиторий сюда клонировать нельзя: его название не подходит для папки.", uk: "⚠️ Цей репозиторій сюди клонувати не можна: його назва не підходить для папки." },
326
326
  'git.opFail': { en: "⚠️ Git: {msg}", ru: "⚠️ Git: {msg}", uk: "⚠️ Git: {msg}" },
327
+ 'git.unsafeConfig': { en: "⚠️ Git: unsafe repository settings found: {keys}. Remove them and try again.", ru: "⚠️ Git: в настройках репозитория найдены небезопасные параметры: {keys}. Уберите их и повторите.", uk: "⚠️ Git: у налаштуваннях репозиторію знайдено небезпечні параметри: {keys}. Приберіть їх і повторіть." },
327
328
  'git.busy': { en: "Wait for the current Git operation to finish.", ru: "Дождитесь завершения текущей операции Git.", uk: "Дочекайтеся завершення поточної операції Git." },
328
329
  'git.agentBusy': { en: "First wait for the agent to answer or stop it: /stop", ru: "Сначала дождитесь ответа агента или остановите его: /stop", uk: "Спочатку дочекайтеся відповіді агента або зупиніть його: /stop" },
329
330
  'git.pulling': { en: "⏳ Pulling changes…", ru: "⏳ Получаю изменения…", uk: "⏳ Отримую зміни…" },
@@ -344,6 +345,7 @@ const M = {
344
345
  'git.saved': { en: "✅ The changes were saved and pushed.", ru: "✅ Изменения сохранены и отправлены.", uk: "✅ Зміни збережено й надіслано." },
345
346
  'git.savedNothing': { en: "ℹ️ There are no changes — nothing to save.", ru: "ℹ️ Изменений нет — сохранять нечего.", uk: "ℹ️ Змін немає — зберігати нічого." },
346
347
  'git.skipped': { en: "Files with secrets were left out of the commit and added to .gitignore: {files}", ru: "Файлы с секретами в коммит не вошли и добавлены в .gitignore: {files}", uk: "Файли із секретами до коміту не ввійшли й додані в .gitignore: {files}" },
348
+ '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
349
  'git.tracked': { en: "⚠️ Files with secrets are already in the repository; their changes were not pushed: {files}", ru: "⚠️ Файлы с секретами уже есть в репозитории, их изменения не отправлены: {files}", uk: "⚠️ Файли із секретами вже є в репозиторії, їхні зміни не надіслано: {files}" },
348
350
  'git.syncFail': { en: "⚠️ Could not check the server: {msg}", ru: "⚠️ Не удалось свериться с сервером: {msg}", uk: "⚠️ Не вдалося звіритися із сервером: {msg}" },
349
351
  'git.hostsBtn': { en: "⚙️ Own servers", ru: "⚙️ Свои серверы", uk: "⚙️ Свої сервери" },
@@ -555,6 +557,7 @@ const M = {
555
557
  'file.why.missing': { en: 'the file does not exist', ru: 'файл не найден', uk: 'файл не знайдено' },
556
558
  'file.why.notfile': { en: 'this is not a regular file', ru: 'это не обычный файл', uk: 'це не звичайний файл' },
557
559
  'file.why.denied': { en: 'the file is outside the allowed folders or is protected', ru: 'файл вне разрешённых папок или защищён', uk: 'файл поза дозволеними теками або захищений' },
560
+ 'file.why.changed': { en: 'the file changed while it was being checked', ru: 'файл изменился во время проверки', uk: 'файл змінився під час перевірки' },
558
561
  'file.why.empty': { en: 'the file is empty', ru: 'файл пустой', uk: 'файл порожній' },
559
562
  'file.why.big': { en: 'the file is larger than 20 MB', ru: 'файл больше 20 МБ', uk: 'файл більший за 20 МБ' },
560
563
  '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/state.mjs CHANGED
@@ -124,6 +124,7 @@ export function getState(userId, chatId, threadId = null) {
124
124
  agent: null,
125
125
  engine: row?.engine ?? db.getSetting(`engine:${userId}`), // выбор пользователя; null — движок по умолчанию (DEFAULT_ENGINE)
126
126
  busy: false,
127
+ gitBusy: false,
127
128
  requestId: null,
128
129
  onUpdate: null, // обработчик событий текущего запроса
129
130
  perms: new Map(), // ожидающие запросы разрешений
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);