acpgram 1.25.0 → 1.27.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 +41 -1
- package/README.ru.md +44 -0
- package/package.json +1 -1
- package/src/bot.mjs +28 -4
- package/src/db.mjs +31 -0
- package/src/engines.mjs +3 -2
- package/src/files.mjs +11 -0
- package/src/filesUi.mjs +293 -0
- package/src/git.mjs +226 -0
- package/src/gitAccess.mjs +112 -0
- package/src/gitHosts.mjs +195 -0
- package/src/gitUi.mjs +438 -0
- package/src/i18n.mjs +115 -0
- package/src/projectFiles.mjs +168 -0
- package/src/projectsUi.mjs +14 -2
- package/src/state.mjs +2 -0
- package/src/turn.mjs +3 -2
- package/src/ui.mjs +3 -1
package/src/filesUi.mjs
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// Команда /files: файлы проекта, которыми пользователь управляет сам, в обход агента — список, создание файла из
|
|
2
|
+
// сообщения, загрузка файла с устройства, удаление. Содержимое таких файлов не попадает в запрос к модели: так в проект
|
|
3
|
+
// кладут секреты (.env, ключи). Обычная отправка файла боту по-прежнему передаёт его агенту.
|
|
4
|
+
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
5
|
+
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
|
+
import { MAX_FILE_BYTES, describeAttachment, safeFileName } from './files.mjs';
|
|
7
|
+
import { LOCALES, errText, t } from './i18n.mjs';
|
|
8
|
+
import { FileError, deleteProjectFile, fmtSize, listProjectDir, projectFileInfo, relPath, resolveTarget, writeProjectFile } from './projectFiles.mjs';
|
|
9
|
+
import { insideRoot, isPersonalRoot, samePath } from './projects.mjs';
|
|
10
|
+
import { folderRows, pathToken, tokenPath } from './projectsUi.mjs';
|
|
11
|
+
import { isAdmin, rootOf, userPath } from './state.mjs';
|
|
12
|
+
import { dest, downloadFile, tg } from './telegram.mjs';
|
|
13
|
+
import { hCode, th } from './ui.mjs';
|
|
14
|
+
|
|
15
|
+
const PAGE = 20;
|
|
16
|
+
const HTML = { parse_mode: 'HTML' };
|
|
17
|
+
/** Сколько бот ждёт имя файла или сам файл; позже сообщения снова уходят агенту. */
|
|
18
|
+
export const FILE_WAIT_MS = 10 * 60_000;
|
|
19
|
+
/** Содержимое файла одним сообщением: длиннее Telegram делит текст на части, и вторая ушла бы агенту. */
|
|
20
|
+
export const INLINE_MAX = 3500;
|
|
21
|
+
/** Сколько после слишком длинного содержимого бот не передаёт текст агенту (части разбитого сообщения). */
|
|
22
|
+
const SWALLOW_MS = 5000;
|
|
23
|
+
/** Альбом из нескольких файлов приходит отдельными сообщениями: все они относятся к одной загрузке. */
|
|
24
|
+
const ALBUM_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Может ли пользователь сам класть и удалять файлы в проекте: администратор — всегда; сотрудник — в личном
|
|
28
|
+
* пространстве, а в общем корне — если его уровень разрешает агенту менять файлы («Обычный», «Полный»).
|
|
29
|
+
*/
|
|
30
|
+
export const canManageFiles = (userId) => isAdmin(userId) || isPersonalRoot(rootOf(userId)) || ['normal', 'full'].includes(db.getUser(userId)?.level);
|
|
31
|
+
|
|
32
|
+
/** Папка проекта диалога, если она доступна (существует и лежит в корне пользователя), иначе null. */
|
|
33
|
+
const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
34
|
+
|
|
35
|
+
/** Путь внутри проекта для показа: «config/.env»; сама папка проекта — «/». */
|
|
36
|
+
const relShow = (project, path) => relative(project, path).split(sep).join('/') || '/';
|
|
37
|
+
|
|
38
|
+
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'fl:x' }]] });
|
|
39
|
+
|
|
40
|
+
/** Текст причины отказа (FileError.code) на языке пользователя. */
|
|
41
|
+
const whyText = (e, lang) => (e instanceof FileError ? t(`files.err.${e.code}`, lang) : errText(e, lang));
|
|
42
|
+
|
|
43
|
+
/** Удаляет сообщение пользователя с содержимым или файлом: в чате не должно оставаться копии секрета. */
|
|
44
|
+
const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch((e) => log('files: сообщение не удалено:', e.message)) : null);
|
|
45
|
+
|
|
46
|
+
/** Экран папки проекта: папки, файлы с размером, «Вверх», «Создать файл» и «Загрузить файл». Текст — HTML. */
|
|
47
|
+
export function filesView(st, project, dir, page = 0, lang = langOf(st.userId)) {
|
|
48
|
+
const { dirs, files } = listProjectDir(project, dir);
|
|
49
|
+
const entries = [...dirs.map((name) => ({ name, dir: true })), ...files];
|
|
50
|
+
const pages = Math.max(1, Math.ceil(entries.length / PAGE));
|
|
51
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
52
|
+
const shown = entries.slice(page * PAGE, (page + 1) * PAGE);
|
|
53
|
+
const rows = [
|
|
54
|
+
...folderRows(shown.filter((e) => e.dir).map((e) => e.name)).map((row) => row.map((n) => ({ text: `📁 ${n}`, callback_data: `fl:o:${pathToken(join(dir, n))}:0` }))),
|
|
55
|
+
...shown.filter((e) => !e.dir).map((f) => [{ text: [...`📄 ${f.name} · ${fmtSize(f.size)}`].slice(0, 60).join(''), callback_data: `fl:f:${pathToken(join(dir, f.name))}` }]),
|
|
56
|
+
];
|
|
57
|
+
if (pages > 1) {
|
|
58
|
+
const nav = [];
|
|
59
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `fl:o:${pathToken(dir)}:${page - 1}` });
|
|
60
|
+
nav.push({ text: `${page + 1}/${pages}`, callback_data: 'nav:n' });
|
|
61
|
+
if (page < pages - 1) nav.push({ text: '▶', callback_data: `fl:o:${pathToken(dir)}:${page + 1}` });
|
|
62
|
+
rows.push(nav);
|
|
63
|
+
}
|
|
64
|
+
if (!samePath(dir, project)) rows.push([{ text: t('proj.up', lang), callback_data: `fl:o:${pathToken(dirname(dir))}:0` }]);
|
|
65
|
+
if (canManageFiles(st.userId)) {
|
|
66
|
+
rows.push([
|
|
67
|
+
{ text: t('files.create', lang), callback_data: `fl:n:${pathToken(dir)}` },
|
|
68
|
+
{ text: t('files.upload', lang), callback_data: `fl:u:${pathToken(dir)}` },
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
const head = th('files.head', lang, { p: hCode(userPath(st.userId, project, lang)), dir: hCode(relShow(project, dir)) });
|
|
72
|
+
const body = entries.length ? th('files.hint', lang) : `<i>${th('files.empty', lang)}</i>\n\n${th('files.hint', lang)}`;
|
|
73
|
+
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** /files — файлы текущего проекта. */
|
|
77
|
+
export async function handleFiles(st) {
|
|
78
|
+
const lang = langOf(st.userId);
|
|
79
|
+
const project = projectOf(st);
|
|
80
|
+
if (!project) return say(st.to, t('state.projectGone', lang));
|
|
81
|
+
const v = filesView(st, project, project, 0, lang);
|
|
82
|
+
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('files:', e.message));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Карточка файла: путь, размер, дата изменения, удаление. */
|
|
86
|
+
function fileCard(st, project, path, lang, { confirm = false } = {}) {
|
|
87
|
+
const info = projectFileInfo(project, path);
|
|
88
|
+
if (!info) return null;
|
|
89
|
+
const when = new Date(info.mtime).toLocaleString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
|
|
90
|
+
const tk = pathToken(path);
|
|
91
|
+
const back = { text: t('files.back', lang), callback_data: `fl:o:${pathToken(dirname(path))}:0` };
|
|
92
|
+
const rows = confirm
|
|
93
|
+
? [[{ text: t('files.deleteYes', lang), callback_data: `fl:D:${tk}` }, { text: t('btn.cancel', lang), callback_data: `fl:f:${tk}` }]]
|
|
94
|
+
: [...(canManageFiles(st.userId) ? [[{ text: t('files.delete', lang), callback_data: `fl:d:${tk}` }]] : []), [back]];
|
|
95
|
+
const text = th(confirm ? 'files.deleteAsk' : 'files.card', lang, { path: hCode(relShow(project, path)), size: fmtSize(info.size), when });
|
|
96
|
+
return { text, markup: { inline_keyboard: rows } };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
let replaceSeq = 0;
|
|
100
|
+
|
|
101
|
+
/** Спрашивает, заменить ли существующий файл; что именно писать — запоминается до ответа (st.replaces). */
|
|
102
|
+
function askReplace(st, project, job, lang) {
|
|
103
|
+
st.replaces ??= new Map();
|
|
104
|
+
if (st.replaces.size > 20) st.replaces.clear();
|
|
105
|
+
const id = ++replaceSeq;
|
|
106
|
+
st.replaces.set(id, job);
|
|
107
|
+
const path = join(job.dir, ...job.parts);
|
|
108
|
+
return say(st.to, th('files.existsAsk', lang, { path: hCode(relShow(project, path)) }), {
|
|
109
|
+
...HTML,
|
|
110
|
+
reply_markup: { inline_keyboard: [[{ text: t('files.replace', lang), callback_data: `fl:r:${id}` }, { text: t('btn.cancel', lang), callback_data: 'fl:x' }]] },
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Просит прислать содержимое файла следующим сообщением. */
|
|
115
|
+
function askContent(st, project, { dir, parts, replace = false }, lang) {
|
|
116
|
+
st.pendingInput = { kind: 'fileContent', dir, parts, replace, at: Date.now() };
|
|
117
|
+
return say(st.to, th('files.contentAsk', lang, { path: hCode(relShow(project, join(dir, ...parts))) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Скачивает присланный файл и кладёт его в проект. */
|
|
121
|
+
async function saveUpload(st, project, { dir, parts, meta, messageId }, lang, { replace = false } = {}) {
|
|
122
|
+
let data;
|
|
123
|
+
try {
|
|
124
|
+
data = await downloadFile(meta.id);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
log('files: скачивание:', e.message, '| пользователь', st.userId);
|
|
127
|
+
return say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang) }));
|
|
128
|
+
}
|
|
129
|
+
if (data.length > MAX_FILE_BYTES) return say(st.to, t('file.tooBig', lang));
|
|
130
|
+
try {
|
|
131
|
+
const r = writeProjectFile(project, dir, parts, data, { replace });
|
|
132
|
+
log('файл загружен в проект:', st.userId, r.path, `${r.size} Б`);
|
|
133
|
+
await dropMessage(st, messageId);
|
|
134
|
+
return say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
log('files: запись:', e.message, '| пользователь', st.userId);
|
|
137
|
+
return say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Кнопки экрана файлов: fl:o (папка), fl:f (файл), fl:d / fl:D (удаление), fl:n (создать), fl:u (загрузить), fl:r (заменить), fl:x (отмена). */
|
|
142
|
+
export async function onFilesCallback(st, cb) {
|
|
143
|
+
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
144
|
+
const lang = langOf(st.userId);
|
|
145
|
+
const chatId = cb.message?.chat?.id ?? st.chatId;
|
|
146
|
+
const messageId = cb.message?.message_id;
|
|
147
|
+
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
148
|
+
const edit = (v) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('files:', e.message));
|
|
149
|
+
|
|
150
|
+
if (action === 'x') {
|
|
151
|
+
st.pendingInput = null;
|
|
152
|
+
st.replaces?.clear();
|
|
153
|
+
await ack();
|
|
154
|
+
return edit({ text: th('files.cancelled', lang) });
|
|
155
|
+
}
|
|
156
|
+
const project = projectOf(st);
|
|
157
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
158
|
+
const manage = canManageFiles(st.userId);
|
|
159
|
+
|
|
160
|
+
if (action === 'r') {
|
|
161
|
+
const job = st.replaces?.get(Number(arg));
|
|
162
|
+
if (!job || !manage) return ack(t('proj.stale', lang));
|
|
163
|
+
st.replaces.delete(Number(arg));
|
|
164
|
+
await ack();
|
|
165
|
+
await edit({ text: th('files.replacing', lang, { path: hCode(relShow(project, join(job.dir, ...job.parts))) }) });
|
|
166
|
+
return job.meta ? saveUpload(st, project, job, lang, { replace: true }) : askContent(st, project, { ...job, replace: true }, lang);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// токены путей общие для всех пользователей: путь из кнопки каждый раз проверяется по проекту нажавшего
|
|
170
|
+
const path = tokenPath(arg);
|
|
171
|
+
if (!path) return ack(t('proj.stale', lang));
|
|
172
|
+
try {
|
|
173
|
+
if (action === 'o') {
|
|
174
|
+
const v = filesView(st, project, path, Number(pageStr) || 0, lang);
|
|
175
|
+
await ack();
|
|
176
|
+
return edit(v);
|
|
177
|
+
}
|
|
178
|
+
if (action === 'f' || action === 'd') {
|
|
179
|
+
const card = fileCard(st, project, path, lang, { confirm: action === 'd' && manage });
|
|
180
|
+
if (!card) return ack(t('files.err.missing', lang));
|
|
181
|
+
await ack();
|
|
182
|
+
return edit(card);
|
|
183
|
+
}
|
|
184
|
+
if (!manage) return ack(t('files.noRights', lang));
|
|
185
|
+
if (action === 'D') {
|
|
186
|
+
deleteProjectFile(project, path);
|
|
187
|
+
log('файл проекта удалён:', st.userId, path);
|
|
188
|
+
await ack(t('files.deleted', lang, { name: basename(path) }));
|
|
189
|
+
return edit(filesView(st, project, dirname(path), 0, lang));
|
|
190
|
+
}
|
|
191
|
+
if (action === 'n' || action === 'u') {
|
|
192
|
+
listProjectDir(project, path); // папка должна быть внутри проекта
|
|
193
|
+
await ack();
|
|
194
|
+
st.pendingInput = { kind: action === 'n' ? 'fileName' : 'fileUpload', dir: path, at: Date.now() };
|
|
195
|
+
return say(st.to, th(action === 'n' ? 'files.nameAsk' : 'files.uploadAsk', lang, { dir: hCode(relShow(project, path)) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
196
|
+
}
|
|
197
|
+
} catch (e) {
|
|
198
|
+
if (!(e instanceof FileError)) log('files:', e.message, '| пользователь', st.userId);
|
|
199
|
+
return ack(whyText(e, lang));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Текст пользователя, пока бот ждёт имя файла или его содержимое. Возвращает true, если текст обработан здесь:
|
|
205
|
+
* агенту он тогда не передаётся. Содержимое не пишется в журнал и базу, а сообщение с ним удаляется из чата.
|
|
206
|
+
* @param {{messageId?: number, now?: number}} [o]
|
|
207
|
+
*/
|
|
208
|
+
export async function onFileInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
209
|
+
const lang = langOf(st.userId);
|
|
210
|
+
// хвост слишком длинного содержимого, разбитого Telegram на несколько сообщений: агенту не передаём
|
|
211
|
+
if (st.swallowUntil && now < st.swallowUntil) {
|
|
212
|
+
await dropMessage(st, messageId);
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
const wait = st.pendingInput;
|
|
216
|
+
if (wait?.kind !== 'fileName' && wait?.kind !== 'fileContent') return false;
|
|
217
|
+
const expired = now - wait.at > FILE_WAIT_MS;
|
|
218
|
+
const project = projectOf(st);
|
|
219
|
+
|
|
220
|
+
if (wait.kind === 'fileContent') {
|
|
221
|
+
// это может быть секрет: что бы ни случилось, агенту текст не уходит, а сообщение удаляется
|
|
222
|
+
st.pendingInput = null;
|
|
223
|
+
await dropMessage(st, messageId);
|
|
224
|
+
if (expired || !project || !canManageFiles(st.userId)) return (await say(st.to, t('files.contentExpired', lang)), true);
|
|
225
|
+
if ([...text].length > INLINE_MAX) {
|
|
226
|
+
st.swallowUntil = now + SWALLOW_MS;
|
|
227
|
+
const markup = { inline_keyboard: [[{ text: t('files.upload', lang), callback_data: `fl:u:${pathToken(wait.dir)}` }]] };
|
|
228
|
+
return (await say(st.to, t('files.contentLong', lang, { max: INLINE_MAX }), { reply_markup: markup }), true);
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const r = writeProjectFile(project, wait.dir, wait.parts, text.endsWith('\n') ? text : `${text}\n`, { replace: wait.replace });
|
|
232
|
+
log('файл создан в проекте:', st.userId, r.path, `${r.size} Б`);
|
|
233
|
+
await say(st.to, th('files.saved', lang, { path: hCode(relShow(project, r.path)), size: fmtSize(r.size) }), HTML);
|
|
234
|
+
} catch (e) {
|
|
235
|
+
log('files: запись:', e.message, '| пользователь', st.userId);
|
|
236
|
+
await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML);
|
|
237
|
+
}
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// имя файла
|
|
242
|
+
if (expired) {
|
|
243
|
+
st.pendingInput = null;
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
if (!project || !canManageFiles(st.userId)) {
|
|
247
|
+
st.pendingInput = null;
|
|
248
|
+
return (await say(st.to, t('state.projectGone', lang)), true);
|
|
249
|
+
}
|
|
250
|
+
const parts = relPath(text);
|
|
251
|
+
if (!parts) return (await say(st.to, t('files.nameBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
252
|
+
let target;
|
|
253
|
+
try {
|
|
254
|
+
target = resolveTarget(project, wait.dir, parts);
|
|
255
|
+
} catch (e) {
|
|
256
|
+
return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), { ...HTML, reply_markup: cancelMarkup(lang) }), true);
|
|
257
|
+
}
|
|
258
|
+
st.pendingInput = null;
|
|
259
|
+
if (target.exists) await askReplace(st, project, { dir: wait.dir, parts }, lang);
|
|
260
|
+
else await askContent(st, project, { dir: wait.dir, parts }, lang);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Файл или фото от пользователя, пока бот ждёт загрузку в проект (кнопка «Загрузить файл»). Возвращает true, если
|
|
266
|
+
* файл сохранён в проект (или отклонён здесь): агенту он тогда не передаётся. Без ожидания — false: файл для агента.
|
|
267
|
+
*/
|
|
268
|
+
export async function onFileUpload(st, msg, now = Date.now()) {
|
|
269
|
+
const wait = st.pendingInput;
|
|
270
|
+
const waiting = wait?.kind === 'fileUpload' && now - wait.at <= FILE_WAIT_MS;
|
|
271
|
+
const album = msg.media_group_id && st.uploadGroup?.id === msg.media_group_id && now < st.uploadGroup.until;
|
|
272
|
+
if (!waiting && !album) return false;
|
|
273
|
+
const dir = waiting ? wait.dir : st.uploadGroup.dir;
|
|
274
|
+
if (waiting) st.pendingInput = null;
|
|
275
|
+
if (msg.media_group_id) st.uploadGroup = { id: msg.media_group_id, dir, until: now + ALBUM_MS };
|
|
276
|
+
const lang = langOf(st.userId);
|
|
277
|
+
const project = projectOf(st);
|
|
278
|
+
if (!project || !canManageFiles(st.userId)) return (await say(st.to, t('state.projectGone', lang)), true);
|
|
279
|
+
const meta = describeAttachment(msg);
|
|
280
|
+
if (!meta) return false;
|
|
281
|
+
if (meta.size > MAX_FILE_BYTES) return (await say(st.to, t('file.tooBig', lang)), true);
|
|
282
|
+
// имя — как у присланного файла (с точкой в начале, если она есть); непригодное заменяется безопасным
|
|
283
|
+
const parts = relPath(basename(String(meta.name).replace(/\\/g, '/'))) ?? relPath(safeFileName(meta.name));
|
|
284
|
+
if (!parts) return (await say(st.to, t('files.nameBad', lang)), true);
|
|
285
|
+
const job = { dir, parts, meta, messageId: msg.message_id };
|
|
286
|
+
try {
|
|
287
|
+
if (resolveTarget(project, dir, parts).exists) return (await askReplace(st, project, job, lang), true);
|
|
288
|
+
} catch (e) {
|
|
289
|
+
return (await say(st.to, th('files.saveFail', lang, { why: whyText(e, lang) }), HTML), true);
|
|
290
|
+
}
|
|
291
|
+
await saveUpload(st, project, job, lang);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
package/src/git.mjs
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// Команды git, которые бот выполняет сам (/git): клонирование, состояние, получение и отправка изменений, коммит.
|
|
2
|
+
// Git — системная программа, не зависимость бота: нет её на сервере — раздел /git не показывается.
|
|
3
|
+
//
|
|
4
|
+
// Безопасность. Репозиторий лежит в папке, куда пишет агент, а настройки и хуки репозитория умеют запускать программы.
|
|
5
|
+
// Поэтому: хуки отключены, общий и системный конфиги не читаются (где это возможно), вход передаётся только через
|
|
6
|
+
// окружение процесса, а при включённой песочнице (AGENT_SANDBOX) git запускается в песочнице того же сотрудника.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { devNull } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { checkCommand, killTree } from './acp.mjs';
|
|
12
|
+
import { agentEnv } from './engines.mjs';
|
|
13
|
+
import { isSecretName } from './files.mjs';
|
|
14
|
+
|
|
15
|
+
const IS_WIN = process.platform === 'win32';
|
|
16
|
+
|
|
17
|
+
/** Команда git: из GIT_COMMAND или из PATH. */
|
|
18
|
+
export const gitCommand = (env = process.env) => env.GIT_COMMAND?.trim() || 'git';
|
|
19
|
+
|
|
20
|
+
let available = false;
|
|
21
|
+
/** Проверка при старте: есть ли git на сервере. */
|
|
22
|
+
export async function checkGit() {
|
|
23
|
+
const r = await checkCommand(gitCommand(), ['--version'], 20_000);
|
|
24
|
+
available = r.ok;
|
|
25
|
+
return r;
|
|
26
|
+
}
|
|
27
|
+
/** Доступен ли git (по проверке при старте). */
|
|
28
|
+
export const gitAvailable = () => available;
|
|
29
|
+
/** Для тестов и повторной проверки. */
|
|
30
|
+
export const setGitAvailable = (on) => {
|
|
31
|
+
available = Boolean(on);
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Настройки git через окружение (GIT_CONFIG_COUNT / KEY_n / VALUE_n): действуют как «-c ключ=значение», но не видны
|
|
36
|
+
* в списке процессов. Добавляются к уже заданным в env.
|
|
37
|
+
* @param {[string, string][]} entries
|
|
38
|
+
*/
|
|
39
|
+
export function configEnv(entries, env = {}) {
|
|
40
|
+
const out = { ...env };
|
|
41
|
+
let n = Number(out.GIT_CONFIG_COUNT) || 0;
|
|
42
|
+
for (const [key, value] of entries) {
|
|
43
|
+
out[`GIT_CONFIG_KEY_${n}`] = key;
|
|
44
|
+
out[`GIT_CONFIG_VALUE_${n}`] = value;
|
|
45
|
+
n++;
|
|
46
|
+
}
|
|
47
|
+
out.GIT_CONFIG_COUNT = String(n);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Настройки безопасного запуска: без хуков, без наблюдателя файлов, без помощников входа и внешних транспортов. */
|
|
52
|
+
export const SAFE_CONFIG = [
|
|
53
|
+
['core.hooksPath', devNull],
|
|
54
|
+
['core.fsmonitor', 'false'],
|
|
55
|
+
['credential.helper', ''],
|
|
56
|
+
['protocol.ext.allow', 'never'],
|
|
57
|
+
['advice.detachedHead', 'false'],
|
|
58
|
+
['core.quotePath', 'false'], // имена файлов не латиницей — как есть, а не восьмеричными кодами
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Окружение процесса git, который запускает бот: без токена бота и ключей API, без вопросов в терминале, с безопасными
|
|
63
|
+
* настройками; identity — автор коммитов {name, email}; auth — настройки входа (gitHosts.authConfig).
|
|
64
|
+
* На Linux и macOS общий и системный конфиги не читаются: в песочнице общий конфиг лежит в папке, куда пишет агент.
|
|
65
|
+
*/
|
|
66
|
+
export function gitEnv({ identity = null, auth = [], base = process.env } = {}) {
|
|
67
|
+
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
68
|
+
if (!IS_WIN) Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' });
|
|
69
|
+
if (identity?.name && identity?.email) {
|
|
70
|
+
Object.assign(env, { GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email, GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
|
|
71
|
+
}
|
|
72
|
+
return configEnv([...SAFE_CONFIG, ...auth], env);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Команда git завершилась с ошибкой: code — код выхода, stderr — её вывод (без секретов). */
|
|
76
|
+
export class GitError extends Error {
|
|
77
|
+
constructor(message, { code = null, stderr = '', timeout = false } = {}) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.code = code;
|
|
80
|
+
this.stderr = stderr;
|
|
81
|
+
this.timeout = timeout;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Запускает git. Без оболочки: аргументы (описание коммита, имена файлов) передаются как есть.
|
|
87
|
+
* @param {string[]} args
|
|
88
|
+
* @param {{cwd: string, env?: object, wrap?: {command: string, args: string[], env: Function}|null, timeoutMs?: number, hide?: string[]}} o
|
|
89
|
+
* wrap — песочница (sandbox.agentSandbox с командой git); hide — строки, которые нужно вычистить из вывода (токены)
|
|
90
|
+
* @returns {Promise<string>} stdout
|
|
91
|
+
*/
|
|
92
|
+
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [] } = {}) {
|
|
93
|
+
const command = wrap ? wrap.command : gitCommand();
|
|
94
|
+
const argv = wrap ? [...wrap.args, ...args] : args;
|
|
95
|
+
const clean = (s) => hide.filter(Boolean).reduce((acc, h) => acc.replaceAll(h, '***'), s);
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
let proc;
|
|
98
|
+
try {
|
|
99
|
+
proc = spawn(command, argv, { cwd, env: wrap ? wrap.env(env) : env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, detached: !IS_WIN });
|
|
100
|
+
} catch (e) {
|
|
101
|
+
return reject(new GitError(e.message));
|
|
102
|
+
}
|
|
103
|
+
let out = '';
|
|
104
|
+
let err = '';
|
|
105
|
+
let timedOut = false;
|
|
106
|
+
const timer = setTimeout(() => {
|
|
107
|
+
timedOut = true;
|
|
108
|
+
killTree(proc, 1000);
|
|
109
|
+
}, timeoutMs);
|
|
110
|
+
proc.stdout.on('data', (d) => (out += d));
|
|
111
|
+
proc.stderr.on('data', (d) => (err += d));
|
|
112
|
+
proc.on('error', (e) => {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
reject(new GitError(e.message));
|
|
115
|
+
});
|
|
116
|
+
proc.on('close', (code) => {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
if (timedOut) return reject(new GitError(`git ${args[0]}: нет ответа за ${Math.round(timeoutMs / 1000)} с`, { timeout: true }));
|
|
119
|
+
if (code !== 0) {
|
|
120
|
+
const stderr = clean(err.trim());
|
|
121
|
+
// подсказки git («hint: …») пользователю не нужны — в сообщение идут последние содержательные строки
|
|
122
|
+
const lines = stderr.split(/\r?\n/).filter((l) => l.trim() && !/^hint:/i.test(l));
|
|
123
|
+
return reject(new GitError(lines.slice(-3).join(' | ') || `git ${args[0]}: код ${code}`, { code, stderr }));
|
|
124
|
+
}
|
|
125
|
+
resolve(clean(out));
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Разбор `git status --porcelain=v2 --branch`.
|
|
132
|
+
* @returns {{branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}}
|
|
133
|
+
*/
|
|
134
|
+
export function parseStatus(text) {
|
|
135
|
+
const st = { branch: null, upstream: null, ahead: 0, behind: 0, changed: 0 };
|
|
136
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
137
|
+
if (line.startsWith('# branch.head ')) st.branch = line.slice(14) === '(detached)' ? null : line.slice(14);
|
|
138
|
+
else if (line.startsWith('# branch.upstream ')) st.upstream = line.slice(18);
|
|
139
|
+
else if (line.startsWith('# branch.ab ')) {
|
|
140
|
+
const m = /\+(\d+) -(\d+)/.exec(line);
|
|
141
|
+
if (m) [st.ahead, st.behind] = [Number(m[1]), Number(m[2])];
|
|
142
|
+
} else if (line && !line.startsWith('#')) st.changed++;
|
|
143
|
+
}
|
|
144
|
+
return st;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Состояние репозитория в папке cwd или null, если это не репозиторий git.
|
|
149
|
+
* @returns {Promise<null | {top: string, remote: string|null, branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}>}
|
|
150
|
+
*/
|
|
151
|
+
export async function repoState(cwd, opts = {}) {
|
|
152
|
+
let top;
|
|
153
|
+
try {
|
|
154
|
+
top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
155
|
+
} catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
// адрес как записан в настройках репозитория (без подстановок url.*.insteadOf): по нему определяется сервис
|
|
159
|
+
const remote = await runGit(['config', '--get', 'remote.origin.url'], { cwd, ...opts }).then((s) => s.trim() || null, () => null);
|
|
160
|
+
const status = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
161
|
+
return { top, remote, ...status };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Клонирует репозиторий url в папку dest (её ещё нет), запускается из её родительской папки cwd. Подмодули не тянутся. */
|
|
165
|
+
export const cloneRepo = (url, dest, { cwd, ...opts }) => runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
|
|
166
|
+
|
|
167
|
+
/** Сверяется с сервером (git fetch): рабочие файлы не трогает, обновляет сведения о ветках сервера. */
|
|
168
|
+
export const fetchRepo = (cwd, opts = {}) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Получает изменения с сервера: fetch и перемотка вперёд, если это возможно без слияния.
|
|
172
|
+
* @returns {Promise<'updated'|'uptodate'|'diverged'|'noupstream'>} diverged — истории разошлись, нужно слияние (его делает агент)
|
|
173
|
+
*/
|
|
174
|
+
export async function pullRepo(cwd, opts = {}) {
|
|
175
|
+
await fetchRepo(cwd, opts);
|
|
176
|
+
const before = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
177
|
+
if (!before.upstream) return 'noupstream';
|
|
178
|
+
if (!before.behind) return 'uptodate';
|
|
179
|
+
if (before.ahead) return 'diverged';
|
|
180
|
+
await runGit(['merge', '--ff-only', '@{u}'], { cwd, ...opts });
|
|
181
|
+
return 'updated';
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Файлы с секретами среди коммитов, которые ещё не отправлены на сервер (по именам: .env, ключи, учётные данные). */
|
|
185
|
+
export async function unpushedSecrets(cwd, opts = {}) {
|
|
186
|
+
const st = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
187
|
+
// без ветки на сервере сравнивать не с чем — смотрим все файлы текущего коммита
|
|
188
|
+
const args = st.upstream ? ['diff', '--name-only', '--diff-filter=AM', '@{u}', 'HEAD'] : ['ls-tree', '-r', '--name-only', 'HEAD'];
|
|
189
|
+
const names = await runGit(args, { cwd, ...opts }).then((s) => s.split(/\r?\n/).filter(Boolean), () => []);
|
|
190
|
+
return names.filter((n) => isSecretName(`/${n}`));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Отправляет текущую ветку на сервер (и связывает её с веткой сервера). */
|
|
194
|
+
export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
|
|
198
|
+
* @returns {Promise<{committed: boolean, skipped: string[], tracked: string[]}>} committed — коммит создан (было что
|
|
199
|
+
* коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы с секретами, которые уже
|
|
200
|
+
* были в репозитории: их изменения в коммит не вошли
|
|
201
|
+
*/
|
|
202
|
+
export async function commitAll(cwd, message, opts = {}) {
|
|
203
|
+
await runGit(['add', '-A'], { cwd, ...opts });
|
|
204
|
+
const staged = (await runGit(['diff', '--cached', '--name-status'], { cwd, ...opts }))
|
|
205
|
+
.split(/\r?\n/)
|
|
206
|
+
.filter(Boolean)
|
|
207
|
+
.map((l) => ({ status: l[0], name: l.split('\t').pop() }));
|
|
208
|
+
const secrets = staged.filter((f) => f.status !== 'D' && isSecretName(`/${f.name}`));
|
|
209
|
+
const skipped = secrets.filter((f) => f.status === 'A').map((f) => f.name);
|
|
210
|
+
const tracked = secrets.filter((f) => f.status !== 'A').map((f) => f.name);
|
|
211
|
+
if (secrets.length) {
|
|
212
|
+
await runGit(['reset', '-q', '--', ...secrets.map((f) => f.name)], { cwd, ...opts });
|
|
213
|
+
if (skipped.length) {
|
|
214
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
215
|
+
const file = join(top, '.gitignore');
|
|
216
|
+
const have = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
217
|
+
const lines = skipped.map((n) => `/${n}`).filter((l) => !have.split(/\r?\n/).includes(l));
|
|
218
|
+
if (lines.length) appendFileSync(file, `${have && !have.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n`);
|
|
219
|
+
await runGit(['add', '--', '.gitignore'], { cwd: top, ...opts });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const left = (await runGit(['diff', '--cached', '--name-only'], { cwd, ...opts })).trim();
|
|
223
|
+
if (!left) return { committed: false, skipped, tracked };
|
|
224
|
+
await runGit(['commit', '-q', '-m', message], { cwd, ...opts });
|
|
225
|
+
return { committed: true, skipped, tracked };
|
|
226
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Аккаунты Git пользователей и то, что из них получает агент.
|
|
2
|
+
//
|
|
3
|
+
// Токен доступа хранится в базе бота и по умолчанию агенту не передаётся: клонирование, получение и отправку делает
|
|
4
|
+
// бот по кнопкам в /git, а агент работает с репозиторием локально. Администратор может выбрать другой режим —
|
|
5
|
+
// GIT_AGENT_AUTH=1: тогда вход передаётся и процессу агента (через его окружение), и агент сам тянет и отправляет
|
|
6
|
+
// изменения. Это удобнее, но токен становится виден агенту, а значит может попасть в запрос к модели.
|
|
7
|
+
import { db } from './ctx.mjs';
|
|
8
|
+
import { configEnv, gitAvailable } from './git.mjs';
|
|
9
|
+
import { authConfig, customHost, gitHosts, hostById, hostOfUrl } from './gitHosts.mjs';
|
|
10
|
+
|
|
11
|
+
/** Режим «вход у агента»: токены пользователя передаются процессу его агента. По умолчанию выключен. */
|
|
12
|
+
export const GIT_AGENT_AUTH = process.env.GIT_AGENT_AUTH?.trim() === '1';
|
|
13
|
+
|
|
14
|
+
// ---- свои серверы (GitLab, GitHub Enterprise), добавленные администратором в /git ----
|
|
15
|
+
|
|
16
|
+
const HOSTS_KEY = 'git:hosts';
|
|
17
|
+
|
|
18
|
+
/** Свои серверы, добавленные администратором: [{kind, url, name}]. */
|
|
19
|
+
export function customHosts() {
|
|
20
|
+
try {
|
|
21
|
+
const list = JSON.parse(db.getSetting(HOSTS_KEY) || '[]');
|
|
22
|
+
return Array.isArray(list) ? list.filter((x) => x && typeof x.url === 'string') : [];
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Все сервисы этой установки: GitHub, GitLab.com, серверы из настроек и добавленные администратором. */
|
|
29
|
+
export const hosts = () => gitHosts(process.env, customHosts());
|
|
30
|
+
/** Сервис по id или null. */
|
|
31
|
+
export const findHost = (id) => hostById(id, hosts());
|
|
32
|
+
/** Сервис, которому принадлежит адрес репозитория, или null. */
|
|
33
|
+
export const hostFor = (url) => hostOfUrl(url, hosts());
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Добавляет свой сервер. @returns {{host: object} | {error: 'bad'|'exists'}} bad — адрес не подходит (нужен https,
|
|
37
|
+
* не github.com и не gitlab.com), exists — такой сервер уже есть.
|
|
38
|
+
*/
|
|
39
|
+
export function addCustomHost(kind, url, name = '') {
|
|
40
|
+
const host = customHost(kind, url, name);
|
|
41
|
+
if (!host) return { error: 'bad' };
|
|
42
|
+
if (hosts().some((h) => h.web === host.web)) return { error: 'exists' };
|
|
43
|
+
db.setSetting(HOSTS_KEY, JSON.stringify([...customHosts(), { kind, url: host.web, name: String(name ?? '').trim() }]));
|
|
44
|
+
return { host };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Меняет название своего сервера (для кнопок). Возвращает false, если сервера нет или он задан в настройках. */
|
|
48
|
+
export function renameCustomHost(id, name) {
|
|
49
|
+
const list = customHosts();
|
|
50
|
+
const i = list.findIndex((x) => customHost(x.kind, x.url)?.id === id);
|
|
51
|
+
if (i < 0) return false;
|
|
52
|
+
list[i] = { ...list[i], name: String(name ?? '').trim().slice(0, 40) };
|
|
53
|
+
db.setSetting(HOSTS_KEY, JSON.stringify(list));
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Убирает свой сервер вместе с подключёнными к нему аккаунтами всех пользователей (их токены удаляются).
|
|
59
|
+
* @returns {number|null} сколько аккаунтов удалено; null — сервера нет или он задан в настройках
|
|
60
|
+
*/
|
|
61
|
+
export function removeCustomHost(id) {
|
|
62
|
+
const list = customHosts();
|
|
63
|
+
const rest = list.filter((x) => customHost(x.kind, x.url)?.id !== id);
|
|
64
|
+
if (rest.length === list.length) return null;
|
|
65
|
+
db.setSetting(HOSTS_KEY, JSON.stringify(rest));
|
|
66
|
+
return db.deleteGitAccountsByHost(id);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Подключённые аккаунты пользователя вместе с их сервисами: [{host, account}] (аккаунты убранных сервисов пропускаются). */
|
|
70
|
+
export function accountsOf(userId, list = hosts()) {
|
|
71
|
+
return db.listGitAccounts(userId).map((account) => ({ host: hostById(account.host, list), account })).filter((x) => x.host);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Автор коммитов по аккаунту: {name, email}. */
|
|
75
|
+
export const identityOf = (account) => (account ? { name: account.name || account.login, email: account.email } : null);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Переменные окружения процесса агента: автор коммитов (чтобы коммиты агента были от имени пользователя) и, в режиме
|
|
79
|
+
* GIT_AGENT_AUTH, вход в сервисы. Без подключённых аккаунтов — пусто: агент работает с git как раньше.
|
|
80
|
+
*/
|
|
81
|
+
export function agentGitEnv(userId, { agentAuth = GIT_AGENT_AUTH, base = process.env } = {}) {
|
|
82
|
+
const list = accountsOf(userId);
|
|
83
|
+
if (!list.length) return {};
|
|
84
|
+
const who = identityOf(list[0].account);
|
|
85
|
+
// Автор — настройкой git (user.name / user.email), а не переменными GIT_AUTHOR_*: она действует как значение по
|
|
86
|
+
// умолчанию и уступает явному выбору автора (ключ -c, переменные GIT_AUTHOR_*), которым пользуются скрипты коммитов.
|
|
87
|
+
const entries = [['user.name', who.name], ['user.email', who.email]];
|
|
88
|
+
if (agentAuth) entries.push(...list.flatMap(({ host, account }) => authConfig(host, account.token)));
|
|
89
|
+
// нумерация продолжает настройки, уже заданные в окружении бота: они тоже достаются агенту
|
|
90
|
+
const env = configEnv(entries, base.GIT_CONFIG_COUNT ? { GIT_CONFIG_COUNT: base.GIT_CONFIG_COUNT } : {});
|
|
91
|
+
return agentAuth ? { ...env, GIT_TERMINAL_PROMPT: '0' } : env;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Подсказка агенту о git (служебный текст — на английском). Без входа: не пытаться получать и отправлять, а направлять
|
|
96
|
+
* пользователя в /git. Со входом (GIT_AGENT_AUTH): работать можно, показывать вход нельзя. Нет git на сервере — null.
|
|
97
|
+
*/
|
|
98
|
+
export function gitNote(userId, { agentAuth = GIT_AGENT_AUTH } = {}) {
|
|
99
|
+
if (!gitAvailable()) return null;
|
|
100
|
+
const connected = db.listGitAccounts(userId).length > 0;
|
|
101
|
+
if (agentAuth && connected) {
|
|
102
|
+
return (
|
|
103
|
+
'[AcpGram] Git: the user\'s sign-in for their Git hosting is provided to git through your environment, so fetch, pull and push work. ' +
|
|
104
|
+
'Never print, echo or store these credentials (do not show `env` or `git config --list` output). Never commit files with secrets (.env, keys).'
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return (
|
|
108
|
+
'[AcpGram] Git: use git locally as usual (status, diff, add, commit, branches, merge). You have no credentials for the remote: ' +
|
|
109
|
+
'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).'
|
|
111
|
+
);
|
|
112
|
+
}
|