acpgram 1.28.0 → 1.30.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 +8 -1
- package/README.ru.md +14 -2
- package/package.json +1 -1
- package/src/bot.mjs +19 -2
- package/src/db.mjs +19 -4
- package/src/gitAccess.mjs +71 -2
- package/src/gitApi.mjs +79 -0
- package/src/gitDevice.mjs +121 -0
- package/src/gitHosts.mjs +29 -10
- package/src/gitInspect.mjs +45 -1
- package/src/gitKeys.mjs +20 -0
- package/src/gitMarks.mjs +42 -0
- package/src/gitPublishUi.mjs +239 -0
- package/src/gitRepoUi.mjs +62 -12
- package/src/gitUi.mjs +122 -22
- package/src/i18n.mjs +59 -1
- package/src/state.mjs +3 -1
- package/src/turn.mjs +7 -2
package/src/gitUi.mjs
CHANGED
|
@@ -5,7 +5,10 @@ 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 {
|
|
8
|
+
import { DeviceError, deviceLogin, startDeviceLogin, waitDeviceLogin } from './gitDevice.mjs';
|
|
9
|
+
import { recall, remember } from './gitKeys.mjs';
|
|
10
|
+
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, refreshAccounts, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
11
|
+
import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
|
|
9
12
|
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
10
13
|
import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
11
14
|
import { LOCALES, errText, t } from './i18n.mjs';
|
|
@@ -80,12 +83,16 @@ export async function gitView(st, lang = langOf(st.userId), { sync = false } = {
|
|
|
80
83
|
if (canManageFiles(st.userId)) {
|
|
81
84
|
rows.push([{ text: t('git.pull', lang), callback_data: 'gt:pull' }, { text: t('git.push', lang), callback_data: 'gt:push' }]);
|
|
82
85
|
rows.push([{ text: t('git.save', lang), callback_data: 'gt:save', style: 'success' }]);
|
|
86
|
+
if (s.branch) rows.push([{ text: t('git.mrBtn', lang), callback_data: 'gt:mr' }]);
|
|
83
87
|
}
|
|
84
88
|
} else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
|
|
85
89
|
else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
|
|
86
90
|
// что изменено и какие есть ветки — можно смотреть без агента и без аккаунта
|
|
87
91
|
rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
|
|
88
92
|
} else lines.push(th('git.noRepo', lang));
|
|
93
|
+
// папку, которая ещё не связана с сервером, можно опубликовать: бот создаст для неё репозиторий
|
|
94
|
+
const publishable = project && !repo?.state.remote ? await canPublish(st, project, { gitOpts }).catch(() => false) : false;
|
|
95
|
+
if (publishable) rows.push([{ text: t('git.pbBtn', lang), callback_data: 'gt:pb' }]);
|
|
89
96
|
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
97
|
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
91
98
|
for (const h of hosts) {
|
|
@@ -111,14 +118,41 @@ function hostsView(lang, note = '') {
|
|
|
111
118
|
return { text: `${note ? `${note}\n\n` : ''}${th('git.hosts.head', lang)}\n\n${list}`, markup: { inline_keyboard: rows } };
|
|
112
119
|
}
|
|
113
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Перед любой операцией /git: обновить входы, которым пора (вход по коду с истекающим токеном). Если сервис больше
|
|
123
|
+
* не принимает вход, аккаунт отключён — пользователю об этом сообщение.
|
|
124
|
+
*/
|
|
125
|
+
async function freshen(st) {
|
|
126
|
+
const lost = await refreshAccounts(st.userId).catch((e) => (log('git: обновление входа:', e.message), []));
|
|
127
|
+
for (const x of lost) await say(st.to, t('git.dv.lost', langOf(st.userId), { host: x.host.label, login: x.login }));
|
|
128
|
+
}
|
|
129
|
+
|
|
114
130
|
/** /git */
|
|
115
131
|
export async function handleGit(st) {
|
|
116
132
|
const lang = langOf(st.userId);
|
|
117
133
|
if (!gitAvailable()) return say(st.to, t('git.none', lang));
|
|
134
|
+
await freshen(st);
|
|
118
135
|
const v = await gitView(st, lang, { sync: true });
|
|
119
136
|
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
|
|
120
137
|
}
|
|
121
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Агент попросил отправить или получить изменения (метки [[git:push]] / [[git:pull]] в ответе): под ответом —
|
|
141
|
+
* сообщение с кнопкой. Нажатие выполняет ту же операцию, что и кнопка на экране /git. Проект не связан с сервером
|
|
142
|
+
* или аккаунт не подключён — подсказка открыть /git.
|
|
143
|
+
* @param {('push'|'pull')[]} actions
|
|
144
|
+
*/
|
|
145
|
+
export async function offerGitActions(st, actions) {
|
|
146
|
+
if (!gitAvailable() || !actions.length) return;
|
|
147
|
+
await freshen(st);
|
|
148
|
+
const lang = langOf(st.userId);
|
|
149
|
+
const project = projectOf(st);
|
|
150
|
+
const repo = project ? await repoOf(st, project).catch(() => null) : null;
|
|
151
|
+
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' }]] } });
|
|
152
|
+
const row = actions.map((a) => ({ text: t(a === 'push' ? 'git.push' : 'git.pull', lang), callback_data: a === 'push' ? 'gt:push' : 'gt:pull' }));
|
|
153
|
+
return say(st.to, t(actions.length > 1 ? 'git.offer.both' : `git.offer.${actions[0]}`, lang), { reply_markup: { inline_keyboard: [row] } });
|
|
154
|
+
}
|
|
155
|
+
|
|
122
156
|
/** Текст ошибки git или сервиса для пользователя. */
|
|
123
157
|
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
124
158
|
|
|
@@ -129,12 +163,12 @@ function cloneBase(st) {
|
|
|
129
163
|
return insideRoot(navStart(st.project, root), root) ?? (root ? insideRoot(root, root) : null);
|
|
130
164
|
}
|
|
131
165
|
|
|
132
|
-
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k
|
|
166
|
+
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<ключ кнопки> (gitKeys). */
|
|
133
167
|
async function reposView(st, host, account, { page = 0, search = '' } = {}, lang) {
|
|
134
168
|
const { items, more } = await listRepos(host, account.token, { page, search });
|
|
135
|
-
st.gitRepos = { host: host.id,
|
|
169
|
+
st.gitRepos = { host: host.id, page, search }; // для перелистывания с тем же поиском
|
|
136
170
|
const base = cloneBase(st);
|
|
137
|
-
const rows = items.map((r
|
|
171
|
+
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
172
|
const nav = [];
|
|
139
173
|
if (page > 0) nav.push({ text: '◀', callback_data: `gt:r:${host.id}:${page - 1}` });
|
|
140
174
|
if (more) nav.push({ text: '▶', callback_data: `gt:r:${host.id}:${page + 1}` });
|
|
@@ -221,6 +255,66 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
|
221
255
|
}
|
|
222
256
|
}
|
|
223
257
|
|
|
258
|
+
/** Сохраняет подключённый аккаунт и сообщает об этом: кто подключён, срок токена, чего не хватает; затем — экран /git. */
|
|
259
|
+
async function finishConnect(st, host, grant, profile, lang, send, key) {
|
|
260
|
+
// вход по коду с токеном, который истекает и не обновляется, через пару часов перестал бы работать — не подключаем
|
|
261
|
+
if (grant.expiresIn && !grant.refreshToken) {
|
|
262
|
+
log('⚠️ git: вход по коду без токена обновления — аккаунт не подключён:', st.userId, host.id, `| срок ${grant.expiresIn} с`);
|
|
263
|
+
return send({ text: th('git.dv.noRefresh', lang, { host: host.label }) });
|
|
264
|
+
}
|
|
265
|
+
const accessUntil = grant.expiresIn ? new Date(Date.now() + grant.expiresIn * 1000).toISOString() : null;
|
|
266
|
+
// срок, который сервис сообщает о продлеваемом входе, — это срок текущего токена, а не аккаунта: напоминать о нём незачем
|
|
267
|
+
const expiresAt = grant.refreshToken ? null : profile.expiresAt;
|
|
268
|
+
if (!db.saveGitAccount(st.userId, { host: host.id, login: profile.login, name: profile.name, email: profile.email, token: grant.token, expiresAt, refreshToken: grant.refreshToken ?? null, accessUntil })) {
|
|
269
|
+
return send({ text: th('access.saveFail', lang) });
|
|
270
|
+
}
|
|
271
|
+
log('аккаунт git подключён:', st.userId, host.id, profile.login, grant.refreshToken ? `| вход обновляемый, срок токена ${grant.expiresIn} с` : '');
|
|
272
|
+
const lack = missingScopes(host, profile.scopes);
|
|
273
|
+
const parts = [
|
|
274
|
+
th(key, lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
275
|
+
...(expiresAt ? [th('git.expires', lang, { date: dateOf(expiresAt, lang) })] : []),
|
|
276
|
+
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
277
|
+
];
|
|
278
|
+
await send({ text: parts.join('\n') });
|
|
279
|
+
return send(await gitView(st, lang));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Вход по ссылке и коду: бот показывает страницу сервиса и код, а сам ждёт подтверждения и подключает аккаунт.
|
|
284
|
+
* Ожидание идёт в фоне (до срока кода); «Отмена» или новый вход прекращают его.
|
|
285
|
+
*/
|
|
286
|
+
async function startCodeLogin(st, host, cfg, lang, edit) {
|
|
287
|
+
let login;
|
|
288
|
+
try {
|
|
289
|
+
login = await startDeviceLogin(cfg);
|
|
290
|
+
} catch (e) {
|
|
291
|
+
log('git: вход по коду:', e.message, '| пользователь', st.userId);
|
|
292
|
+
return edit({ text: th('git.dv.fail', lang, { msg: e.message }) });
|
|
293
|
+
}
|
|
294
|
+
const attempt = { host: host.id };
|
|
295
|
+
st.gitDevice = attempt; // новый вход или «Отмена» заменяют запись — прежнее ожидание это видит и прекращается
|
|
296
|
+
await edit({
|
|
297
|
+
text: th('git.dv.how', lang, { host: host.label, url: login.url, code: hCode(login.userCode), min: Math.round(login.expiresIn / 60) }),
|
|
298
|
+
markup: { inline_keyboard: [[{ text: t('git.dv.open', lang, { host: host.label }), url: login.url }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] },
|
|
299
|
+
});
|
|
300
|
+
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
301
|
+
// не ждём здесь: обработка нажатия заканчивается сразу, подтверждение придёт позже
|
|
302
|
+
waitDeviceLogin(cfg, login, { cancelled: () => st.gitDevice !== attempt })
|
|
303
|
+
.then(async (grant) => {
|
|
304
|
+
st.gitDevice = null;
|
|
305
|
+
const profile = await fetchProfile(host, grant.token);
|
|
306
|
+
await edit({ text: th('git.dv.ok', lang, { host: host.label }) });
|
|
307
|
+
await finishConnect(st, host, grant, profile, lang, send, 'git.connectedCode');
|
|
308
|
+
})
|
|
309
|
+
.catch((e) => {
|
|
310
|
+
if (st.gitDevice === attempt) st.gitDevice = null;
|
|
311
|
+
if (e instanceof DeviceError && e.code === 'cancelled') return null;
|
|
312
|
+
log('git: вход по коду:', e.code ?? '', e.message, '| пользователь', st.userId);
|
|
313
|
+
const key = e instanceof DeviceError && e.code === 'expired' ? 'git.dv.expired' : e instanceof DeviceError && e.code === 'denied' ? 'git.dv.denied' : 'git.dv.fail';
|
|
314
|
+
return edit({ text: th(key, lang, { msg: e.message }) });
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
224
318
|
/** Кнопки /git (gt:<действие>[:<аргумент>[:<страница>]]). */
|
|
225
319
|
export async function onGitCallback(st, cb) {
|
|
226
320
|
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
@@ -230,8 +324,10 @@ export async function onGitCallback(st, cb) {
|
|
|
230
324
|
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
231
325
|
const edit = (v) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => /not modified/i.test(e.message) || log('git:', e.message));
|
|
232
326
|
if (!gitAvailable()) return ack(t('git.none', lang));
|
|
327
|
+
await freshen(st);
|
|
233
328
|
if (action === 'x') {
|
|
234
329
|
st.pendingInput = null;
|
|
330
|
+
st.gitDevice = null; // и ожидание входа по коду, если оно шло
|
|
235
331
|
await ack();
|
|
236
332
|
return edit({ text: th('files.cancelled', lang) });
|
|
237
333
|
}
|
|
@@ -266,6 +362,8 @@ export async function onGitCallback(st, cb) {
|
|
|
266
362
|
}
|
|
267
363
|
// экраны «Изменения» и «Ветки» — gitRepoUi
|
|
268
364
|
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
|
|
365
|
+
// «Опубликовать проект» и «Запрос на слияние» — gitPublishUi
|
|
366
|
+
if (PUBLISH_ACTIONS.includes(action)) return onPublishCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
|
|
269
367
|
const host = findHost(arg);
|
|
270
368
|
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
271
369
|
try {
|
|
@@ -273,7 +371,18 @@ export async function onGitCallback(st, cb) {
|
|
|
273
371
|
if (action === 'c' && host) {
|
|
274
372
|
await ack();
|
|
275
373
|
st.pendingInput = { kind: 'gitToken', host: host.id, at: Date.now() };
|
|
276
|
-
|
|
374
|
+
// у сервиса с входом по коду токен не обязателен: кнопка «Войти без токена» (сам токен тоже можно прислать)
|
|
375
|
+
const byCode = deviceLogin(host);
|
|
376
|
+
const text = th('git.tokenAsk', lang, { host: host.label, url: host.tokenUrl, scopes: hCode(host.scopes) }) + (byCode ? `\n\n${th('git.dv.or', lang)}` : '');
|
|
377
|
+
const rows = [...(byCode ? [[{ text: t('git.dv.btn', lang), callback_data: `gt:dv:${host.id}`, style: 'success' }]] : []), [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]];
|
|
378
|
+
return say(st.to, text, { ...HTML, reply_markup: { inline_keyboard: rows } });
|
|
379
|
+
}
|
|
380
|
+
if (action === 'dv' && host) {
|
|
381
|
+
const cfg = deviceLogin(host);
|
|
382
|
+
if (!cfg) return ack(t('proj.stale', lang));
|
|
383
|
+
await ack();
|
|
384
|
+
st.pendingInput = null; // токен больше не ждём: вход идёт по коду
|
|
385
|
+
return startCodeLogin(st, host, cfg, lang, edit);
|
|
277
386
|
}
|
|
278
387
|
if ((action === 'a' || action === 'd') && account) {
|
|
279
388
|
await ack();
|
|
@@ -309,9 +418,9 @@ export async function onGitCallback(st, cb) {
|
|
|
309
418
|
return say(st.to, t('git.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
310
419
|
}
|
|
311
420
|
if (action === 'k') {
|
|
312
|
-
const
|
|
313
|
-
const repo =
|
|
314
|
-
const h = findHost(
|
|
421
|
+
const chosen = recall(st, arg);
|
|
422
|
+
const repo = chosen?.repo;
|
|
423
|
+
const h = findHost(chosen?.host);
|
|
315
424
|
const acc = h ? db.getGitAccount(st.userId, h.id) : null;
|
|
316
425
|
if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
|
|
317
426
|
if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
|
|
@@ -359,8 +468,9 @@ const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_i
|
|
|
359
468
|
*/
|
|
360
469
|
export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
361
470
|
const wait = st.pendingInput;
|
|
362
|
-
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch'].includes(wait?.kind)) return false;
|
|
471
|
+
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch', ...PUBLISH_INPUTS].includes(wait?.kind)) return false;
|
|
363
472
|
const lang = langOf(st.userId);
|
|
473
|
+
await freshen(st);
|
|
364
474
|
const expired = now - wait.at > GIT_WAIT_MS;
|
|
365
475
|
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
366
476
|
|
|
@@ -378,28 +488,18 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
378
488
|
profile = await fetchProfile(host, token);
|
|
379
489
|
} catch (e) {
|
|
380
490
|
log('git: проверка токена:', e.message, '| пользователь', st.userId);
|
|
381
|
-
const textFail = e instanceof HostError && e.code
|
|
491
|
+
const textFail = e instanceof HostError && ['auth', 'forbidden'].includes(e.code) ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
|
|
382
492
|
return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
|
|
383
493
|
}
|
|
384
494
|
st.pendingInput = null;
|
|
385
|
-
|
|
386
|
-
return (await say(st.to, t('access.saveFail', lang)), true);
|
|
387
|
-
}
|
|
388
|
-
log('аккаунт git подключён:', st.userId, host.id, profile.login);
|
|
389
|
-
const lack = missingScopes(host, profile.scopes);
|
|
390
|
-
const parts = [
|
|
391
|
-
th('git.connected', lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
392
|
-
...(profile.expiresAt ? [th('git.expires', lang, { date: dateOf(profile.expiresAt, lang) })] : []),
|
|
393
|
-
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
394
|
-
];
|
|
395
|
-
await send({ text: parts.join('\n') });
|
|
396
|
-
await send(await gitView(st, lang));
|
|
495
|
+
await finishConnect(st, host, { token }, profile, lang, send, 'git.connected');
|
|
397
496
|
return true;
|
|
398
497
|
}
|
|
399
498
|
|
|
400
499
|
st.pendingInput = null;
|
|
401
500
|
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
402
501
|
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
|
|
502
|
+
if (PUBLISH_INPUTS.includes(wait.kind)) return onPublishInput(st, text, { wait, now, lang, send, project: projectOf(st), repoOf, gitOpts, view: () => gitView(st, lang) });
|
|
403
503
|
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
404
504
|
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
405
505
|
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
|
|
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,64 @@ 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 із новим токеном." },
|
|
432
|
+
'git.dv.or': { en: "Or sign in without a token — with the button below.", ru: "Или войдите без токена — кнопкой ниже.", uk: "Або увійдіть без токена — кнопкою нижче." },
|
|
433
|
+
'git.dv.btn': { en: "🔗 Sign in without a token", ru: "🔗 Войти без токена", uk: "🔗 Увійти без токена" },
|
|
434
|
+
'git.dv.how': { en: "🔗 Signing in to {host} without a token\n\n1. Open {url}\n2. Enter the code: {code}\n3. Confirm access for AcpGram.\n\nThe bot is waiting for the confirmation and will connect the account by itself. The code is valid for {min} min.", ru: "🔗 Вход в {host} без токена\n\n1. Откройте {url}\n2. Введите код: {code}\n3. Подтвердите доступ для AcpGram.\n\nБот ждёт подтверждения и подключит аккаунт сам. Код действует {min} мин.", uk: "🔗 Вхід у {host} без токена\n\n1. Відкрийте {url}\n2. Введіть код: {code}\n3. Підтвердьте доступ для AcpGram.\n\nБот чекає підтвердження й підключить акаунт сам. Код дійсний {min} хв." },
|
|
435
|
+
'git.dv.open': { en: "🔗 Open {host}", ru: "🔗 Открыть {host}", uk: "🔗 Відкрити {host}" },
|
|
436
|
+
'git.dv.ok': { en: "✅ Access to {host} confirmed.", ru: "✅ Доступ к {host} подтверждён.", uk: "✅ Доступ до {host} підтверджено." },
|
|
437
|
+
'git.dv.expired': { en: "⌛ The code has expired — the sign-in was not confirmed. Start again in /git.", ru: "⌛ Код устарел — вход не подтверждён. Начните заново в /git.", uk: "⌛ Код застарів — вхід не підтверджено. Почніть знову в /git." },
|
|
438
|
+
'git.dv.denied': { en: "✖ Access was not confirmed.", ru: "✖ Доступ не подтверждён.", uk: "✖ Доступ не підтверджено." },
|
|
439
|
+
'git.dv.fail': { en: "⚠️ Could not sign in: {msg}", ru: "⚠️ Не удалось войти: {msg}", uk: "⚠️ Не вдалося увійти: {msg}" },
|
|
440
|
+
'git.connectedCode': { en: "✅ {host} connected: {login} ({name}).", ru: "✅ {host} подключён: {login} ({name}).", uk: "✅ {host} підключено: {login} ({name})." },
|
|
441
|
+
'git.dv.noRefresh': { en: "⚠️ {host} gave a sign-in that expires and cannot be renewed, so the account was not connected. Connect it with an access token instead.", ru: "⚠️ {host} выдал вход, который истекает и не продлевается, поэтому аккаунт не подключён. Подключите его токеном доступа.", uk: "⚠️ {host} видав вхід, який спливає й не продовжується, тому акаунт не підключено. Підключіть його токеном доступу." },
|
|
442
|
+
'git.dv.lost': { en: "⚠️ The sign-in to {host} ({login}) is no longer valid, the account was disconnected. Connect it again in /git.", ru: "⚠️ Вход в {host} ({login}) больше не действует, аккаунт отключён. Подключите его заново в /git.", uk: "⚠️ Вхід у {host} ({login}) більше не діє, акаунт відключено. Підключіть його знову в /git." },
|
|
385
443
|
'proj.notFound': { en: '⚠️ The folder was not found or is unavailable', ru: '⚠️ Папка не найдена или недоступна', uk: '⚠️ Папку не знайдено або вона недоступна' },
|
|
386
444
|
'proj.same': { en: '📁 Project already selected: {p}', ru: '📁 Проект уже выбран: {p}', uk: '📁 Проєкт уже обрано: {p}' },
|
|
387
445
|
'proj.set': { en: '📁 Project: {p}\nA new session starts with the next request.', ru: '📁 Проект: {p}\nНовая сессия начнётся со следующего запроса.', uk: '📁 Проєкт: {p}\nНова сесія почнеться з наступного запиту.' },
|
package/src/state.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { canUseEngine, parseJson } from './access.mjs';
|
|
|
6
6
|
import { DEFAULT_ENGINE, ENGINES, createAgent, engineCommand, engineMode, getEngine, modeAllowed, resolveEngine } from './engines.mjs';
|
|
7
7
|
import { HOME, ROOT, insideRoot, isPersonalRoot, pushRecent, samePath, showPath, userRoot } from './projects.mjs';
|
|
8
8
|
import { SANDBOX, agentSandbox } from './sandbox.mjs';
|
|
9
|
-
import { agentGitEnv } from './gitAccess.mjs';
|
|
9
|
+
import { GIT_AGENT_AUTH, agentGitEnv, refreshAccounts } from './gitAccess.mjs';
|
|
10
10
|
|
|
11
11
|
const states = new Map(); // userId -> состояние
|
|
12
12
|
|
|
@@ -337,6 +337,8 @@ async function startAgent(st, { resume } = {}) {
|
|
|
337
337
|
log('⚠️ папка проекта недоступна или вне корня пользователя — агент не запущен | пользователь', st.userId, '| проект', st.project);
|
|
338
338
|
throw new ProjectError(t('state.projectGone', langOf(st.userId)));
|
|
339
339
|
}
|
|
340
|
+
// в режиме «вход у агента» токен должен быть свежим на старте сессии (вход по коду у GitLab живёт 2 часа)
|
|
341
|
+
if (GIT_AGENT_AUTH) await refreshAccounts(st.userId).catch((e) => log('git: обновление входа перед запуском агента:', e.message));
|
|
340
342
|
releaseSessionElsewhere(st, resume);
|
|
341
343
|
reserveSlot(st);
|
|
342
344
|
const engine = engineOf(st);
|
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
|
|
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
|
}
|