acpgram 1.28.0 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -230,11 +230,16 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
230
230
 
231
231
  - **Own servers** are added by the administrator right in `/git`: "⚙️ Own servers" → "➕ GitLab" or "➕ GitHub Enterprise" → the server address (`https://git.example.com`). The bot checks that a server of that kind answers at the address, and after that every user can connect an account on it. The same screen renames and removes a server — together with the accounts connected to it. Without this the menu has only GitHub and GitLab.com. Where settings are kept in a file, a server can also be set in `.env` (`GITLAB_URL`, `GITHUB_URL`).
232
232
 
233
- - **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Disconnecting removes the token from the bot.
233
+ - **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Full permissions are needed: on GitLab `api`, `read_repository`, `write_repository` (without `api` publishing and merge requests do not work), on GitHub `repo`. Disconnecting removes the token from the bot.
234
234
  - **Cloning.** "⬇️ Clone a repository" (or "⬇️ From Git" in `/project`) lists the user's repositories as buttons, recently changed first, with search by name. The chosen one is cloned into the personal workspace (without it, next to the current project) and becomes the project.
235
235
  - **The project repository.** The screen shows the branch, the number of changed files, of commits not pushed and of new commits on the server; it checks the server when opened and on "Refresh". "⬇️ Pull" takes the changes when that is possible without a merge; if the histories diverged, the agent does the merge. "⬆️ Push" sends the commits. "💾 Save and push" asks for a description, commits all changes and pushes.
236
236
  - **"📋 Changes".** The list of changed files with marks (new, modified, deleted, renamed) and the number of added and removed lines. Pressing a file shows what changed in it: short changes in the message, long ones as a file. The contents of files with secrets are not shown. The same screen lists the commits that are not pushed yet and those waiting on the server. All of this is visible without the agent and without model requests.
237
237
  - **"🌿 Branches".** Local and server branches in one list; pressing a branch switches to it, "➕ New branch" creates one from the current branch. With unsaved changes the bot does not switch and offers to save them first; the same while the agent is working. After switching, the next request starts a new agent session, because the project files have changed. "Push" creates a new branch on the server too.
238
+ - **Discarding changes.** The card of a changed file has "↩️ Restore as it was", and the "Changes" screen has "↩️ Discard all changes": modified and deleted files return to the last commit, new files are deleted. It cannot be undone, so it always asks for confirmation; files with secrets are not touched.
239
+ - **"🚀 Publish the project".** For a folder that is not connected to a server yet: the user chooses the service, the place (personal space, a GitLab group with subgroups or a GitHub organization — with search), the visibility (private, internal, public) and the name. The bot creates the repository, makes the first commit without files with secrets and pushes it.
240
+ - **"🔀 Merge request".** From the current branch into the main branch of the repository: the bot asks for a title (or suggests the last commit message), creates the request and gives the link; if an open request from this branch already exists, it shows that one.
241
+ - **The agent asks to push.** The agent has no sign-in for the server, so on "push it" it commits and puts the mark `[[git:push]]` (or `[[git:pull]]`) into its reply. The bot removes the mark and shows a button under the reply; nothing is sent without the user pressing it.
242
+ - **Token reminder.** A week before, a day before and when the token expires, the bot writes to the account owner.
238
243
  - **The commit author** is the account owner: the name and email are given to both the bot and the agent, so the agent's commits are signed by the user.
239
244
  - **Secrets do not go to the repository.** On "Save and push", files with secrets (`.env`, keys, credentials) are left out of the commit and appended to `.gitignore`. If the agent committed such a file, the bot warns before pushing and pushes only after "Push anyway".
240
245
 
package/README.ru.md CHANGED
@@ -120,11 +120,16 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
120
120
 
121
121
  - **Свои серверы** добавляет администратор прямо в `/git`: «⚙️ Свои серверы» → «➕ GitLab» или «➕ GitHub Enterprise» → адрес сервера (`https://git.example.com`). Бот проверяет, что по адресу отвечает сервер нужного вида, и после этого каждый пользователь может подключить на нём аккаунт. Там же сервер переименовывается и убирается — вместе с подключёнными к нему аккаунтами. Без этого в меню только GitHub и GitLab.com. Там, где настройки задаются файлом, сервер можно указать и в `.env` (`GITLAB_URL`, `GITHUB_URL`).
122
122
 
123
- - **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Отключение удаляет токен из бота.
123
+ - **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Права нужны полные: у GitLab — `api`, `read_repository`, `write_repository` (без `api` не работают публикация и запросы на слияние), у GitHub — `repo`. Отключение удаляет токен из бота.
124
124
  - **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
125
125
  - **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
126
126
  - **«📋 Изменения».** Список изменённых файлов с пометками (новый, изменён, удалён, переименован) и числом добавленных и убранных строк. Нажатие на файл показывает, что в нём изменилось: короткие изменения — в сообщении, длинные — файлом. Содержимое файлов с секретами не показывается. Там же — коммиты, которые ещё не отправлены, и те, что ждут на сервере. Всё это видно без агента и без запросов к модели.
127
127
  - **«🌿 Ветки».** Локальные ветки и ветки сервера одним списком; нажатие переключает на ветку, «➕ Новая ветка» создаёт её от текущей. При несохранённых изменениях бот не переключает, а предлагает сначала сохранить их; пока агент выполняет запрос — тоже. После переключения следующий запрос начинает новую сессию агента: файлы проекта сменились. «Отправить» создаёт новую ветку и на сервере.
128
+ - **Отмена изменений.** В карточке изменённого файла — «↩️ Вернуть как было», на экране «Изменения» — «↩️ Отменить все изменения»: изменённые и удалённые файлы возвращаются к последнему коммиту, новые удаляются. Действие необратимо, поэтому всегда с подтверждением; файлы с секретами не затрагиваются.
129
+ - **«🚀 Опубликовать проект».** Для папки, которая ещё не связана с сервером: пользователь выбирает сервис, место (личное пространство, группа GitLab с подгруппами или организация GitHub — с поиском), видимость (закрытый, внутренний, открытый) и название. Бот создаёт репозиторий, делает первый коммит без файлов с секретами и отправляет его.
130
+ - **«🔀 Запрос на слияние».** Из текущей ветки в основную ветку репозитория: бот спрашивает заголовок (или предлагает описание последнего коммита), создаёт запрос и даёт ссылку; если открытый запрос из этой ветки уже есть — показывает его.
131
+ - **Агент просит отправить.** У агента нет входа на сервер, поэтому «отправь на сервер» он выполняет так: коммитит и ставит в ответе метку `[[git:push]]` (или `[[git:pull]]`). Бот убирает метку и показывает под ответом кнопку; без нажатия пользователя ничего не уходит.
132
+ - **Напоминание о токене.** За неделю, за день и по истечении срока токена бот пишет владельцу аккаунта.
128
133
  - **Автор коммитов** — владелец аккаунта: его имя и почта передаются и боту, и агенту, так что коммиты агента подписаны пользователем.
129
134
  - **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
130
135
 
@@ -425,7 +430,11 @@ src/
425
430
  gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
426
431
  gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
427
432
  gitInspect.mjs что изменилось и какие есть ветки: список файлов, изменения по файлу, коммиты, переключение ветки
428
- gitRepoUi.mjs экраны /git «Изменения» и «Ветки»
433
+ gitRepoUi.mjs экраны /git «Изменения» и «Ветки», отмена изменений
434
+ gitApi.mjs GitHub и GitLab: создание репозитория, места для публикации, запрос на слияние
435
+ gitPublishUi.mjs экраны /git «Опубликовать проект» и «Запрос на слияние»
436
+ gitMarks.mjs метки агента [[git:push]] / [[git:pull]]: отправка и получение по просьбе агента
437
+ gitKeys.mjs ключи кнопок списков /git: старая кнопка не укажет на другой файл или ветку
429
438
  sessionsUi.mjs команда /sessions: возврат к прошлой сессии
430
439
  tools.mjs разбор событий вызовов инструментов агента
431
440
  asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.28.0",
3
+ "version": "1.29.0",
4
4
  "type": "module",
5
5
  "description": "Telegram gateway to AI coding agents (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) over the Agent Client Protocol",
6
6
  "license": "MIT",
package/src/bot.mjs CHANGED
@@ -8,12 +8,12 @@ import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './a
8
8
  import { handleModel, onModelCallback } from './modelUi.mjs';
9
9
  import { ADMIN_ID, IDLE_MINUTES, LEVEL_KEYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
10
10
  import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from './admin.mjs';
11
- import { LANGS, LANG_CODES, LANG_PICK, errText, normLang, t } from './i18n.mjs';
11
+ import { LANGS, LANG_CODES, LANG_PICK, LOCALES, errText, normLang, t } from './i18n.mjs';
12
12
  import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
13
13
  import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
14
14
  import { handleFiles, onFileInput, onFileUpload, onFilesCallback } from './filesUi.mjs';
15
15
  import { checkGit, gitCommand } from './git.mjs';
16
- import { GIT_AGENT_AUTH } from './gitAccess.mjs';
16
+ import { GIT_AGENT_AUTH, tokenReminders } from './gitAccess.mjs';
17
17
  import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
18
18
  import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
19
19
  import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
@@ -482,6 +482,23 @@ async function main() {
482
482
  };
483
483
  sweep();
484
484
  setInterval(sweep, 24 * 3600_000).unref();
485
+ // токены доступа к Git истекают: владельцу аккаунта — напоминание за неделю, за день и по истечении
486
+ const remind = () => {
487
+ try {
488
+ for (const r of tokenReminders()) {
489
+ const lang = langOf(r.userId);
490
+ const date = new Date(r.account.expires_at).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' });
491
+ log('git: напоминание о токене:', r.userId, r.host.id, r.stage);
492
+ say(r.userId, t(r.stage === 'expired' ? 'git.exp.expired' : 'git.exp.soon', lang, { host: r.host.label, login: r.account.login, date, days: r.days }), {
493
+ reply_markup: { inline_keyboard: [[{ text: t('start.btn.git', lang), callback_data: 'ui:git' }]] },
494
+ });
495
+ }
496
+ } catch (e) {
497
+ log('напоминания о токенах git:', e.message);
498
+ }
499
+ };
500
+ remind();
501
+ setInterval(remind, 12 * 3600_000).unref();
485
502
  const admin = getState(ADMIN_ID, ADMIN_ID);
486
503
  log(`бот @${botInfo.username} запущен | администратор ${ADMIN_ID} | проект админа: ${admin.project} | сотрудников: ${db.listUsers().filter((x) => x.status === 'active').length} | лимит агентов сотрудников: ${MAX_AGENTS} | простой: ${IDLE_MINUTES} мин | уровни: ${LEVEL_KEYS.join('/')}`);
487
504
 
package/src/db.mjs CHANGED
@@ -245,6 +245,7 @@ export function openDb(path = 'data/bot.db') {
245
245
  deleteTopic: db.prepare('DELETE FROM topics WHERE user_id = ? AND thread_id = ?'),
246
246
  getGitAccount: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? AND host = ?'),
247
247
  listGitAccounts: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? ORDER BY added_at'),
248
+ allGitAccounts: db.prepare('SELECT * FROM git_accounts'),
248
249
  saveGitAccount: db.prepare(
249
250
  `INSERT INTO git_accounts (user_id, host, login, name, email, token, expires_at, added_at) VALUES (?,?,?,?,?,?,?,?)
250
251
  ON CONFLICT(user_id, host) DO UPDATE SET login = excluded.login, name = excluded.name, email = excluded.email,
@@ -326,6 +327,8 @@ export function openDb(path = 'data/bot.db') {
326
327
  // --- аккаунты Git ---
327
328
  getGitAccount: safe((userId, host) => q.getGitAccount.get(userId, host) ?? null),
328
329
  listGitAccounts: (userId) => safe(() => q.listGitAccounts.all(userId))() ?? [],
330
+ /** Аккаунты всех пользователей (для напоминаний об истекающих токенах). */
331
+ allGitAccounts: () => safe(() => q.allGitAccounts.all())() ?? [],
329
332
  /** Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt}. Возвращает true, если записано. */
330
333
  saveGitAccount: (userId, a) =>
331
334
  safe(() => q.saveGitAccount.run(userId, a.host, a.login ?? null, a.name ?? null, a.email ?? null, a.token, a.expiresAt ?? null, now()).changes === 1)() ?? false,
package/src/gitAccess.mjs CHANGED
@@ -91,6 +91,30 @@ export function agentGitEnv(userId, { agentAuth = GIT_AGENT_AUTH, base = process
91
91
  return agentAuth ? { ...env, GIT_TERMINAL_PROMPT: '0' } : env;
92
92
  }
93
93
 
94
+ const DAY_MS = 24 * 3600_000;
95
+
96
+ /**
97
+ * Кому пора напомнить об истекающем токене: за 7 дней, за день и когда срок вышел. Каждое напоминание — один раз
98
+ * (отметка в настройках: срок токена и ступень); новый токен с другим сроком начинает отсчёт заново.
99
+ * @returns {{userId: number, host: object, account: object, stage: '7'|'1'|'expired', days: number}[]}
100
+ */
101
+ export function tokenReminders(now = Date.now()) {
102
+ const out = [];
103
+ for (const account of db.allGitAccounts()) {
104
+ const host = account.expires_at ? findHost(account.host) : null;
105
+ if (!host) continue;
106
+ const days = Math.ceil((Date.parse(account.expires_at) - now) / DAY_MS);
107
+ const stage = days <= 0 ? 'expired' : days <= 1 ? '1' : days <= 7 ? '7' : null;
108
+ if (!stage) continue;
109
+ const key = `gitexp:${account.user_id}:${account.host}`;
110
+ const mark = `${account.expires_at}|${stage}`;
111
+ if (db.getSetting(key) === mark) continue;
112
+ db.setSetting(key, mark);
113
+ out.push({ userId: account.user_id, host, account, stage, days });
114
+ }
115
+ return out;
116
+ }
117
+
94
118
  /**
95
119
  * Подсказка агенту о git (служебный текст — на английском). Без входа: не пытаться получать и отправлять, а направлять
96
120
  * пользователя в /git. Со входом (GIT_AGENT_AUTH): работать можно, показывать вход нельзя. Нет git на сервере — null.
@@ -107,6 +131,7 @@ export function gitNote(userId, { agentAuth = GIT_AGENT_AUTH } = {}) {
107
131
  return (
108
132
  '[AcpGram] Git: use git locally as usual (status, diff, add, commit, branches, merge). You have no credentials for the remote: ' +
109
133
  'do not try to fetch, pull, push or clone private repositories and do not ask the user for tokens or passwords. ' +
110
- 'When changes must be received or sent, tell the user to use the /git command of this bot (buttons to pull and push). Never commit files with secrets (.env, keys).'
134
+ 'When changes must be sent to or received from the server, put [[git:push]] or [[git:pull]] on its own line at the end of your reply: ' +
135
+ 'the bot then shows the user a button that does it (commit first — the button only pushes). The user can also open /git. Never commit files with secrets (.env, keys).'
111
136
  );
112
137
  }
package/src/gitApi.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // GitHub и GitLab: создание репозитория (публикация проекта) и запрос на слияние — действия, которым нужен API
2
+ // сервиса, а не git. Запросы идут от имени владельца токена (gitHosts.api); у GitLab для них нужно право api.
3
+ import { api, showRemote } from './gitHosts.mjs';
4
+
5
+ /**
6
+ * Где пользователь может создать репозиторий: личное пространство и группы (GitLab, вместе с подгруппами) или
7
+ * организации (GitHub). search — часть названия группы.
8
+ * @returns {Promise<{id: string|number|null, path: string, kind: 'user'|'group'}[]>} id — для createRepo (у личного — null)
9
+ */
10
+ export async function listNamespaces(host, token, login, { search = '', ...opts } = {}) {
11
+ const q = search.trim().toLowerCase();
12
+ const own = { id: null, path: login, kind: 'user' };
13
+ if (host.kind === 'gitlab') {
14
+ // 30 — уровень Developer: с него группа может разрешать создание проектов
15
+ const { data } = await api(host, token, `/groups?min_access_level=30&order_by=path&per_page=50${q ? `&search=${encodeURIComponent(q)}` : ''}`, opts);
16
+ return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...data.map((g) => ({ id: g.id, path: g.full_path, kind: 'group' }))];
17
+ }
18
+ const { data } = await api(host, token, '/user/orgs?per_page=100', opts);
19
+ const orgs = data.map((o) => ({ id: o.login, path: o.login, kind: 'group' })).filter((o) => !q || o.path.toLowerCase().includes(q));
20
+ return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...orgs];
21
+ }
22
+
23
+ /** Видимость нового репозитория, которую умеет сервис: «внутренний» (виден всем пользователям сервера) — только GitLab. */
24
+ export const visibilities = (host) => (host.kind === 'gitlab' ? ['private', 'internal', 'public'] : ['private', 'public']);
25
+
26
+ /**
27
+ * Имя репозитория в адресе из названия папки: латиница, цифры, «.», «-», «_»; остальное — в «-». Не получилось
28
+ * (например, название целиком кириллицей) — null: имя нужно спросить у пользователя.
29
+ */
30
+ export function repoSlug(name) {
31
+ const slug = String(name ?? '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').replace(/\.git$/, '').slice(0, 100);
32
+ return slug && /[a-z0-9]/.test(slug) ? slug : null;
33
+ }
34
+
35
+ /**
36
+ * Создаёт пустой репозиторий. namespace — запись из listNamespaces; visibility — private | internal | public.
37
+ * @returns {Promise<{url: string, web: string, path: string}>} url — адрес для git (https), web — страница репозитория
38
+ */
39
+ export async function createRepo(host, token, { name, slug, namespace = null, visibility = 'private' }, opts = {}) {
40
+ if (host.kind === 'gitlab') {
41
+ const body = { name, path: slug, visibility, initialize_with_readme: false, ...(namespace?.id ? { namespace_id: namespace.id } : {}) };
42
+ const { data } = await api(host, token, '/projects', { ...opts, body });
43
+ return { url: data.http_url_to_repo, web: data.web_url, path: data.path_with_namespace };
44
+ }
45
+ const body = { name: slug, private: visibility !== 'public', auto_init: false };
46
+ const { data } = await api(host, token, namespace?.id ? `/orgs/${encodeURIComponent(namespace.id)}/repos` : '/user/repos', { ...opts, body });
47
+ return { url: data.clone_url, web: data.html_url, path: data.full_name };
48
+ }
49
+
50
+ /** Путь репозитория на сервисе по адресу origin: «group/sub/app» (у GitHub — «owner/repo»). */
51
+ export const repoPath = (host, remote) => showRemote(remote).slice(showRemote(host.web).length).replace(/^\/+|\/+$/g, '');
52
+
53
+ const projectRef = (host, remote) => (host.kind === 'gitlab' ? `/projects/${encodeURIComponent(repoPath(host, remote))}` : `/repos/${repoPath(host, remote).split('/').map(encodeURIComponent).join('/')}`);
54
+
55
+ /** Основная ветка репозитория на сервере и адрес его страницы. */
56
+ export async function repoInfo(host, token, remote, opts = {}) {
57
+ const { data } = await api(host, token, projectRef(host, remote), opts);
58
+ return { defaultBranch: data.default_branch ?? null, web: data.web_url ?? data.html_url ?? null };
59
+ }
60
+
61
+ /**
62
+ * Запрос на слияние ветки branch в ветку target (у GitHub — pull request). Если открытый запрос из этой ветки уже есть,
63
+ * возвращает его, а не создаёт второй.
64
+ * @returns {Promise<{url: string, number: number, existed: boolean}>}
65
+ */
66
+ export async function openMergeRequest(host, token, remote, { branch, target, title }, opts = {}) {
67
+ const ref = projectRef(host, remote);
68
+ if (host.kind === 'gitlab') {
69
+ const found = await api(host, token, `${ref}/merge_requests?state=opened&source_branch=${encodeURIComponent(branch)}&target_branch=${encodeURIComponent(target)}`, opts);
70
+ if (found.data[0]) return { url: found.data[0].web_url, number: found.data[0].iid, existed: true };
71
+ const { data } = await api(host, token, `${ref}/merge_requests`, { ...opts, body: { source_branch: branch, target_branch: target, title } });
72
+ return { url: data.web_url, number: data.iid, existed: false };
73
+ }
74
+ const owner = repoPath(host, remote).split('/')[0];
75
+ const found = await api(host, token, `${ref}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&base=${encodeURIComponent(target)}`, opts);
76
+ if (found.data[0]) return { url: found.data[0].html_url, number: found.data[0].number, existed: true };
77
+ const { data } = await api(host, token, `${ref}/pulls`, { ...opts, body: { title, head: branch, base: target } });
78
+ return { url: data.html_url, number: data.number, existed: false };
79
+ }
package/src/gitHosts.mjs CHANGED
@@ -26,7 +26,7 @@ export function normalizeHostUrl(input) {
26
26
  const hostId = (kind, web) => `${kind}-${web.replace(/^https:\/\//, '')}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '').slice(0, 40);
27
27
 
28
28
  const githubHost = (id, label, web, api) => ({ id, kind: 'github', label, web, api, tokenUrl: `${web}/settings/tokens`, user: 'x-access-token', scopes: 'repo' });
29
- const gitlabHost = (id, label, web) => ({ id, kind: 'gitlab', label, web, api: `${web}/api/v4`, tokenUrl: `${web}/-/user_settings/personal_access_tokens`, user: 'oauth2', scopes: 'read_api, read_repository, write_repository' });
29
+ const gitlabHost = (id, label, web) => ({ id, kind: 'gitlab', label, web, api: `${web}/api/v4`, tokenUrl: `${web}/-/user_settings/personal_access_tokens`, user: 'oauth2', scopes: 'api, read_repository, write_repository' });
30
30
 
31
31
  /**
32
32
  * Свой сервер: GitLab или GitHub Enterprise по адресу. name — название для кнопок (по умолчанию — имя сервера).
@@ -104,19 +104,38 @@ export class HostError extends Error {
104
104
  }
105
105
  }
106
106
 
107
- async function api(host, token, path, { fetchImpl = fetch } = {}) {
107
+ /** Что сервис написал в ответе с ошибкой: у GitLab — message (строка, список или {поле: [причины]}), у GitHub — message и errors. */
108
+ function errorDetail(data) {
109
+ const m = data?.message ?? data?.error_description ?? data?.error;
110
+ const flat = (v) => (v == null ? [] : typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(flat) : Object.entries(v).flatMap(([k, x]) => flat(x).map((s) => `${k} ${s}`)));
111
+ const extra = Array.isArray(data?.errors) ? data.errors.map((e) => (typeof e === 'string' ? e : e?.message || [e?.field, e?.code].filter(Boolean).join(' '))).filter(Boolean) : [];
112
+ return [...flat(m), ...extra].join('; ').slice(0, 300);
113
+ }
114
+
115
+ /**
116
+ * Запрос к API сервиса от имени владельца токена. body — объект: отправляется JSON методом POST (или method).
117
+ * Ошибки — HostError: 'auth' (401), 'forbidden' (403: токену не хватает прав), 'http' (с текстом сервиса), 'network'.
118
+ */
119
+ export async function api(host, token, path, { fetchImpl = fetch, method = null, body = null } = {}) {
108
120
  const headers = host.kind === 'github'
109
121
  ? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
110
122
  : { 'private-token': token, accept: 'application/json', 'user-agent': 'acpgram' };
123
+ const init = { headers, signal: AbortSignal.timeout(TIMEOUT_MS) };
124
+ if (body) Object.assign(init, { method: method ?? 'POST', body: JSON.stringify(body), headers: { ...headers, 'content-type': 'application/json' } });
125
+ else if (method) init.method = method;
111
126
  let res;
112
127
  try {
113
- res = await fetchImpl(`${host.api}${path}`, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
128
+ res = await fetchImpl(`${host.api}${path}`, init);
114
129
  } catch (e) {
115
130
  throw new HostError('network', `${host.label}: ${e.message}`);
116
131
  }
117
- if (res.status === 401 || res.status === 403) throw new HostError('auth', `${host.label}: HTTP ${res.status}`, res.status);
118
- if (!res.ok) throw new HostError('http', `${host.label}: HTTP ${res.status}`, res.status);
119
- return { data: await res.json(), headers: res.headers };
132
+ if (res.status === 401) throw new HostError('auth', `${host.label}: HTTP 401`, 401);
133
+ if (!res.ok) {
134
+ const detail = errorDetail(await res.json().catch(() => null));
135
+ // 403 при чтении профиля — тоже «токен не подошёл»; при остальном — не хватает прав
136
+ throw new HostError(res.status === 403 ? 'forbidden' : 'http', `${host.label}: ${detail || `HTTP ${res.status}`}`, res.status);
137
+ }
138
+ return { data: res.status === 204 ? null : await res.json(), headers: res.headers };
120
139
  }
121
140
 
122
141
  const isoDate = (v) => {
@@ -158,8 +177,8 @@ export function missingScopes(host, scopes) {
158
177
  if (!Array.isArray(scopes)) return [];
159
178
  const has = (s) => scopes.includes(s);
160
179
  if (host.kind === 'github') return has('repo') || !scopes.length ? [] : ['repo']; // у fine-grained токенов список пуст
161
- if (has('api')) return [];
162
- return ['read_api', 'read_repository', 'write_repository'].filter((s) => !has(s));
180
+ // api — создание репозиториев и запросов на слияние; с ним работают и клонирование, и отправка
181
+ return has('api') ? [] : ['api'];
163
182
  }
164
183
 
165
184
  export const REPOS_PAGE = 10;
@@ -2,8 +2,9 @@
2
2
  // Только чтение репозитория, кроме переключения и создания ветки. Команды запускает runGit (git.mjs) — с теми же
3
3
  // безопасными настройками и, при включённой песочнице, внутри неё.
4
4
  import { readFileSync, statSync } from 'node:fs';
5
- import { join } from 'node:path';
5
+ import { join, resolve } from 'node:path';
6
6
  import { GitError, runGit } from './git.mjs';
7
+ import { samePath } from './projects.mjs';
7
8
 
8
9
  /** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
9
10
  export const CHANGES_MAX = 300;
@@ -161,3 +162,46 @@ export async function switchBranch(cwd, branch, opts = {}) {
161
162
 
162
163
  /** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
163
164
  export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
165
+
166
+ /**
167
+ * Отменяет несохранённые изменения файлов (записи из changedFiles): изменённые и удалённые возвращаются к последнему
168
+ * коммиту, новые — удаляются. Действие необратимо; что отменять, решает вызывающий (секреты сюда не передаются).
169
+ * @returns {Promise<number>} сколько файлов обработано
170
+ */
171
+ export async function discardFiles(cwd, files, opts = {}) {
172
+ if (!files.length) return 0;
173
+ const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
174
+ const at = { cwd: top, ...opts };
175
+ const paths = [...new Set(files.flatMap((f) => [f.path, f.from]).filter(Boolean))];
176
+ // какие пути есть в последнем коммите: их возвращаем, остальные (новые файлы) убираем
177
+ const tracked = new Set((await runGit(['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...paths], at).catch(() => '')).split('\0').filter(Boolean));
178
+ const restore = paths.filter((p) => tracked.has(p));
179
+ const remove = paths.filter((p) => !tracked.has(p));
180
+ await runGit(['reset', '-q', '--', ...paths], at).catch(() => {}); // убрать из подготовленного к коммиту
181
+ if (restore.length) await runGit(['checkout', '-q', 'HEAD', '--', ...restore], at);
182
+ if (remove.length) await runGit(['clean', '-f', '-q', '--', ...remove], at);
183
+ return files.length;
184
+ }
185
+
186
+ /** Является ли сама папка cwd корнем репозитория (а не просто лежит внутри чужого, выше по дереву). */
187
+ export async function isRepoRoot(cwd, opts = {}) {
188
+ const top = await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts }).then((s) => s.trim(), () => null);
189
+ return Boolean(top) && samePath(resolve(top), resolve(cwd));
190
+ }
191
+
192
+ /** Делает папку репозиторием с веткой main, если она им ещё не была (чужой репозиторий выше по дереву не трогается). */
193
+ export async function ensureRepo(cwd, opts = {}) {
194
+ if (!(await isRepoRoot(cwd, opts))) await runGit(['init', '-q', '-b', 'main'], { cwd, ...opts });
195
+ }
196
+
197
+ /** Есть ли в репозитории хотя бы один коммит. */
198
+ export const hasCommits = (cwd, opts = {}) => runGit(['rev-parse', '--verify', '-q', 'HEAD'], { cwd, ...opts }).then(() => true, () => false);
199
+
200
+ /** Описание последнего коммита (первая строка) или пусто. */
201
+ export const lastSubject = (cwd, opts = {}) => runGit(['log', '-1', '--format=%s'], { cwd, ...opts }).then((s) => s.trim(), () => '');
202
+
203
+ /** Записывает адрес сервера (origin). Адрес — без входа: он передаётся отдельно, на время отправки. */
204
+ export async function setRemote(cwd, url, opts = {}) {
205
+ const has = await runGit(['config', '--get', 'remote.origin.url'], { cwd, ...opts }).then((s) => s.trim(), () => '');
206
+ await runGit(has ? ['remote', 'set-url', 'origin', url] : ['remote', 'add', 'origin', url], { cwd, ...opts });
207
+ }
@@ -0,0 +1,20 @@
1
+ // Что стоит за кнопкой списка в /git (файл, ветка, репозиторий, место публикации).
2
+ // Кнопка не должна ссылаться на номер в списке: список перерисовывается, и старая кнопка указала бы на другой элемент —
3
+ // для «Отменить изменения» это значило бы потерю не того файла. Поэтому каждому элементу при показе выдаётся ключ,
4
+ // который больше никогда не повторяется: старая кнопка ведёт либо к тому же элементу, либо никуда («кнопка устарела»).
5
+
6
+ let seq = 0;
7
+ /** Сколько ключей помнит диалог; сверх этого старые забываются, их кнопки становятся устаревшими. */
8
+ const KEEP = 600;
9
+
10
+ /** Запоминает значение за кнопкой и возвращает её ключ (короткая строка для callback_data). */
11
+ export function remember(st, value) {
12
+ st.gitKeys ??= new Map();
13
+ if (st.gitKeys.size >= KEEP) st.gitKeys.clear();
14
+ const key = (++seq).toString(36);
15
+ st.gitKeys.set(key, value);
16
+ return key;
17
+ }
18
+
19
+ /** Значение за кнопкой по её ключу или null, если кнопка устарела. */
20
+ export const recall = (st, key) => st.gitKeys?.get(String(key)) ?? null;
@@ -0,0 +1,42 @@
1
+ // Метки агента [[git:push]] и [[git:pull]]: у агента нет входа на сервер Git, поэтому отправить или получить изменения
2
+ // он просит бота. Бот убирает метку из ответа и показывает под ним кнопку — без нажатия пользователя ничего не уходит.
3
+ import { splitCode } from './files.mjs';
4
+
5
+ const MARK = /\[\[git:(push|pull)\]\]/gi;
6
+ /** После вырезанной метки: пробелы в конце строки и двойные пробелы внутри неё. */
7
+ const tidy = (s) => s.replace(/[ \t]+(\r?\n)/g, '$1').replace(/([^ \n]) {2,}/g, '$1 ');
8
+
9
+ /**
10
+ * Достаёт из ответа агента метки [[git:push]] и [[git:pull]] (вне кода) и убирает их из текста.
11
+ * @returns {{text: string, actions: ('push'|'pull')[]}} actions — без повторов, в порядке появления
12
+ */
13
+ export function extractGitMarks(text) {
14
+ const src = String(text ?? '');
15
+ if (!/\[\[git:/i.test(src)) return { text: src, actions: [] };
16
+ const actions = [];
17
+ const out = splitCode(src)
18
+ .map(({ code, s }) => {
19
+ if (code) return s;
20
+ return tidy(
21
+ s.replace(MARK, (_, a) => {
22
+ const action = a.toLowerCase();
23
+ if (!actions.includes(action)) actions.push(action);
24
+ return '';
25
+ }),
26
+ );
27
+ })
28
+ .join('');
29
+ return { text: out.replace(/\n{3,}/g, '\n\n').trim(), actions };
30
+ }
31
+
32
+ /** Для черновика: убирает целые метки и ещё не дописанную в конце («[[git:pu», «[[gi»). Код не трогает. */
33
+ export function stripGitMarks(text) {
34
+ const parts = splitCode(String(text ?? ''));
35
+ return parts
36
+ .map(({ code, s }, i) => {
37
+ if (code) return s;
38
+ const r = s.replace(MARK, '');
39
+ return i === parts.length - 1 ? r.replace(/\[\[g(?:i(?:t(?::(?:p(?:u(?:s(?:h(?:\]\]?)?)?|l(?:l(?:\]\]?)?)?)?)?)?)?)?)?$/i, '') : r;
40
+ })
41
+ .join('');
42
+ }
@@ -0,0 +1,239 @@
1
+ // Экраны /git «Опубликовать проект» и «Запрос на слияние».
2
+ // Публикация: папка, которая ещё не связана с сервером, становится репозиторием — пользователь выбирает сервис, место
3
+ // (личное пространство, группа или организация), видимость и название; бот создаёт репозиторий, делает первый коммит
4
+ // (без файлов с секретами) и отправляет. Запрос на слияние: из текущей ветки в основную ветку репозитория.
5
+ // Вызывается из gitUi.mjs, который передаёт общие помощники (h).
6
+ import { basename } from 'node:path';
7
+ import { db, log, say } from './ctx.mjs';
8
+ import { canManageFiles } from './filesUi.mjs';
9
+ import { GitError, commitAll, pushRepo, repoState } from './git.mjs';
10
+ import { accountsOf, findHost } from './gitAccess.mjs';
11
+ import { recall, remember } from './gitKeys.mjs';
12
+ import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visibilities } from './gitApi.mjs';
13
+ import { HostError, showRemote } from './gitHosts.mjs';
14
+ import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
15
+ import { errText, t } from './i18n.mjs';
16
+ import { userPath } from './state.mjs';
17
+ import { hCode, th } from './ui.mjs';
18
+
19
+ /** Действия кнопок этого модуля (gt:<действие>:<аргумент>). */
20
+ export const PUBLISH_ACTIONS = ['pb', 'pbh', 'pbn', 'pbs', 'pbv', 'pbname', 'pbgo', 'mr', 'mrgo'];
21
+ /** Ожидания текста, которые обрабатывает этот модуль. */
22
+ export const PUBLISH_INPUTS = ['gitNsSearch', 'gitRepoName', 'gitMrTitle'];
23
+
24
+ const HTML = { parse_mode: 'HTML', link_preview_options: { is_disabled: true } };
25
+ const NS_MAX = 30;
26
+ const VIS_MARK = { private: '🔒', internal: '🏢', public: '🌍' };
27
+ const backRow = (lang) => [{ text: t('btn.back', lang), callback_data: 'gt:v' }];
28
+ const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
29
+
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
+ /** Можно ли публиковать проект: это ещё не репозиторий с адресом сервера (свой репозиторий без origin — тоже можно). */
37
+ export async function canPublish(st, project, h) {
38
+ if (!canManageFiles(st.userId) || !accountsOf(st.userId).length) return false;
39
+ const opts = h.gitOpts(st, project);
40
+ if (!(await isRepoRoot(project, opts))) return true;
41
+ return !(await repoState(project, opts))?.remote;
42
+ }
43
+
44
+ const accountOf = (st, pub) => {
45
+ const host = findHost(pub?.hostId);
46
+ const account = host ? db.getGitAccount(st.userId, host.id) : null;
47
+ return host && account ? { host, account } : null;
48
+ };
49
+
50
+ /** Шаг «куда»: личное пространство и группы (организации) кнопками, поиск по группам. */
51
+ async function namespacesView(st, lang, search = '') {
52
+ const { host, account } = accountOf(st, st.gitPublish);
53
+ const list = (await listNamespaces(host, account.token, account.login, { search })).slice(0, NS_MAX);
54
+ const rows = list.map((n) => [{ text: [...(n.kind === 'user' ? `👤 ${n.path} — ${t('git.pb.personal', lang)}` : `👥 ${n.path}`)].slice(0, 60).join(''), callback_data: `gt:pbn:${remember(st, { host: host.id, namespace: n })}` }]);
55
+ rows.push([{ text: t('git.pb.search', lang), callback_data: 'gt:pbs' }, ...backRow(lang)]);
56
+ const head = th('git.pb.where', lang, { host: host.label, q: search ? ` «${search}»` : '' });
57
+ return { text: list.length ? head : `${head}\n\n<i>${th('git.pb.noPlaces', lang)}</i>`, markup: { inline_keyboard: rows } };
58
+ }
59
+
60
+ /** Итог перед созданием: что и куда публикуется; название можно изменить. */
61
+ function summaryView(st, project, lang) {
62
+ const pub = st.gitPublish;
63
+ const { host } = accountOf(st, pub);
64
+ const address = pub.slug ? `${showRemote(host.web)}/${pub.namespace.path}/${pub.slug}` : '—';
65
+ const text = th('git.pb.summary', lang, { p: hCode(userPath(st.userId, project, lang)), address: hCode(address), vis: `${VIS_MARK[pub.visibility]} ${t(`git.vis.${pub.visibility}`, lang)}` });
66
+ const rows = [
67
+ ...(pub.slug ? [[{ text: t('git.pb.go', lang), callback_data: 'gt:pbgo', style: 'success' }]] : []),
68
+ [{ text: t('git.pb.rename', lang), callback_data: 'gt:pbname' }],
69
+ backRow(lang),
70
+ ];
71
+ return { text, markup: { inline_keyboard: rows } };
72
+ }
73
+
74
+ /** Создаёт репозиторий на сервисе, делает первый коммит и отправляет. */
75
+ async function publish(st, project, lang, edit, h) {
76
+ const pub = st.gitPublish;
77
+ const { host, account } = accountOf(st, pub);
78
+ const opts = h.gitOpts(st, project, { host, account });
79
+ st.gitBusy = true;
80
+ try {
81
+ await edit({ text: th('git.pb.working', lang) });
82
+ // сначала локальная часть: если публиковать нечего, репозиторий на сервере не создаётся
83
+ await ensureRepo(project, opts);
84
+ const first = await commitAll(project, t('git.pb.firstCommit', lang), opts);
85
+ if (!(await hasCommits(project, opts))) return await edit({ text: th('git.pb.empty', lang), markup: { inline_keyboard: [backRow(lang)] } });
86
+ const created = await createRepo(host, account.token, { name: pub.name, slug: pub.slug, namespace: pub.namespace, visibility: pub.visibility });
87
+ log('git: репозиторий создан:', st.userId, host.id, created.path);
88
+ await setRemote(project, created.url, opts);
89
+ await pushRepo(project, opts);
90
+ log('git: проект опубликован:', st.userId, project, '→', created.path);
91
+ st.gitPublish = null;
92
+ const note = first.skipped.length ? `\n${th('git.skipped', lang, { files: first.skipped.join(', ') })}` : '';
93
+ const v = await h.view();
94
+ const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
95
+ 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] } });
96
+ } catch (e) {
97
+ log('git: публикация:', e.message, '| пользователь', st.userId);
98
+ return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
99
+ } finally {
100
+ st.gitBusy = false;
101
+ }
102
+ }
103
+
104
+ /** Создаёт запрос на слияние текущей ветки в основную (или находит уже открытый) и даёт ссылку. */
105
+ async function mergeRequest(st, project, title, lang, edit, h) {
106
+ const mr = st.gitMr;
107
+ const repo = await h.repoOf(st, project);
108
+ if (!mr || !repo?.account) return edit({ text: th('git.diff.gone', lang), markup: { inline_keyboard: [backRow(lang)] } });
109
+ st.gitMr = null;
110
+ try {
111
+ const r = await openMergeRequest(repo.host, repo.account.token, repo.state.remote, { branch: mr.branch, target: mr.target, title });
112
+ log('git: запрос на слияние:', st.userId, project, mr.branch, '→', mr.target, r.existed ? '(уже был)' : '');
113
+ const text = th(r.existed ? 'git.mr.exists' : 'git.mr.done', lang, { n: r.number, branch: hCode(mr.branch), target: hCode(mr.target) });
114
+ return await edit({ text, markup: { inline_keyboard: [[{ text: t('git.open', lang), url: r.url }], backRow(lang)] } });
115
+ } catch (e) {
116
+ log('git: запрос на слияние:', e.message, '| пользователь', st.userId);
117
+ return await edit({ text: failText(e, lang, repo.host), markup: { inline_keyboard: [backRow(lang)] } });
118
+ }
119
+ }
120
+
121
+ /** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). h — помощники из gitUi. */
122
+ export async function onPublishCallback(st, cb, h) {
123
+ const { action, arg, lang, ack, edit, project } = h;
124
+ if (!project) return ack(t('state.projectGone', lang));
125
+ if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
126
+ if (st.gitBusy) return ack(t('git.busy', lang));
127
+ if (st.busy) return ack(t('git.agentBusy', lang));
128
+ try {
129
+ // ---- запрос на слияние ----
130
+ if (action === 'mr') {
131
+ const repo = await h.repoOf(st, project);
132
+ if (!repo?.account || !repo.state.branch) return ack(t('proj.stale', lang));
133
+ await ack();
134
+ const info = await repoInfo(repo.host, repo.account.token, repo.state.remote);
135
+ const s = repo.state;
136
+ 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)] } });
137
+ 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)] } });
138
+ const suggested = (await lastSubject(project, h.gitOpts(st, project, repo))) || s.branch;
139
+ st.gitMr = { branch: s.branch, target: info.defaultBranch, suggested };
140
+ st.pendingInput = { kind: 'gitMrTitle', at: Date.now() };
141
+ const markup = { inline_keyboard: [[{ text: [...`«${suggested}»`].slice(0, 60).join(''), callback_data: 'gt:mrgo' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
142
+ return edit({ text: th('git.mr.ask', lang, { branch: hCode(s.branch), target: hCode(info.defaultBranch) }), markup });
143
+ }
144
+ if (action === 'mrgo') {
145
+ st.pendingInput = null;
146
+ await ack();
147
+ return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit, h);
148
+ }
149
+ // ---- публикация ----
150
+ if (!(await canPublish(st, project, h))) return ack(t('proj.stale', lang));
151
+ const accounts = accountsOf(st.userId);
152
+ if (action === 'pb') {
153
+ await ack();
154
+ st.gitPublish = { hostId: accounts[0].host.id, visibility: 'private', name: basename(project), slug: repoSlug(basename(project)) };
155
+ if (accounts.length === 1) return edit(await namespacesView(st, lang));
156
+ return edit({ text: th('git.pb.pickHost', lang), markup: { inline_keyboard: [...accounts.map((x) => [{ text: x.host.label, callback_data: `gt:pbh:${x.host.id}` }]), backRow(lang)] } });
157
+ }
158
+ const pub = st.gitPublish;
159
+ if (!pub) return ack(t('proj.stale', lang));
160
+ if (action === 'pbh') {
161
+ if (!accounts.some((x) => x.host.id === arg)) return ack(t('proj.stale', lang));
162
+ pub.hostId = arg;
163
+ await ack();
164
+ return edit(await namespacesView(st, lang));
165
+ }
166
+ if (!accountOf(st, pub)) return ack(t('proj.stale', lang));
167
+ if (action === 'pbs') {
168
+ await ack();
169
+ st.pendingInput = { kind: 'gitNsSearch', at: Date.now() };
170
+ return say(st.to, t('git.pb.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
171
+ }
172
+ if (action === 'pbn') {
173
+ const chosen = recall(st, arg);
174
+ const ns = chosen?.host === pub.hostId ? chosen.namespace : null; // место — того же сервиса, что выбран для публикации
175
+ if (!ns) return ack(t('proj.stale', lang));
176
+ pub.namespace = ns;
177
+ await ack();
178
+ const { host } = accountOf(st, pub);
179
+ const rows = visibilities(host).map((v) => [{ text: `${VIS_MARK[v]} ${t(`git.vis.${v}`, lang)} — ${t(`git.vis.${v}.hint`, lang)}`, callback_data: `gt:pbv:${v}` }]);
180
+ return edit({ text: th('git.pb.visAsk', lang, { where: hCode(ns.path) }), markup: { inline_keyboard: [...rows, backRow(lang)] } });
181
+ }
182
+ if (!pub.namespace) return ack(t('proj.stale', lang));
183
+ if (action === 'pbv') {
184
+ if (!visibilities(accountOf(st, pub).host).includes(arg)) return ack(t('proj.stale', lang));
185
+ pub.visibility = arg;
186
+ await ack();
187
+ return edit(summaryView(st, project, lang));
188
+ }
189
+ if (action === 'pbname') {
190
+ await ack();
191
+ st.pendingInput = { kind: 'gitRepoName', at: Date.now() };
192
+ return say(st.to, t('git.pb.nameAsk', lang), { reply_markup: cancelMarkup(lang) });
193
+ }
194
+ if (action === 'pbgo') {
195
+ if (!pub.slug) return ack(t('git.pb.nameBad', lang));
196
+ await ack();
197
+ return await publish(st, project, lang, edit, h);
198
+ }
199
+ return ack(t('proj.stale', lang));
200
+ } catch (e) {
201
+ log(`git: ${action}:`, e.message, '| пользователь', st.userId);
202
+ await ack();
203
+ return edit({ text: failText(e, lang, accountOf(st, st.gitPublish)?.host), markup: { inline_keyboard: [backRow(lang)] } });
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Текст пользователя для публикации и запроса на слияние: строка поиска группы, название репозитория, заголовок запроса.
209
+ * @param {object} h {wait, now, lang, project, send, repoOf, gitOpts, view}
210
+ * @returns {Promise<boolean>} true — текст обработан здесь
211
+ */
212
+ export async function onPublishInput(st, text, h) {
213
+ const { wait, lang, project, send } = h;
214
+ if (!project || !canManageFiles(st.userId)) return false;
215
+ try {
216
+ if (wait.kind === 'gitMrTitle') {
217
+ if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
218
+ const title = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || st.gitMr?.suggested || '';
219
+ await mergeRequest(st, project, title, lang, send, h);
220
+ return true;
221
+ }
222
+ const pub = st.gitPublish;
223
+ if (!pub || !accountOf(st, pub)) return false;
224
+ if (wait.kind === 'gitNsSearch') return (await send(await namespacesView(st, lang, text.trim().slice(0, 60))), true);
225
+ // название репозитория
226
+ const slug = repoSlug(text);
227
+ if (!slug) {
228
+ st.pendingInput = { ...wait, at: h.now }; // название не подошло — ждём другое
229
+ return (await say(st.to, t('git.pb.nameBad', lang), { reply_markup: cancelMarkup(lang) }), true);
230
+ }
231
+ Object.assign(pub, { name: text.trim().slice(0, 100), slug });
232
+ if (!pub.namespace) return (await send(await namespacesView(st, lang)), true);
233
+ return (await send(summaryView(st, project, lang)), true);
234
+ } catch (e) {
235
+ log('git: публикация (ввод):', e.message, '| пользователь', st.userId);
236
+ await say(st.to, failText(e, lang, accountOf(st, st.gitPublish)?.host), HTML);
237
+ return true;
238
+ }
239
+ }
package/src/gitRepoUi.mjs CHANGED
@@ -8,14 +8,15 @@ import { log, say } from './ctx.mjs';
8
8
  import { isSecretName, outboxDir, safeFileName } from './files.mjs';
9
9
  import { canManageFiles } from './filesUi.mjs';
10
10
  import { GitError, fetchRepo } from './git.mjs';
11
- import { branchName, changedFiles, commitList, createBranch, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
11
+ import { recall, remember } from './gitKeys.mjs';
12
+ import { branchName, changedFiles, commitList, createBranch, discardFiles, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
12
13
  import { errText, t } from './i18n.mjs';
13
14
  import { endAgent, userPath } from './state.mjs';
14
15
  import { escHtml, sendFile } from './telegram.mjs';
15
16
  import { hCode, th } from './ui.mjs';
16
17
 
17
18
  /** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
18
- export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn'];
19
+ export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn', 'dx', 'dX', 'da', 'dA'];
19
20
 
20
21
  const PAGE = 10;
21
22
  /** Изменения файла длиннее этого приходят файлом: в сообщение Telegram они не помещаются. */
@@ -38,13 +39,12 @@ const pager = (prefix, page, pages) => {
38
39
  /** Экран «Изменения»: несохранённые изменения рабочей папки кнопками по файлам и переходы к спискам коммитов. */
39
40
  async function changesView(st, project, repo, opts, page, lang) {
40
41
  const { files, total } = await changedFiles(project, opts);
41
- st.gitChanges = files; // кнопки ссылаются на файл номером в этом списке
42
42
  const pages = Math.max(1, Math.ceil(files.length / PAGE));
43
43
  page = Math.min(Math.max(page, 0), pages - 1);
44
44
  const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0);
45
45
  const head = th('git.ch.head', lang, { p: hCode(userPath(st.userId, project, lang)), branch: repo.state.branch ?? '—' });
46
46
  const body = total ? th('git.ch.sum', lang, { n: total, a: sum('added'), d: sum('deleted') }) + (total > files.length ? `\n<i>${th('git.ch.cut', lang, { n: files.length })}</i>` : '') : th('git.ch.none', lang);
47
- const rows = files.slice(page * PAGE, (page + 1) * PAGE).map((f, i) => [{ text: [...`${MARK[f.kind] ?? '✏️'} ${tail(f.path, 40)} ${counts(f)}`.trim()].slice(0, 60).join(''), callback_data: `gt:cf:${page * PAGE + i}` }]);
47
+ const rows = files.slice(page * PAGE, (page + 1) * PAGE).map((f) => [{ text: [...`${MARK[f.kind] ?? '✏️'} ${tail(f.path, 40)} ${counts(f)}`.trim()].slice(0, 60).join(''), callback_data: `gt:cf:${remember(st, { path: f.path })}` }]);
48
48
  if (pages > 1) rows.push(pager('gt:ch', page, pages));
49
49
  const s = repo.state;
50
50
  const commits = [];
@@ -52,19 +52,22 @@ async function changesView(st, project, repo, opts, page, lang) {
52
52
  if (s.upstream && s.ahead) commits.push({ text: t('git.ch.out', lang, { n: s.ahead }), callback_data: 'gt:cm:o' });
53
53
  if (s.upstream && s.behind) commits.push({ text: t('git.ch.in', lang, { n: s.behind }), callback_data: 'gt:cm:i' });
54
54
  if (commits.length) rows.push(commits);
55
+ if (files.length && canManageFiles(st.userId)) rows.push([{ text: t('git.da.btn', lang), callback_data: 'gt:da' }]);
55
56
  rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
56
57
  return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
57
58
  }
58
59
 
60
+ /** Файлы с секретами отменой не трогаем: ими пользователь управляет сам в /files. */
61
+ const isSecretFile = (f) => isSecretName(`/${f.path}`);
62
+
59
63
  /** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
60
64
  async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
61
65
  // ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
62
66
  if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
63
67
  const { current, branches } = await listBranches(project, opts);
64
- st.gitBranches = branches;
65
68
  const pages = Math.max(1, Math.ceil(branches.length / PAGE));
66
69
  page = Math.min(Math.max(page, 0), pages - 1);
67
- const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b, i) => [{ text: [...`${b.current ? '✓' : b.local ? '🌿' : '☁️'} ${b.name}`].slice(0, 60).join(''), callback_data: `gt:bs:${page * PAGE + i}` }]);
70
+ const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b) => [{ text: [...`${b.current ? '✓' : b.local ? '🌿' : '☁️'} ${b.name}`].slice(0, 60).join(''), callback_data: `gt:bs:${remember(st, { branch: b.name })}` }]);
68
71
  if (pages > 1) rows.push(pager('gt:br', page, pages));
69
72
  if (canManageFiles(st.userId)) rows.push([{ text: t('git.br.new', lang), callback_data: 'gt:bn' }]);
70
73
  rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
@@ -72,10 +75,12 @@ async function branchesView(st, project, repo, opts, page, lang, { sync = false
72
75
  }
73
76
 
74
77
  /** Изменения одного файла: короткие — в сообщении, длинные — файлом; содержимое файлов с секретами не показывается. */
75
- async function showDiff(st, project, file, opts, lang, edit) {
76
- const back = { inline_keyboard: [[{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }]] };
78
+ async function showDiff(st, project, file, index, opts, lang, edit) {
79
+ const toList = [{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }];
77
80
  const title = `${MARK[file.kind] ?? '✏️'} ${hCode(file.path).html}`;
78
- if (isSecretName(`/${file.path}`)) return edit({ text: th('git.diff.secret', lang, { path: hCode(file.path) }), markup: back });
81
+ if (isSecretFile(file)) return edit({ text: th('git.diff.secret', lang, { path: hCode(file.path) }), markup: { inline_keyboard: [toList] } });
82
+ // «Вернуть как было» — отмена изменений этого файла (с подтверждением)
83
+ const back = { inline_keyboard: [...(canManageFiles(st.userId) ? [[{ text: t('git.dx.btn', lang), callback_data: `gt:dx:${index}` }]] : []), toList] };
79
84
  const diff = await fileDiff(project, file, opts);
80
85
  if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
81
86
  if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
@@ -114,10 +119,12 @@ export async function onRepoCallback(st, cb, h) {
114
119
  if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
115
120
  if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
116
121
  if (action === 'cf') {
117
- const file = st.gitChanges?.[Number(arg)];
122
+ // кнопка помнит путь файла; сам файл ищется в свежем списке изменений
123
+ const path = recall(st, arg)?.path;
124
+ const file = path ? (await changedFiles(project, opts)).files.find((f) => f.path === path) : null;
118
125
  if (!file) return ack(t('git.diff.gone', lang));
119
126
  await ack();
120
- return await showDiff(st, project, file, opts, lang, edit);
127
+ return await showDiff(st, project, file, arg, opts, lang, edit);
121
128
  }
122
129
  if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
123
130
  // ---- переключение и создание ветки меняют проект ----
@@ -129,7 +136,50 @@ export async function onRepoCallback(st, cb, h) {
129
136
  st.pendingInput = { kind: 'gitBranch', at: Date.now() };
130
137
  return say(st.to, th('git.br.nameAsk', lang, { branch: hCode(repo.state.branch ?? '—') }), { parse_mode: 'HTML', reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } });
131
138
  }
132
- const branch = st.gitBranches?.[Number(arg)];
139
+ // ---- отмена изменений: необратимо, поэтому сначала вопрос, а список файлов берётся заново ----
140
+ if (['dx', 'dX', 'da', 'dA'].includes(action)) {
141
+ 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
+ };
150
+ const show = async (note) => {
151
+ const v = await changesView(st, project, await h.repoOf(st, project), opts, 0, lang);
152
+ return edit({ text: `${note}\n\n${v.text}`, markup: v.markup });
153
+ };
154
+ if (action === 'dx' || action === 'dX') {
155
+ const path = recall(st, arg)?.path;
156
+ const file = path ? fresh.find((f) => f.path === path) : null;
157
+ if (!file) return ack(t('git.diff.gone', lang));
158
+ if (isSecretFile(file)) return ack(t('git.dx.secret', lang));
159
+ await ack();
160
+ if (action === 'dx') {
161
+ const markup = { inline_keyboard: [[{ text: t('git.dx.yes', lang), callback_data: `gt:dX:${arg}` }, { text: t('btn.cancel', lang), callback_data: `gt:cf:${arg}` }]] };
162
+ return edit({ text: th(file.kind === 'new' ? 'git.dx.askNew' : 'git.dx.ask', lang, { path: hCode(file.path) }), markup });
163
+ }
164
+ await run([file]);
165
+ log('git: изменения файла отменены:', st.userId, project, file.path);
166
+ return show(th('git.dx.done', lang, { path: hCode(file.path) }));
167
+ }
168
+ const list = fresh.filter((f) => !isSecretFile(f));
169
+ if (!list.length) return ack(t('git.ch.none', lang));
170
+ await ack();
171
+ if (action === 'da') {
172
+ const markup = { inline_keyboard: [[{ text: t('git.da.yes', lang), callback_data: 'gt:dA' }, { text: t('btn.cancel', lang), callback_data: 'gt:ch:0' }]] };
173
+ const names = list.slice(0, 15).map((f) => `${MARK[f.kind] ?? '✏️'} ${escHtml(f.path)}`).join('\n') + (list.length > 15 ? '\n…' : '');
174
+ return edit({ text: `${th('git.da.ask', lang, { n: list.length })}\n\n${names}`, markup });
175
+ }
176
+ const n = await run(list);
177
+ log('git: все изменения отменены:', st.userId, project, '| файлов', n);
178
+ return show(th('git.da.done', lang, { n }));
179
+ }
180
+ // кнопка помнит название ветки; сама ветка ищется в свежем списке
181
+ const name = recall(st, arg)?.branch;
182
+ const branch = name ? (await listBranches(project, opts)).branches.find((b) => b.name === name) : null;
133
183
  if (!branch) return ack(t('proj.stale', lang));
134
184
  if (branch.current) return ack(t('git.br.same', lang));
135
185
  // несохранённые изменения git либо не даст унести, либо молча перенесёт в другую ветку — сначала их нужно сохранить
package/src/gitUi.mjs CHANGED
@@ -5,7 +5,9 @@ import { join } from 'node:path';
5
5
  import { db, langOf, log, say } from './ctx.mjs';
6
6
  import { canManageFiles } from './filesUi.mjs';
7
7
  import { GitError, cloneRepo, commitAll, fetchRepo, gitAvailable, gitCommand, gitEnv, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
8
+ import { recall, remember } from './gitKeys.mjs';
8
9
  import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
10
+ import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
9
11
  import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
10
12
  import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
11
13
  import { LOCALES, errText, t } from './i18n.mjs';
@@ -80,12 +82,16 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
80
82
  if (canManageFiles(st.userId)) {
81
83
  rows.push([{ text: t('git.pull', lang), callback_data: 'gt:pull' }, { text: t('git.push', lang), callback_data: 'gt:push' }]);
82
84
  rows.push([{ text: t('git.save', lang), callback_data: 'gt:save', style: 'success' }]);
85
+ if (s.branch) rows.push([{ text: t('git.mrBtn', lang), callback_data: 'gt:mr' }]);
83
86
  }
84
87
  } else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
85
88
  else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
86
89
  // что изменено и какие есть ветки — можно смотреть без агента и без аккаунта
87
90
  rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
88
91
  } else lines.push(th('git.noRepo', lang));
92
+ // папку, которая ещё не связана с сервером, можно опубликовать: бот создаст для неё репозиторий
93
+ const publishable = project && !repo?.state.remote ? await canPublish(st, project, { gitOpts }).catch(() => false) : false;
94
+ if (publishable) rows.push([{ text: t('git.pbBtn', lang), callback_data: 'gt:pb' }]);
89
95
  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));
90
96
  if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
91
97
  for (const h of hosts) {
@@ -119,6 +125,22 @@ export async function handleGit(st) {
119
125
  return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
120
126
  }
121
127
 
128
+ /**
129
+ * Агент попросил отправить или получить изменения (метки [[git:push]] / [[git:pull]] в ответе): под ответом —
130
+ * сообщение с кнопкой. Нажатие выполняет ту же операцию, что и кнопка на экране /git. Проект не связан с сервером
131
+ * или аккаунт не подключён — подсказка открыть /git.
132
+ * @param {('push'|'pull')[]} actions
133
+ */
134
+ export async function offerGitActions(st, actions) {
135
+ if (!gitAvailable() || !actions.length) return;
136
+ const lang = langOf(st.userId);
137
+ const project = projectOf(st);
138
+ const repo = project ? await repoOf(st, project).catch(() => null) : null;
139
+ if (!repo?.account || !canManageFiles(st.userId)) return say(st.to, t('git.offer.noAccount', lang), { reply_markup: { inline_keyboard: [[{ text: t('start.btn.git', lang), callback_data: 'ui:git' }]] } });
140
+ const row = actions.map((a) => ({ text: t(a === 'push' ? 'git.push' : 'git.pull', lang), callback_data: a === 'push' ? 'gt:push' : 'gt:pull' }));
141
+ return say(st.to, t(actions.length > 1 ? 'git.offer.both' : `git.offer.${actions[0]}`, lang), { reply_markup: { inline_keyboard: [row] } });
142
+ }
143
+
122
144
  /** Текст ошибки git или сервиса для пользователя. */
123
145
  const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
124
146
 
@@ -129,12 +151,12 @@ function cloneBase(st) {
129
151
  return insideRoot(navStart(st.project, root), root) ?? (root ? insideRoot(root, root) : null);
130
152
  }
131
153
 
132
- /** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<номер> по запомненному списку. */
154
+ /** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<ключ кнопки> (gitKeys). */
133
155
  async function reposView(st, host, account, { page = 0, search = '' } = {}, lang) {
134
156
  const { items, more } = await listRepos(host, account.token, { page, search });
135
- st.gitRepos = { host: host.id, items, page, search };
157
+ st.gitRepos = { host: host.id, page, search }; // для перелистывания с тем же поиском
136
158
  const base = cloneBase(st);
137
- const rows = items.map((r, i) => [{ text: [...`${r.private ? '🔒' : '📂'} ${r.name}`].slice(0, 60).join(''), callback_data: `gt:k:${i}` }]);
159
+ const rows = items.map((r) => [{ text: [...`${r.private ? '🔒' : '📂'} ${r.name}`].slice(0, 60).join(''), callback_data: `gt:k:${remember(st, { host: host.id, repo: r })}` }]);
138
160
  const nav = [];
139
161
  if (page > 0) nav.push({ text: '◀', callback_data: `gt:r:${host.id}:${page - 1}` });
140
162
  if (more) nav.push({ text: '▶', callback_data: `gt:r:${host.id}:${page + 1}` });
@@ -266,6 +288,8 @@ export async function onGitCallback(st, cb) {
266
288
  }
267
289
  // экраны «Изменения» и «Ветки» — gitRepoUi
268
290
  if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
291
+ // «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
292
+ if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
269
293
  const host = findHost(arg);
270
294
  const account = host ? db.getGitAccount(st.userId, host.id) : null;
271
295
  try {
@@ -309,9 +333,9 @@ export async function onGitCallback(st, cb) {
309
333
  return say(st.to, t('git.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
310
334
  }
311
335
  if (action === 'k') {
312
- const list = st.gitRepos;
313
- const repo = list?.items[Number(arg)];
314
- const h = findHost(list?.host);
336
+ const chosen = recall(st, arg);
337
+ const repo = chosen?.repo;
338
+ const h = findHost(chosen?.host);
315
339
  const acc = h ? db.getGitAccount(st.userId, h.id) : null;
316
340
  if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
317
341
  if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
@@ -359,7 +383,7 @@ const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_i
359
383
  */
360
384
  export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
361
385
  const wait = st.pendingInput;
362
- if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch'].includes(wait?.kind)) return false;
386
+ if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch', ...PUBLISH_INPUTS].includes(wait?.kind)) return false;
363
387
  const lang = langOf(st.userId);
364
388
  const expired = now - wait.at > GIT_WAIT_MS;
365
389
  const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
@@ -378,7 +402,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
378
402
  profile = await fetchProfile(host, token);
379
403
  } catch (e) {
380
404
  log('git: проверка токена:', e.message, '| пользователь', st.userId);
381
- const textFail = e instanceof HostError && e.code === 'auth' ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
405
+ const textFail = e instanceof HostError && ['auth', 'forbidden'].includes(e.code) ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
382
406
  return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
383
407
  }
384
408
  st.pendingInput = null;
@@ -400,6 +424,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
400
424
  st.pendingInput = null;
401
425
  if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
402
426
  if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
427
+ if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
403
428
  // свои серверы: адрес нового сервера или новое название — только от администратора
404
429
  if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
405
430
  if (!isAdmin(st.userId)) return false;
package/src/i18n.mjs CHANGED
@@ -304,7 +304,7 @@ const M = {
304
304
  'git.tokenFail': { en: "⚠️ Could not check the token: {msg}. Your message was deleted; send the token again.", ru: "⚠️ Не удалось проверить токен: {msg}. Ваше сообщение удалено; отправьте токен ещё раз.", uk: "⚠️ Не вдалося перевірити токен: {msg}. Ваше повідомлення видалено; надішліть токен ще раз." },
305
305
  'git.connected': { en: "✅ {host} connected: {login} ({name}). The message with the token was deleted from the chat.", ru: "✅ {host} подключён: {login} ({name}). Сообщение с токеном удалено из чата.", uk: "✅ {host} підключено: {login} ({name}). Повідомлення з токеном видалено з чату." },
306
306
  'git.expires': { en: "The token is valid until {date}.", ru: "Токен действует до {date}.", uk: "Токен дійсний до {date}." },
307
- 'git.scopesWarn': { en: "⚠️ The token lacks permissions: {scopes} — cloning or pushing may not work.", ru: "⚠️ Токену не хватает прав: {scopes} — клонирование или отправка могут не работать.", uk: "⚠️ Токену бракує прав: {scopes} — клонування або надсилання можуть не працювати." },
307
+ 'git.scopesWarn': { en: "⚠️ The token lacks permissions: {scopes} — some features will not work (cloning, pushing, publishing or merge requests).", ru: "⚠️ Токену не хватает прав: {scopes} — часть возможностей не будет работать (клонирование, отправка, публикация или запросы на слияние).", uk: "⚠️ Токену бракує прав: {scopes} — частина можливостей не працюватиме (клонування, надсилання, публікація або запити на злиття)." },
308
308
  'git.accCard': { en: "{host}\nAccount: {login} ({name})\nCommit email: {email}\nToken valid until: {date}", ru: "{host}\nАккаунт: {login} ({name})\nПочта для коммитов: {email}\nТокен действует до: {date}", uk: "{host}\nАкаунт: {login} ({name})\nПошта для комітів: {email}\nТокен дійсний до: {date}" },
309
309
  'git.disconnect': { en: "Disconnect", ru: "Отключить", uk: "Відключити" },
310
310
  'git.disconnectAsk': { en: "Disconnect {host} ({login})? The token will be removed from the bot.", ru: "Отключить {host} ({login})? Токен будет удалён из бота.", uk: "Відключити {host} ({login})? Токен буде видалено з бота." },
@@ -382,6 +382,53 @@ const M = {
382
382
  'git.br.switched': { en: "✅ You are on the branch {name}. The next request to the agent starts a new session.", ru: "✅ Вы на ветке {name}. Следующий запрос агенту начнёт новую сессию.", uk: "✅ Ви на гілці {name}. Наступний запит агенту почне нову сесію." },
383
383
  'git.br.dirty': { en: "⚠️ The project has unsaved changes (files: {n}). Save them first — otherwise they would move to the branch {name} or get lost.", ru: "⚠️ В проекте есть несохранённые изменения (файлов: {n}). Сначала сохраните их — иначе они перейдут в ветку {name} или потеряются.", uk: "⚠️ У проєкті є незбережені зміни (файлів: {n}). Спочатку збережіть їх — інакше вони перейдуть у гілку {name} або загубляться." },
384
384
  'git.br.same': { en: "You are already on this branch.", ru: "Вы уже на этой ветке.", uk: "Ви вже на цій гілці." },
385
+ 'git.da.btn': { en: "↩️ Discard all changes", ru: "↩️ Отменить все изменения", uk: "↩️ Скасувати всі зміни" },
386
+ 'git.da.ask': { en: "↩️ Discard all unsaved changes (files: {n})? Modified and deleted files return to the last commit, new files are deleted. This cannot be undone. Files with secrets are not touched.", ru: "↩️ Отменить все несохранённые изменения (файлов: {n})? Изменённые и удалённые файлы вернутся к последнему коммиту, новые будут удалены. Восстановить их будет нельзя. Файлы с секретами не затрагиваются.", uk: "↩️ Скасувати всі незбережені зміни (файлів: {n})? Змінені й видалені файли повернуться до останнього коміту, нові буде видалено. Відновити їх буде неможливо. Файли із секретами не зачіпаються." },
387
+ 'git.da.yes': { en: "Yes, discard everything", ru: "Да, отменить всё", uk: "Так, скасувати все" },
388
+ 'git.da.done': { en: "↩️ Changes discarded, files: {n}.", ru: "↩️ Изменения отменены, файлов: {n}.", uk: "↩️ Зміни скасовано, файлів: {n}." },
389
+ 'git.dx.btn': { en: "↩️ Restore as it was", ru: "↩️ Вернуть как было", uk: "↩️ Повернути як було" },
390
+ 'git.dx.ask': { en: "↩️ Return the file {path} to the last commit? The unsaved changes in it will be lost and cannot be restored.", ru: "↩️ Вернуть файл {path} к последнему коммиту? Несохранённые изменения в нём пропадут, восстановить их будет нельзя.", uk: "↩️ Повернути файл {path} до останнього коміту? Незбережені зміни в ньому зникнуть, відновити їх буде неможливо." },
391
+ 'git.dx.askNew': { en: "↩️ Delete the new file {path}? It is not in the repository yet, so it cannot be restored.", ru: "↩️ Удалить новый файл {path}? В репозитории его ещё нет, восстановить его будет нельзя.", uk: "↩️ Видалити новий файл {path}? У репозиторії його ще немає, відновити його буде неможливо." },
392
+ 'git.dx.yes': { en: "Yes, discard", ru: "Да, отменить", uk: "Так, скасувати" },
393
+ 'git.dx.done': { en: "↩️ The changes in {path} were discarded.", ru: "↩️ Изменения в файле {path} отменены.", uk: "↩️ Зміни у файлі {path} скасовано." },
394
+ 'git.dx.secret': { en: "Files with secrets are not changed from here — manage them in /files.", ru: "Файлы с секретами отсюда не меняются — управляйте ими в /files.", uk: "Файли із секретами звідси не змінюються — керуйте ними в /files." },
395
+ 'git.mrBtn': { en: "🔀 Merge request", ru: "🔀 Запрос на слияние", uk: "🔀 Запит на злиття" },
396
+ 'git.mr.ask': { en: "🔀 Merge request from {branch} into {target}. Send the title in one message — or press the suggested one.", ru: "🔀 Запрос на слияние ветки {branch} в {target}. Отправьте заголовок одним сообщением — или нажмите на предложенный.", uk: "🔀 Запит на злиття гілки {branch} у {target}. Надішліть заголовок одним повідомленням — або натисніть на запропонований." },
397
+ 'git.mr.onDefault': { en: "You are on the main branch {branch}. A merge request is made from another branch — create one in “Branches”.", ru: "Вы на основной ветке {branch}. Запрос на слияние делается из другой ветки — создайте её в «Ветках».", uk: "Ви на основній гілці {branch}. Запит на злиття робиться з іншої гілки — створіть її у «Гілках»." },
398
+ 'git.mr.pushFirst': { en: "First push the changes of the branch {branch} to the server.", ru: "Сначала отправьте изменения ветки {branch} на сервер.", uk: "Спочатку надішліть зміни гілки {branch} на сервер." },
399
+ 'git.mr.done': { en: "✅ Merge request #{n} created: {branch} → {target}.", ru: "✅ Запрос на слияние №{n} создан: {branch} → {target}.", uk: "✅ Запит на злиття №{n} створено: {branch} → {target}." },
400
+ 'git.mr.exists': { en: "ℹ️ A merge request {branch} → {target} is already open (#{n}).", ru: "ℹ️ Запрос на слияние {branch} → {target} уже открыт (№{n}).", uk: "ℹ️ Запит на злиття {branch} → {target} уже відкрито (№{n})." },
401
+ 'git.open': { en: "🔗 Open", ru: "🔗 Открыть", uk: "🔗 Відкрити" },
402
+ 'git.needApi': { en: "⚠️ {host}: the token lacks permissions for this action ({msg}). Create a token with the api permission and connect the account again in /git.", ru: "⚠️ {host}: токену не хватает прав для этого действия ({msg}). Создайте токен с правом api и подключите аккаунт заново в /git.", uk: "⚠️ {host}: токену бракує прав для цієї дії ({msg}). Створіть токен із правом api й підключіть акаунт знову в /git." },
403
+ 'git.pbBtn': { en: "🚀 Publish the project", ru: "🚀 Опубликовать проект", uk: "🚀 Опублікувати проєкт" },
404
+ 'git.pb.pickHost': { en: "🚀 Where to publish the project?", ru: "🚀 Где опубликовать проект?", uk: "🚀 Де опублікувати проєкт?" },
405
+ 'git.pb.where': { en: "🚀 Publishing to {host}{q}. Choose where to create the repository:", ru: "🚀 Публикация на {host}{q}. Выберите, где создать репозиторий:", uk: "🚀 Публікація на {host}{q}. Оберіть, де створити репозиторій:" },
406
+ 'git.pb.personal': { en: "personal space", ru: "личное пространство", uk: "особистий простір" },
407
+ 'git.pb.noPlaces': { en: "(nothing found)", ru: "(ничего не найдено)", uk: "(нічого не знайдено)" },
408
+ 'git.pb.search': { en: "🔎 Find a group", ru: "🔎 Найти группу", uk: "🔎 Знайти групу" },
409
+ 'git.pb.searchAsk': { en: "Send a part of the group name.", ru: "Отправьте часть названия группы.", uk: "Надішліть частину назви групи." },
410
+ 'git.pb.visAsk': { en: "🚀 The repository will be created in {where}. Who may see it?", ru: "🚀 Репозиторий будет создан в {where}. Кто сможет его видеть?", uk: "🚀 Репозиторій буде створено в {where}. Хто зможе його бачити?" },
411
+ 'git.vis.private': { en: "Private", ru: "Закрытый", uk: "Закритий" },
412
+ 'git.vis.private.hint': { en: "only you and invited people", ru: "только вы и приглашённые", uk: "лише ви та запрошені" },
413
+ 'git.vis.internal': { en: "Internal", ru: "Внутренний", uk: "Внутрішній" },
414
+ 'git.vis.internal.hint': { en: "all users of the server", ru: "все пользователи сервера", uk: "усі користувачі сервера" },
415
+ 'git.vis.public': { en: "Public", ru: "Открытый", uk: "Відкритий" },
416
+ 'git.vis.public.hint': { en: "everyone on the internet", ru: "все в интернете", uk: "усі в інтернеті" },
417
+ 'git.pb.summary': { en: "🚀 Publishing the project {p}\nAddress: {address}\nVisibility: {vis}\n\nThe bot will create the repository, make the first commit (files with secrets are left out) and push it.", ru: "🚀 Публикация проекта {p}\nАдрес: {address}\nВидимость: {vis}\n\nБот создаст репозиторий, сделает первый коммит (файлы с секретами в него не попадут) и отправит его.", uk: "🚀 Публікація проєкту {p}\nАдреса: {address}\nВидимість: {vis}\n\nБот створить репозиторій, зробить перший коміт (файли із секретами до нього не потраплять) і надішле його." },
418
+ 'git.pb.go': { en: "🚀 Create and push", ru: "🚀 Создать и отправить", uk: "🚀 Створити й надіслати" },
419
+ 'git.pb.rename': { en: "✏️ Another name", ru: "✏️ Другое название", uk: "✏️ Інша назва" },
420
+ 'git.pb.nameAsk': { en: "Send the repository name (Latin letters, digits, “-”, “_”, “.”).", ru: "Отправьте название репозитория (латиница, цифры, «-», «_», «.»).", uk: "Надішліть назву репозиторію (латиниця, цифри, «-», «_», «.»)." },
421
+ 'git.pb.nameBad': { en: "⚠️ A Latin name is needed: letters, digits, “-”, “_”, “.”. Send another one.", ru: "⚠️ Нужно название латиницей: буквы, цифры, «-», «_», «.». Отправьте другое.", uk: "⚠️ Потрібна назва латиницею: літери, цифри, «-», «_», «.». Надішліть іншу." },
422
+ 'git.pb.working': { en: "⏳ Creating the repository and pushing the files…", ru: "⏳ Создаю репозиторий и отправляю файлы…", uk: "⏳ Створюю репозиторій і надсилаю файли…" },
423
+ 'git.pb.firstCommit': { en: "First commit", ru: "Первый коммит", uk: "Перший коміт" },
424
+ 'git.pb.empty': { en: "ℹ️ The project has no files to publish — the repository was not created.", ru: "ℹ️ В проекте нет файлов для публикации — репозиторий не создан.", uk: "ℹ️ У проєкті немає файлів для публікації — репозиторій не створено." },
425
+ 'git.pb.done': { en: "✅ The project is published: {address}", ru: "✅ Проект опубликован: {address}", uk: "✅ Проєкт опубліковано: {address}" },
426
+ 'git.offer.push': { en: "⬆️ The agent suggests pushing the changes to the server.", ru: "⬆️ Агент предлагает отправить изменения на сервер.", uk: "⬆️ Агент пропонує надіслати зміни на сервер." },
427
+ 'git.offer.pull': { en: "⬇️ The agent suggests pulling the changes from the server.", ru: "⬇️ Агент предлагает получить изменения с сервера.", uk: "⬇️ Агент пропонує отримати зміни із сервера." },
428
+ 'git.offer.both': { en: "🔀 The agent suggests pulling the changes from the server and pushing its own.", ru: "🔀 Агент предлагает получить изменения с сервера и отправить свои.", uk: "🔀 Агент пропонує отримати зміни із сервера й надіслати свої." },
429
+ 'git.offer.noAccount': { en: "ℹ️ The agent suggests pushing or pulling changes, but the project is not connected to a Git server or the account is not connected. Open /git.", ru: "ℹ️ Агент предлагает отправить или получить изменения, но проект не связан с сервером Git или аккаунт не подключён. Откройте /git.", uk: "ℹ️ Агент пропонує надіслати або отримати зміни, але проєкт не пов’язаний із сервером Git або акаунт не підключено. Відкрийте /git." },
430
+ 'git.exp.soon': { en: "⏰ The access token for {host} ({login}) expires on {date} — days left: {days}. Create a new one and connect the account again in /git, otherwise cloning and pushing will stop working.", ru: "⏰ Токен доступа к {host} ({login}) истекает {date} — осталось дней: {days}. Создайте новый и подключите аккаунт заново в /git, иначе клонирование и отправка перестанут работать.", uk: "⏰ Токен доступу до {host} ({login}) спливає {date} — залишилося днів: {days}. Створіть новий і підключіть акаунт знову в /git, інакше клонування й надсилання перестануть працювати." },
431
+ 'git.exp.expired': { en: "⛔ The access token for {host} ({login}) expired on {date}. Connect the account again in /git with a new token.", ru: "⛔ Токен доступа к {host} ({login}) истёк {date}. Подключите аккаунт заново в /git с новым токеном.", uk: "⛔ Токен доступу до {host} ({login}) сплив {date}. Підключіть акаунт знову в /git із новим токеном." },
385
432
  'proj.notFound': { en: '⚠️ The folder was not found or is unavailable', ru: '⚠️ Папка не найдена или недоступна', uk: '⚠️ Папку не знайдено або вона недоступна' },
386
433
  'proj.same': { en: '📁 Project already selected: {p}', ru: '📁 Проект уже выбран: {p}', uk: '📁 Проєкт уже обрано: {p}' },
387
434
  'proj.set': { en: '📁 Project: {p}\nA new session starts with the next request.', ru: '📁 Проект: {p}\nНовая сессия начнётся со следующего запроса.', uk: '📁 Проєкт: {p}\nНова сесія почнеться з наступного запиту.' },
package/src/turn.mjs CHANGED
@@ -10,6 +10,8 @@ import { ClosedError, LimitError, ProjectError, dropPermissions, engineOf, ensur
10
10
  import { diffOf, parseTool } from './tools.mjs';
11
11
  import { lineDiff } from './diff.mjs';
12
12
  import { gitNote } from './gitAccess.mjs';
13
+ import { extractGitMarks, stripGitMarks } from './gitMarks.mjs';
14
+ import { offerGitActions } from './gitUi.mjs';
13
15
  import { ASK_NOTE, ASK_PLACEHOLDER, askChoice, extractAsks, placeAsks, stripAskMarks } from './asks.mjs';
14
16
  import { dest, tg, mediaIdsOf, sendFile, sendRich, sendRichDraft, sendThinkingDraft, escHtml } from './telegram.mjs';
15
17
  import { composeDraft, finalExtras, finalMessages, lastThoughtTitle, neutralizeTgTags, toolMeta, trunc } from './ui.mjs';
@@ -266,7 +268,7 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
266
268
  if (!dirty && Date.now() - lastSent < HEARTBEAT_MS) return;
267
269
  dirty = false;
268
270
  lastSent = Date.now();
269
- const d = composeDraft({ thought, steps, plan, answer: stripAskMarks(stripTitle(stripSendMarks(neutralizeTgTags(clean(answer))))), elapsedMs: Date.now() - startedAt, lang });
271
+ const d = composeDraft({ thought, steps, plan, answer: stripAskMarks(stripGitMarks(stripTitle(stripSendMarks(neutralizeTgTags(clean(answer)))))), elapsedMs: Date.now() - startedAt, lang });
270
272
  const draft = d.plain ? '(точки Telegram)' : d.markdown;
271
273
  if (draft !== lastText) dbg(`draft u${st.userId}`, draft);
272
274
  lastText = draft;
@@ -383,7 +385,8 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
383
385
  // метки [[send:путь]] (вне кода) → заглушки: на их место встанут сами файлы
384
386
  // теги <tg-button> в тексте агента обезвреживаются: кнопки бота рисует только сам бот (ui.mjs)
385
387
  const titled = extractTitle(neutralizeTgTags(clean(answer))); // строка с названием темы — в название, а не в ответ
386
- const asked = extractAsks(titled.text); // метки [[ask: …]] → заглушки: на их место встанут кнопки быстрого ответа
388
+ const gitted = extractGitMarks(titled.text); // метки [[git:push]] / [[git:pull]] → кнопки под ответом: вход на сервер есть только у бота
389
+ const asked = extractAsks(gitted.text); // метки [[ask: …]] → заглушки: на их место встанут кнопки быстрого ответа
387
390
  const sent = extractSendMarks(asked.text, { placeholders: true });
388
391
  const answerText = sent.text.replace(FILE_PLACEHOLDER, '').replace(ASK_PLACEHOLDER, '').trim(); // ответ без файлов и кнопок: для базы и проверки «пустой ли»
389
392
  db.finishRequest(st.requestId, { stopReason, answer: answerText, error, usage: usage ?? {} });
@@ -421,6 +424,8 @@ export async function runTurn(st, text, { files = [], quote = null } = {}) {
421
424
  const inAnswer = Object.keys(placed.media).length - loose.length;
422
425
  if (inAnswer > 0) log('файлы в ответе:', inAnswer, '| пользователь', st.userId);
423
426
  if (loose.length || placed.extra.length) await sendLooseFiles(st, [...loose, ...placed.extra], lang);
427
+ // агент попросил отправить или получить изменения: кнопка под ответом, без нажатия ничего не уходит
428
+ if (!limited && gitted.actions.length) await offerGitActions(st, gitted.actions).catch((e) => log('git: предложение агента:', e.message));
424
429
  if (naming && !limited && stopReason !== 'error') await nameTopic(st, titled.title || titleFromRequest(text || dbText));
425
430
  return drainQueue(st);
426
431
  }