acpgram 1.31.7 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gitRepoUi.mjs CHANGED
@@ -1,15 +1,16 @@
1
1
  // Экраны /git «Изменения» и «Ветки»: что изменено в проекте (список файлов, изменения по файлу, неотправленные и
2
2
  // ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
3
3
  // без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
4
- // Вызывается из gitUi.mjs, который передаёт сюда общие помощники (h): проект, репозиторий, запуск git.
4
+ // Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
5
5
  import { basename } from 'node:path';
6
6
  import { log, say } from './ctx.mjs';
7
7
  import { isSecretName, safeFileName } from './files.mjs';
8
8
  import { canManageFiles } from './filesUi.mjs';
9
- import { GitError, fetchRepo } from './git.mjs';
9
+ import { fetchRepo } from './git.mjs';
10
+ import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
10
11
  import { recall, remember } from './gitKeys.mjs';
11
12
  import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
12
- import { errText, t } from './i18n.mjs';
13
+ import { t } from './i18n.mjs';
13
14
  import { endAgent, userPath } from './state.mjs';
14
15
  import { escHtml, sendBuffer } from './telegram.mjs';
15
16
  import { hCode, th } from './ui.mjs';
@@ -23,7 +24,6 @@ export const DIFF_INLINE_MAX = 3200;
23
24
  const DIFF_FILE_MAX = 1024 * 1024;
24
25
  const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
25
26
 
26
- const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
27
27
  /** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
28
28
  const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
29
29
  const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
@@ -60,9 +60,20 @@ async function changesView(st, project, repo, opts, page, lang) {
60
60
  const isSecretFile = (f) => isSecretName(`/${f.path}`);
61
61
 
62
62
  /** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
63
- async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
63
+ async function branchesView(st, project, repo, opts, net, page, lang, { sync = false } = {}) {
64
64
  // ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
65
- 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
+ }
66
77
  const { current, branches } = await listBranches(project, opts);
67
78
  const pages = Math.max(1, Math.ceil(branches.length / PAGE));
68
79
  page = Math.min(Math.max(page, 0), pages - 1);
@@ -98,15 +109,19 @@ async function commitsView(project, opts, which, lang) {
98
109
 
99
110
  /**
100
111
  * Кнопки экранов «Изменения» и «Ветки».
101
- * @param {object} h помощники из gitUi: {action, arg, lang, ack, edit, project, repoOf, gitOpts}
112
+ * @param {object} h {action, arg, lang, ack, edit, project}
102
113
  */
103
114
  export async function onRepoCallback(st, cb, h) {
104
115
  const { action, arg, lang, ack, edit, project } = h;
105
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));
106
120
  try {
107
- const repo = await h.repoOf(st, project);
121
+ const repo = await repoOf(st, project);
108
122
  if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
109
- 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;
110
125
  if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
111
126
  if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
112
127
  if (action === 'cf') {
@@ -117,10 +132,10 @@ export async function onRepoCallback(st, cb, h) {
117
132
  await ack();
118
133
  return await showDiff(st, project, file, arg, opts, lang, edit);
119
134
  }
120
- 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 })));
121
136
  // ---- переключение и создание ветки меняют проект ----
122
137
  if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
123
- if (st.gitBusy) return ack(t('git.busy', lang));
138
+ if (!mutating && st.gitBusy) return ack(t('git.busy', lang));
124
139
  if (st.busy) return ack(t('git.agentBusy', lang));
125
140
  if (action === 'bn') {
126
141
  await ack();
@@ -130,16 +145,9 @@ export async function onRepoCallback(st, cb, h) {
130
145
  // ---- отмена изменений: необратимо, поэтому сначала вопрос, а список файлов берётся заново ----
131
146
  if (['dx', 'dX', 'da', 'dA'].includes(action)) {
132
147
  const fresh = (await changedFiles(project, opts)).files;
133
- const run = async (list) => {
134
- st.gitBusy = true;
135
- try {
136
- return await discardFiles(project, list, opts);
137
- } finally {
138
- st.gitBusy = false;
139
- }
140
- };
148
+ const run = async (list) => discardFiles(project, list, opts);
141
149
  const show = async (note) => {
142
- 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);
143
151
  return edit({ text: `${note}\n\n${v.text}`, markup: v.markup });
144
152
  };
145
153
  if (action === 'dx' || action === 'dX') {
@@ -180,51 +188,53 @@ export async function onRepoCallback(st, cb, h) {
180
188
  return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
181
189
  }
182
190
  await ack();
183
- st.gitBusy = true;
184
- try {
185
- await switchBranch(project, branch, opts);
186
- } finally {
187
- st.gitBusy = false;
188
- }
191
+ await switchBranch(project, branch, net ?? opts);
189
192
  // файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
190
193
  endAgent(st, 'branch');
191
194
  log('git: ветка переключена:', st.userId, project, '→', branch.name);
192
- const v = await branchesView(st, project, repo, opts, 0, lang);
195
+ const v = await branchesView(st, project, repo, opts, net, 0, lang);
193
196
  return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
194
197
  } catch (e) {
195
198
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
196
199
  await ack();
197
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);
198
203
  }
199
204
  }
200
205
 
201
206
  /**
202
207
  * Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
203
208
  * Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
204
- * @param {object} h {wait, now, lang, project, repoOf, gitOpts}
209
+ * @param {object} h {wait, now, lang, project}
205
210
  * @returns {Promise<boolean>} true — текст обработан здесь
206
211
  */
207
212
  export async function onBranchInput(st, text, h) {
208
- const { lang, project } = h;
213
+ const { wait, now, lang, project } = h;
209
214
  const html = { parse_mode: 'HTML' };
210
215
  if (!project || !canManageFiles(st.userId)) return false;
211
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);
212
219
  try {
213
- const repo = await h.repoOf(st, project);
220
+ const repo = await repoOf(st, project);
214
221
  if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
215
- 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;
216
224
  const name = await branchName(text, { cwd: project, ...opts });
217
225
  if (!name) {
218
- st.pendingInput = { ...h.wait, at: h.now }; // название не подошло — ждём другое
226
+ st.pendingInput = { ...wait, at: now }; // название не подошло — ждём другое
219
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);
220
228
  }
221
- await createBranch(project, name, opts);
229
+ await createBranch(project, name, net ?? opts);
222
230
  log('git: ветка создана:', st.userId, project, name);
223
231
  const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
224
232
  await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
225
233
  } catch (e) {
226
234
  log('git: новая ветка:', e.message, '| пользователь', st.userId);
227
235
  await say(st.to, failText(e, lang), html);
236
+ } finally {
237
+ releaseGitLock(st, lock);
228
238
  }
229
239
  return true;
230
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
  }
@@ -241,7 +232,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
241
232
  const state = await repoState(project, opts);
242
233
  if (state?.upstream && !state.ahead) return await done(th('git.nothingToPush', lang) + note);
243
234
  try {
244
- await pushRepo(project, opts);
235
+ await pushRepo(project, net);
245
236
  } catch (e) {
246
237
  if (/rejected|non-fast-forward|fetch first/i.test(`${e.message} ${e.stderr ?? ''}`)) return await done(th('git.pushRejected', lang) + note);
247
238
  throw e;
@@ -252,7 +243,7 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
252
243
  log(`git: ${action}:`, e.message, '| пользователь', st.userId);
253
244
  return await done(failText(e, lang));
254
245
  } finally {
255
- st.gitBusy = false;
246
+ releaseGitLock(st, lock);
256
247
  }
257
248
  }
258
249
 
@@ -362,9 +353,9 @@ export async function onGitCallback(st, cb) {
362
353
  return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
363
354
  }
364
355
  // экраны «Изменения» и «Ветки» — gitRepoUi
365
- 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) });
366
357
  // «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
367
- 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) });
368
359
  const host = findHost(arg);
369
360
  const account = host ? db.getGitAccount(st.userId, host.id) : null;
370
361
  try {
@@ -425,13 +416,13 @@ export async function onGitCallback(st, cb) {
425
416
  const acc = h ? db.getGitAccount(st.userId, h.id) : null;
426
417
  if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
427
418
  if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
428
- 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));
429
421
  await ack();
430
- st.gitBusy = true;
431
422
  try {
432
423
  return await cloneChosen(st, repo, h, acc, lang, edit);
433
424
  } finally {
434
- st.gitBusy = false;
425
+ releaseGitLock(st, lock);
435
426
  }
436
427
  }
437
428
  // ---- репозиторий проекта ----
@@ -499,8 +490,8 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
499
490
 
500
491
  st.pendingInput = null;
501
492
  if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
502
- if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
503
- 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) });
504
495
  // свои серверы: адрес нового сервера или новое название — только от администратора
505
496
  if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
506
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: "⏳ Отримую зміни…" },
@@ -532,6 +533,7 @@ const M = {
532
533
  'perm.res.cancelled': { en: '✖️ Request cancelled', ru: '✖️ Запрос отменён', uk: '✖️ Запит скасовано' },
533
534
  'perm.blocked': { en: '🔒 The agent requested an action that is not allowed at your access level — rejected.\n{head}: {what}', ru: '🔒 Агент запросил действие, недоступное на вашем уровне доступа, — отклонено.\n{head}: {what}', uk: '🔒 Агент запросив дію, недоступну на вашому рівні доступу, — відхилено.\n{head}: {what}' },
534
535
  'perm.ask': { en: '🔐 <b>The agent asks for permission</b>', ru: '🔐 <b>Агент просит разрешение</b>', uk: '🔐 <b>Агент просить дозвіл</b>' },
536
+ 'perm.trimmed': { en: '… shown {shown} of {total} characters …', ru: '… показано {shown} из {total} символов …', uk: '… показано {shown} із {total} символів …' },
535
537
  'perm.timeout': { en: '⌛ Time is up, rejected\n{head}: {what}', ru: '⌛ Время вышло, отклонено\n{head}: {what}', uk: '⌛ Час минув, відхилено\n{head}: {what}' },
536
538
  'perm.stale': { en: 'This request is no longer active', ru: 'Запрос уже неактуален', uk: 'Запит уже неактуальний' },
537
539
  'perm.badOption': { en: 'No such option', ru: 'Нет такого варианта', uk: 'Такого варіанта немає' },
@@ -547,6 +549,13 @@ const M = {
547
549
  'turn.error': { en: '⚠️ Error: {msg}', ru: '⚠️ Ошибка: {msg}', uk: '⚠️ Помилка: {msg}' },
548
550
  'turn.files': { en: '📎 Files:', ru: '📎 Файлы:', uk: '📎 Файли:' },
549
551
  'file.tooBig': { en: '⚠️ The file is too large: the limit is 20 MB.', ru: '⚠️ Файл слишком большой: лимит 20 МБ.', uk: '⚠️ Файл завеликий: ліміт 20 МБ.' },
552
+ 'file.receiving': { en: '⏳ The previous file is still being received. Wait for it to finish.', ru: '⏳ Предыдущий файл ещё принимается. Дождитесь окончания.', uk: '⏳ Попередній файл ще завантажується. Дочекайтеся завершення.' },
553
+ 'file.quota': { en: '⚠️ Not enough space to accept the file. Try again later or ask the administrator.', ru: '⚠️ Не хватает места для приёма файла. Попробуйте позже или обратитесь к администратору.', uk: '⚠️ Недостатньо місця для приймання файлу. Спробуйте пізніше або зверніться до адміністратора.' },
554
+ 'secret.detected': { en: '⚠️ This looks like an access token. It was not sent to the agent. Press the button again and enter the token.', ru: '⚠️ Это похоже на токен доступа. Он не передан агенту. Нажмите кнопку ещё раз и введите токен.', uk: '⚠️ Це схоже на токен доступу. Його не передано агенту. Натисніть кнопку ще раз і введіть токен.' },
555
+ 'warn.title': { en: '⚠️ Security notices (shown once)', ru: '⚠️ Замечания по безопасности (показываются один раз)', uk: '⚠️ Зауваження з безпеки (показуються один раз)' },
556
+ 'warn.noSandbox': { en: 'Teammates work without a sandbox: their agents can read the bot .env and database, including Git tokens of all users. Run the bot in WSL/Linux with AGENT_SANDBOX=bwrap or under a separate OS account.', ru: 'Сотрудники работают без песочницы: их агенты могут читать .env и базу бота, включая токены Git всех пользователей. Запустите бота в WSL/Linux с AGENT_SANDBOX=bwrap или под отдельной учётной записью ОС.', uk: 'Співробітники працюють без пісочниці: їх агенти можуть читати .env і базу бота, включно з токенами Git усіх користувачів. Запустіть бота у WSL/Linux з AGENT_SANDBOX=bwrap або під окремим обліковим записом ОС.' },
557
+ 'warn.adminNoSandbox': { en: 'The administrator works without a sandbox in a folder writable by teammates: a planted engine config can run with bot rights. Set ADMIN_SANDBOX=1 to sandbox the administrator there.', ru: 'Администратор работает без песочницы в папке, куда пишут сотрудники: подложенный файл настроек движка может выполниться с правами бота. Включите ADMIN_SANDBOX=1, чтобы песочнить администратора в таких папках.', uk: 'Адміністратор працює без пісочниці у теці, куди пишуть співробітники: підкладений файл налаштувань движка може виконатися з правами бота. Увімкніть ADMIN_SANDBOX=1, щоб пісочнити адміністратора в таких теках.' },
558
+ 'warn.broadAcl': { en: 'The bot .env is readable by local user groups (Users, Authenticated Users or Everyone). Restrict it with icacls and give access only to the service account, SYSTEM and Administrators.', ru: 'Файл .env бота доступен локальным группам пользователей (Users, Authenticated Users или Everyone). Ограничьте права через icacls и оставьте только учётную запись службы, SYSTEM и Administrators.', uk: 'Файл .env бота доступний локальним групам користувачів (Users, Authenticated Users або Everyone). Обмежте права через icacls і залиште лише обліковий запис служби, SYSTEM та Administrators.' },
550
559
  'file.downloadFail': { en: '⚠️ Could not download the file: {msg}', ru: '⚠️ Не удалось скачать файл: {msg}', uk: '⚠️ Не вдалося завантажити файл: {msg}' },
551
560
  'file.archiveSkipped': { en: '⚠️ The archive «{name}» was not unpacked: {why}. The agent gets it as a file.', ru: '⚠️ Архив «{name}» не распакован: {why}. Агент получит его как файл.', uk: '⚠️ Архів «{name}» не розпаковано: {why}. Агент отримає його як файл.' },
552
561
  'file.archiveWhy.limit': { en: 'more than 500 files or 100 MB after unpacking', ru: 'больше 500 файлов или 100 МБ после распаковки', uk: 'понад 500 файлів або 100 МБ після розпакування' },
@@ -562,6 +571,7 @@ const M = {
562
571
  'file.why.error': { en: 'Telegram rejected the file ({msg})', ru: 'Telegram не принял файл ({msg})', uk: 'Telegram не прийняв файл ({msg})' },
563
572
  'limit.slots': { en: '⏳ All {max} employee agent slots are busy right now. Try again in a minute.', ru: '⏳ Сейчас заняты все {max} слота агентов сотрудников. Попробуйте через минуту.', uk: '⏳ Зараз зайняті всі {max} слоти агентів співробітників. Спробуйте за хвилину.' },
564
573
  'state.modeViolation': { en: '⛔ The agent tried to switch to the «{mode}» mode, which is not available at your access level. The request was stopped and the session closed.', ru: '⛔ Агент попытался перейти в режим «{mode}», недоступный на вашем уровне доступа. Запрос остановлен, сессия закрыта.', uk: '⛔ Агент спробував перейти в режим «{mode}», недоступний на вашому рівні доступу. Запит зупинено, сесію закрито.' },
574
+ 'state.modelViolation': { en: '⛔ The agent used model «{model}», which is not allowed by the administrator. The request was stopped and the session closed.', ru: '⛔ Агент использовал модель «{model}», которая не разрешена администратором. Запрос остановлен, сессия закрыта.', uk: '⛔ Агент використав модель «{model}», яку не дозволив адміністратор. Запит зупинено, сесію закрито.' },
565
575
  'state.startTimeout': {
566
576
  en: '{engine} did not start within {sec} s (perhaps it is waiting for a sign-in or is overloaded); the process was stopped. Try again, and if it repeats, check the agent on the server.',
567
577
  ru: '{engine} не запустился за {sec} с (возможно, ждёт входа в аккаунт или перегружен); процесс остановлен. Повторите запрос, а если не поможет — проверьте агента на сервере.',
package/src/log.mjs CHANGED
@@ -1,8 +1,33 @@
1
1
  // Вывод в журнал бота (stdout и stderr службы → data/service.log): каждая строка с отметкой времени.
2
2
  // Отдельный модуль без зависимостей: им пользуются и нижние слои (acp, telegram, db), которым нельзя импортировать ctx.mjs.
3
+ import { readdirSync, statSync, unlinkSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { inspect } from 'node:util';
6
+ import { clipLogLine } from './clip.mjs';
7
+
3
8
  const stamp = () => new Date().toISOString();
9
+ const format = (args) => clipLogLine(args.map((a) => (typeof a === 'string' ? a : inspect(a, { depth: 3, breakLength: Infinity }))).join(' '));
4
10
 
5
- export const log = (...a) => console.log(stamp(), ...a);
11
+ export const log = (...a) => console.log(stamp(), format(a));
6
12
 
7
13
  /** То же в stderr: ошибки и предупреждения. */
8
- export const logError = (...a) => console.error(stamp(), ...a);
14
+ export const logError = (...a) => console.error(stamp(), format(a));
15
+
16
+ export function cleanupLogs(dir, days) {
17
+ if (!(Number(days) > 0)) return 0;
18
+ const before = Date.now() - Number(days) * 86400_000;
19
+ let removed = 0;
20
+ for (const name of readdirSync(dir)) {
21
+ if (!/^debug\.log\.\d+$/.test(name)) continue;
22
+ const path = join(dir, name);
23
+ try {
24
+ if (statSync(path).mtimeMs < before) {
25
+ unlinkSync(path);
26
+ removed++;
27
+ }
28
+ } catch {
29
+ continue;
30
+ }
31
+ }
32
+ return removed;
33
+ }
@@ -0,0 +1,62 @@
1
+ const PREFIX = 'pending:';
2
+ const DEFAULT_TTL_MS = 24 * 3600_000;
3
+ const SECRET_PATTERNS = [
4
+ /^gh[pousr]_[A-Za-z0-9]{16,}$/i,
5
+ /^github_pat_[A-Za-z0-9_]{16,}$/i,
6
+ /^glpat-[A-Za-z0-9_-]{16,}$/i,
7
+ /^npm_[A-Za-z0-9]{20,}$/i,
8
+ /^sk-[A-Za-z0-9_-]{20,}$/i,
9
+ /^AKIA[A-Z0-9]{16}$/,
10
+ ];
11
+
12
+ const parse = (value) => {
13
+ if (!value) return null;
14
+ try {
15
+ const data = JSON.parse(value);
16
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : null;
17
+ } catch {
18
+ return null;
19
+ }
20
+ };
21
+
22
+ export function looksLikeSecret(text) {
23
+ const s = String(text ?? '').trim();
24
+ return SECRET_PATTERNS.some((re) => re.test(s));
25
+ }
26
+
27
+ export function createPendingStore(db, { now = Date.now, ttlMs = DEFAULT_TTL_MS } = {}) {
28
+ const keyOf = (userId, topic = 0) => `${PREFIX}${userId}:${topic}`;
29
+ return {
30
+ set(userId, topic, value) {
31
+ const data = { ...value, at: Number.isFinite(value?.at) ? value.at : now() };
32
+ db.setSetting(keyOf(userId, topic), JSON.stringify(data));
33
+ return data;
34
+ },
35
+ get(userId, topic = 0) {
36
+ const key = keyOf(userId, topic);
37
+ const data = parse(db.getSetting(key));
38
+ if (!data) return null;
39
+ if (!Number.isFinite(data.at) || now() - data.at > ttlMs) {
40
+ db.setSetting(key, null);
41
+ return null;
42
+ }
43
+ return data;
44
+ },
45
+ clear(userId, topic = 0) {
46
+ db.setSetting(keyOf(userId, topic), null);
47
+ },
48
+ sweep() {
49
+ const keys = db.allSettings ? db.allSettings() : [];
50
+ let removed = 0;
51
+ for (const { key, value } of keys) {
52
+ if (!key?.startsWith(PREFIX) || !value) continue;
53
+ const data = parse(value);
54
+ if (!data || !Number.isFinite(data.at) || now() - data.at > ttlMs) {
55
+ db.setSetting(key, null);
56
+ removed++;
57
+ }
58
+ }
59
+ return removed;
60
+ },
61
+ };
62
+ }
@@ -15,6 +15,8 @@ export const DEPTH_MAX = 8;
15
15
 
16
16
  // В эти папки бот не пишет и их не показывает: служебные данные git и тяжёлые каталоги зависимостей
17
17
  const SKIP_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', 'renv', 'packrat', 'site-packages']);
18
+ const CONFIG_DIRS = new Set(['.claude', '.gemini', '.codex', '.opencode']);
19
+ const CONFIG_FILES = new Set(['opencode.json']);
18
20
 
19
21
  /** Ошибка операции с файлом проекта: code — причина для сообщения пользователю (ключ files.err.<code>). */
20
22
  export class FileError extends Error {
@@ -29,7 +31,7 @@ export class FileError extends Error {
29
31
  * Возвращает части пути или null, если путь не подходит: абсолютный, с «..», с запрещёнными символами, в служебной папке.
30
32
  * Имена с точки (.env, .Renviron) разрешены — ради них это и сделано.
31
33
  */
32
- export function relPath(input) {
34
+ export function relPath(input, { hideConfig = false } = {}) {
33
35
  const raw = String(input ?? '').trim().replace(/\\/g, '/');
34
36
  if (!raw || raw.startsWith('/') || /^[A-Za-z]:/.test(raw) || raw.startsWith('~')) return null;
35
37
  const parts = raw.split('/').map((s) => s.trim());
@@ -39,7 +41,9 @@ export function relPath(input) {
39
41
  // eslint-disable-next-line no-control-regex -- управляющие символы в имени файла недопустимы
40
42
  if (/[\u0000-\u001f<>:"|?*]/.test(p) || /[. ]$/.test(p)) return null;
41
43
  if (/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(p)) return null;
42
- if (SKIP_DIRS.has(p.toLowerCase())) return null;
44
+ const lower = p.toLowerCase();
45
+ if (SKIP_DIRS.has(lower)) return null;
46
+ if (hideConfig && (CONFIG_DIRS.has(lower) || CONFIG_FILES.has(lower))) return null;
43
47
  }
44
48
  return parts;
45
49
  }
@@ -146,15 +150,17 @@ export function deleteProjectFile(project, path) {
146
150
  * Содержимое папки проекта: папки и файлы по алфавиту, со скрытыми файлами (.env), без ссылок и служебных папок.
147
151
  * @returns {{dirs: string[], files: {name: string, size: number, mtime: number}[]}}
148
152
  */
149
- export function listProjectDir(project, dir) {
153
+ export function listProjectDir(project, dir, { hideConfig = false } = {}) {
150
154
  const { real } = inProject(project, dir);
151
155
  const dirs = [];
152
156
  const files = [];
153
157
  for (const d of readdirSync(real, { withFileTypes: true })) {
154
158
  if (d.isSymbolicLink() || d.name.endsWith('.tmp') && d.name.startsWith('.acpgram-')) continue;
159
+ const lower = d.name.toLowerCase();
155
160
  if (d.isDirectory()) {
156
- if (!SKIP_DIRS.has(d.name.toLowerCase())) dirs.push(d.name);
161
+ if (!SKIP_DIRS.has(lower) && !(hideConfig && CONFIG_DIRS.has(lower))) dirs.push(d.name);
157
162
  } else if (d.isFile()) {
163
+ if (hideConfig && CONFIG_FILES.has(lower)) continue;
158
164
  const st = lstat(join(real, d.name));
159
165
  if (st) files.push({ name: d.name, size: st.size, mtime: st.mtimeMs });
160
166
  }
@@ -0,0 +1,18 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { broadAclFromOutput } from './safety.mjs';
3
+
4
+ export function protectWindowsPath(path, { directory = false, platform = process.platform, env = process.env, run = spawnSync } = {}) {
5
+ if (platform !== 'win32') return null;
6
+ const name = env.USERNAME ? (env.USERDOMAIN ? `${env.USERDOMAIN}\\${env.USERNAME}` : `.\\${env.USERNAME}`) : null;
7
+ const flags = directory ? '(OI)(CI)F' : 'F';
8
+ const grants = [name && `${name}:${flags}`, `SYSTEM:${flags}`, `Administrators:${flags}`].filter(Boolean);
9
+ const r = run('icacls', [path, '/inheritance:r', '/grant:r', ...grants], { encoding: 'utf8', windowsHide: true });
10
+ return { status: r?.status ?? null, error: r?.error ?? null, output: `${r?.stdout ?? ''}\n${r?.stderr ?? ''}` };
11
+ }
12
+
13
+ export function envAclRisk(path, { platform = process.platform, run = spawnSync } = {}) {
14
+ if (platform !== 'win32') return false;
15
+ const r = run('icacls', [path], { encoding: 'utf8', windowsHide: true });
16
+ if (r?.error || r?.status !== 0) return false;
17
+ return broadAclFromOutput(`${r?.stdout ?? ''}\n${r?.stderr ?? ''}`);
18
+ }