acpgram 1.31.7 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -3
- package/README.ru.md +10 -3
- package/package.json +1 -1
- package/src/access.mjs +9 -0
- package/src/bot.mjs +81 -24
- package/src/cli-i18n.mjs +19 -6
- package/src/clip.mjs +15 -0
- package/src/ctx.mjs +6 -0
- package/src/db.mjs +41 -3
- package/src/engines.mjs +14 -3
- package/src/filesUi.mjs +5 -4
- package/src/forceStop.mjs +18 -0
- package/src/git.mjs +50 -5
- package/src/gitCtx.mjs +68 -0
- package/src/gitInspect.mjs +7 -2
- package/src/gitPublishUi.mjs +25 -28
- package/src/gitRepoUi.mjs +43 -33
- package/src/gitUi.mjs +49 -58
- package/src/i18n.mjs +10 -0
- package/src/log.mjs +27 -2
- package/src/pending.mjs +62 -0
- package/src/projectFiles.mjs +10 -4
- package/src/protect.mjs +18 -0
- package/src/queue.mjs +42 -0
- package/src/quota.mjs +40 -0
- package/src/safety.mjs +20 -0
- package/src/sandbox.mjs +16 -1
- package/src/setup.mjs +14 -0
- package/src/state.mjs +28 -8
- package/src/turn.mjs +26 -4
- package/src/warnings.mjs +38 -0
package/src/engines.mjs
CHANGED
|
@@ -124,6 +124,8 @@ export const PROVIDER_KEYS = new Set([...GOOGLE_KEYS, 'ANTHROPIC_API_KEY', 'OPEN
|
|
|
124
124
|
|
|
125
125
|
/** Переменные самого бота: процессу агента не нужны, а токен даёт полный контроль над ботом. */
|
|
126
126
|
const BOT_ONLY_ENV = new Set(['TELEGRAM_BOT_TOKEN', 'ALLOWED_USER_ID', 'ALLOWED_USERNAME']);
|
|
127
|
+
const SECRET_ENV = /(?:^|_)(TOKEN|SECRET|PASSWORD|PWD|PAT|KEY)$/i;
|
|
128
|
+
const envList = (value) => new Set(String(value ?? '').split(/[,\s]+/).map((s) => s.trim().toUpperCase()).filter(Boolean));
|
|
127
129
|
|
|
128
130
|
/**
|
|
129
131
|
* Окружение процесса агента: окружение бота без переменных самого бота (BOT_ONLY_ENV) и без ключей API чужих
|
|
@@ -134,11 +136,15 @@ const BOT_ONLY_ENV = new Set(['TELEGRAM_BOT_TOKEN', 'ALLOWED_USER_ID', 'ALLOWED_
|
|
|
134
136
|
*/
|
|
135
137
|
export function agentEnv(engine, env = process.env) {
|
|
136
138
|
const own = engine.apiKeys ? new Set(engine.apiKeys) : null;
|
|
139
|
+
const hide = envList(env.AGENT_ENV_HIDE);
|
|
140
|
+
const pass = envList(env.AGENT_ENV_PASS);
|
|
137
141
|
const out = {};
|
|
138
142
|
for (const [name, value] of Object.entries(env)) {
|
|
139
143
|
const key = name.toUpperCase();
|
|
140
|
-
if (BOT_ONLY_ENV.has(key)) continue;
|
|
141
|
-
|
|
144
|
+
if (BOT_ONLY_ENV.has(key) || hide.has(key) || key === 'AGENT_ENV_HIDE' || key === 'AGENT_ENV_PASS') continue;
|
|
145
|
+
const provider = PROVIDER_KEYS.has(key);
|
|
146
|
+
if (provider && own && !own.has(key)) continue;
|
|
147
|
+
if (!provider && !pass.has(key) && SECRET_ENV.test(key)) continue;
|
|
142
148
|
out[name] = value;
|
|
143
149
|
}
|
|
144
150
|
return out;
|
|
@@ -470,6 +476,11 @@ export function selectionRequest(engine, sessionId, kind, value) {
|
|
|
470
476
|
return ['session/set_config_option', { sessionId, configId: kind === 'model' ? 'model' : engine.effortConfig, value }];
|
|
471
477
|
}
|
|
472
478
|
|
|
479
|
+
export function actualModelFromUpdate(update) {
|
|
480
|
+
const meta = update?._meta;
|
|
481
|
+
return meta?.['_claude/model'] || (Array.isArray(meta?.quota?.model_usage) && meta.quota.model_usage[0]?.model) || null;
|
|
482
|
+
}
|
|
483
|
+
|
|
473
484
|
/**
|
|
474
485
|
* Расход запроса из ответа session/prompt и последнего usage_update.
|
|
475
486
|
* Реальная модель: _meta.quota.model_usage (Gemini CLI, Claude Code) или _meta._claude/model.
|
|
@@ -480,7 +491,7 @@ export function parseUsage(res, usageUpdate) {
|
|
|
480
491
|
const num = (v) => (Number.isFinite(v) ? v : null);
|
|
481
492
|
const usageModels = res?._meta?.quota?.model_usage;
|
|
482
493
|
// у Claude Code в model_usage бывают и модели субагентов — основная модель сессии в _claude/model
|
|
483
|
-
const model = usageUpdate
|
|
494
|
+
const model = actualModelFromUpdate(usageUpdate) || (Array.isArray(usageModels) && usageModels[0]?.model) || null;
|
|
484
495
|
const cost = usageUpdate?.cost;
|
|
485
496
|
return {
|
|
486
497
|
model,
|
package/src/filesUi.mjs
CHANGED
|
@@ -45,7 +45,7 @@ const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_i
|
|
|
45
45
|
|
|
46
46
|
/** Экран папки проекта: папки, файлы с размером, «Вверх», «Создать файл» и «Загрузить файл». Текст — HTML. */
|
|
47
47
|
export function filesView(st, project, dir, page = 0, lang = langOf(st.userId)) {
|
|
48
|
-
const { dirs, files } = listProjectDir(project, dir);
|
|
48
|
+
const { dirs, files } = listProjectDir(project, dir, { hideConfig: !canManageFiles(st.userId) });
|
|
49
49
|
const entries = [...dirs.map((name) => ({ name, dir: true })), ...files];
|
|
50
50
|
const pages = Math.max(1, Math.ceil(entries.length / PAGE));
|
|
51
51
|
page = Math.min(Math.max(page, 0), pages - 1);
|
|
@@ -189,7 +189,7 @@ export async function onFilesCallback(st, cb) {
|
|
|
189
189
|
return edit(filesView(st, project, dirname(path), 0, lang));
|
|
190
190
|
}
|
|
191
191
|
if (action === 'n' || action === 'u') {
|
|
192
|
-
listProjectDir(project, path); // папка должна быть внутри проекта
|
|
192
|
+
listProjectDir(project, path, { hideConfig: !canManageFiles(st.userId) }); // папка должна быть внутри проекта
|
|
193
193
|
await ack();
|
|
194
194
|
st.pendingInput = { kind: action === 'n' ? 'fileName' : 'fileUpload', dir: path, at: Date.now() };
|
|
195
195
|
return say(st.to, th(action === 'n' ? 'files.nameAsk' : 'files.uploadAsk', lang, { dir: hCode(relShow(project, path)) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
@@ -249,7 +249,7 @@ export async function onFileInput(st, text, { messageId, now = Date.now() } = {}
|
|
|
249
249
|
st.pendingInput = null;
|
|
250
250
|
return (await say(st.to, t('state.projectGone', lang)), true);
|
|
251
251
|
}
|
|
252
|
-
const parts = relPath(text);
|
|
252
|
+
const parts = relPath(text, { hideConfig: !canManageFiles(st.userId) });
|
|
253
253
|
if (!parts) return (await say(st.to, t('files.nameBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
254
254
|
let target;
|
|
255
255
|
try {
|
|
@@ -282,7 +282,8 @@ export async function onFileUpload(st, msg, now = Date.now()) {
|
|
|
282
282
|
if (!meta) return false;
|
|
283
283
|
if (meta.size > MAX_FILE_BYTES) return (await say(st.to, t('file.tooBig', lang)), true);
|
|
284
284
|
// имя — как у присланного файла (с точкой в начале, если она есть); непригодное заменяется безопасным
|
|
285
|
-
const
|
|
285
|
+
const opts = { hideConfig: !canManageFiles(st.userId) };
|
|
286
|
+
const parts = relPath(basename(String(meta.name).replace(/\\/g, '/')), opts) ?? relPath(safeFileName(meta.name), opts);
|
|
286
287
|
if (!parts) return (await say(st.to, t('files.nameBad', lang)), true);
|
|
287
288
|
const job = { dir, parts, meta, messageId: msg.message_id };
|
|
288
289
|
try {
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function clearStopTimer(st, { clearTimer = clearTimeout } = {}) {
|
|
2
|
+
if (!st) return;
|
|
3
|
+
if (st.stopTimer) clearTimer(st.stopTimer);
|
|
4
|
+
st.stopTimer = null;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function forceStopAfter(st, { ms = 5000, setTimer = setTimeout, clearTimer = clearTimeout, kill = (agent) => agent.close() } = {}) {
|
|
8
|
+
clearStopTimer(st, { clearTimer });
|
|
9
|
+
if (!st?.busy || !st.agent || st.agent.closed) return () => {};
|
|
10
|
+
const turn = st.turnId;
|
|
11
|
+
st.stopTimer = setTimer(() => {
|
|
12
|
+
st.stopTimer = null;
|
|
13
|
+
if (!st.busy || st.turnId !== turn || !st.agent || st.agent.closed) return;
|
|
14
|
+
kill(st.agent);
|
|
15
|
+
}, ms);
|
|
16
|
+
if (typeof st.stopTimer?.unref === 'function') st.stopTimer.unref();
|
|
17
|
+
return () => clearStopTimer(st, { clearTimer });
|
|
18
|
+
}
|
package/src/git.mjs
CHANGED
|
@@ -54,7 +54,10 @@ export const SAFE_CONFIG = [
|
|
|
54
54
|
['core.hooksPath', devNull],
|
|
55
55
|
['core.fsmonitor', 'false'],
|
|
56
56
|
['credential.helper', ''],
|
|
57
|
+
['protocol.allow', 'never'],
|
|
58
|
+
['protocol.https.allow', 'always'],
|
|
57
59
|
['protocol.ext.allow', 'never'],
|
|
60
|
+
['safe.bareRepository', 'explicit'],
|
|
58
61
|
['advice.detachedHead', 'false'],
|
|
59
62
|
['core.quotePath', 'false'], // имена файлов не латиницей — как есть, а не восьмеричными кодами
|
|
60
63
|
];
|
|
@@ -65,7 +68,7 @@ export const SAFE_CONFIG = [
|
|
|
65
68
|
* На Linux и macOS общий и системный конфиги не читаются: в песочнице общий конфиг лежит в папке, куда пишет агент.
|
|
66
69
|
*/
|
|
67
70
|
export function gitEnv({ identity = null, auth = [], base = process.env } = {}) {
|
|
68
|
-
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
71
|
+
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_ASKPASS: '', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
69
72
|
if (!IS_WIN) Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' });
|
|
70
73
|
if (identity?.name && identity?.email) {
|
|
71
74
|
Object.assign(env, { GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email, GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
|
|
@@ -83,6 +86,13 @@ export class GitError extends Error {
|
|
|
83
86
|
}
|
|
84
87
|
}
|
|
85
88
|
|
|
89
|
+
export class GitConfigError extends GitError {
|
|
90
|
+
constructor(keys) {
|
|
91
|
+
super(`небезопасные настройки репозитория: ${keys.join(', ')}`);
|
|
92
|
+
this.keys = keys;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
86
96
|
/**
|
|
87
97
|
* Запускает git. Без оболочки: аргументы (описание коммита, имена файлов) передаются как есть.
|
|
88
98
|
* @param {string[]} args
|
|
@@ -138,6 +148,28 @@ export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120
|
|
|
138
148
|
});
|
|
139
149
|
}
|
|
140
150
|
|
|
151
|
+
const DENIED_CONFIG = (key) =>
|
|
152
|
+
['core.sshcommand', 'core.askpass', 'gpg.program', 'core.alternaterefscommand'].includes(key) ||
|
|
153
|
+
key === 'include.path' ||
|
|
154
|
+
/^includeif\..*\.path$/.test(key) ||
|
|
155
|
+
/^remote\..+\.(uploadpack|receivepack)$/.test(key) ||
|
|
156
|
+
(/^filter\./.test(key) && !key.startsWith('filter.lfs.'));
|
|
157
|
+
|
|
158
|
+
const isFalse = (value) => /^(false|no|off|0)$/i.test(String(value).trim());
|
|
159
|
+
|
|
160
|
+
export async function assertPlainConfig(cwd, opts = {}) {
|
|
161
|
+
const raw = await runGit(['config', '--local', '--list', '-z'], { cwd, ...opts });
|
|
162
|
+
const bad = [];
|
|
163
|
+
for (const rec of raw.split('\0')) {
|
|
164
|
+
if (!rec) continue;
|
|
165
|
+
const cut = rec.indexOf('\n');
|
|
166
|
+
const key = (cut < 0 ? rec : rec.slice(0, cut)).toLowerCase();
|
|
167
|
+
const value = cut < 0 ? '' : rec.slice(cut + 1);
|
|
168
|
+
if (DENIED_CONFIG(key) || (/^http(\..+)?\.sslverify$/.test(key) && isFalse(value))) bad.push(key);
|
|
169
|
+
}
|
|
170
|
+
if (bad.length) throw new GitConfigError([...new Set(bad)]);
|
|
171
|
+
}
|
|
172
|
+
|
|
141
173
|
/**
|
|
142
174
|
* Разбор `git status --porcelain=v2 --branch`.
|
|
143
175
|
* @returns {{branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}}
|
|
@@ -174,17 +206,26 @@ export async function repoState(cwd, opts = {}) {
|
|
|
174
206
|
}
|
|
175
207
|
|
|
176
208
|
/** Клонирует репозиторий url в папку dest (её ещё нет), запускается из её родительской папки cwd. Подмодули не тянутся. */
|
|
177
|
-
export
|
|
209
|
+
export async function cloneRepo(url, dest, { cwd, ...opts }) {
|
|
210
|
+
await runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
|
|
211
|
+
await assertPlainConfig(join(cwd, dest), opts);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const fetchRaw = (cwd, opts) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
|
|
178
215
|
|
|
179
216
|
/** Сверяется с сервером (git fetch): рабочие файлы не трогает, обновляет сведения о ветках сервера. */
|
|
180
|
-
export
|
|
217
|
+
export async function fetchRepo(cwd, opts = {}) {
|
|
218
|
+
await assertPlainConfig(cwd, opts);
|
|
219
|
+
return fetchRaw(cwd, opts);
|
|
220
|
+
}
|
|
181
221
|
|
|
182
222
|
/**
|
|
183
223
|
* Получает изменения с сервера: fetch и перемотка вперёд, если это возможно без слияния.
|
|
184
224
|
* @returns {Promise<'updated'|'uptodate'|'diverged'|'noupstream'>} diverged — истории разошлись, нужно слияние (его делает агент)
|
|
185
225
|
*/
|
|
186
226
|
export async function pullRepo(cwd, opts = {}) {
|
|
187
|
-
await
|
|
227
|
+
await assertPlainConfig(cwd, opts);
|
|
228
|
+
await fetchRaw(cwd, opts);
|
|
188
229
|
const before = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
189
230
|
if (!before.upstream) return 'noupstream';
|
|
190
231
|
if (!before.behind) return 'uptodate';
|
|
@@ -211,7 +252,10 @@ export async function unpushedSecrets(cwd, opts = {}) {
|
|
|
211
252
|
}
|
|
212
253
|
|
|
213
254
|
/** Отправляет текущую ветку на сервер (и связывает её с веткой сервера). */
|
|
214
|
-
export
|
|
255
|
+
export async function pushRepo(cwd, opts = {}) {
|
|
256
|
+
await assertPlainConfig(cwd, opts);
|
|
257
|
+
return runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
|
|
258
|
+
}
|
|
215
259
|
|
|
216
260
|
/**
|
|
217
261
|
* Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
|
|
@@ -221,6 +265,7 @@ export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEA
|
|
|
221
265
|
* подменён ссылкой или недоступен, правила туда не записаны
|
|
222
266
|
*/
|
|
223
267
|
export async function commitAll(cwd, message, opts = {}) {
|
|
268
|
+
await assertPlainConfig(cwd, opts);
|
|
224
269
|
await runGit(['add', '-A'], { cwd, ...opts });
|
|
225
270
|
const staged = (await runGit(['diff', '--cached', '--name-status'], { cwd, ...opts }))
|
|
226
271
|
.split(/\r?\n/)
|
package/src/gitCtx.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { db } from './ctx.mjs';
|
|
3
|
+
import { accountsOf, hostFor, identityOf } from './gitAccess.mjs';
|
|
4
|
+
import { authConfig, HostError } from './gitHosts.mjs';
|
|
5
|
+
import { gitCommand, gitEnv, GitConfigError, GitError, repoState } from './git.mjs';
|
|
6
|
+
import { errText } from './i18n.mjs';
|
|
7
|
+
import { insideRoot, isPersonalRoot, ROOT } from './projects.mjs';
|
|
8
|
+
import { agentSandbox } from './sandbox.mjs';
|
|
9
|
+
import { rootOf, sandboxed } from './state.mjs';
|
|
10
|
+
import { th } from './ui.mjs';
|
|
11
|
+
|
|
12
|
+
export const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
13
|
+
|
|
14
|
+
const baseOpts = (st, cwd, account, auth, hide) => {
|
|
15
|
+
const root = rootOf(st.userId);
|
|
16
|
+
const wrap = sandboxed(st.userId, cwd)
|
|
17
|
+
? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
|
|
18
|
+
: null;
|
|
19
|
+
return { env: gitEnv({ identity: identityOf(account), auth }), wrap, hide };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function gitOpts(st, cwd, account = null) {
|
|
23
|
+
const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
|
|
24
|
+
return baseOpts(st, cwd, who, [], []);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function gitNetOpts(st, cwd, { host, account }) {
|
|
28
|
+
const auth = host && account ? authConfig(host, account.token) : [];
|
|
29
|
+
const hide = account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [];
|
|
30
|
+
return baseOpts(st, cwd, account, auth, hide);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function repoOf(st, project) {
|
|
34
|
+
const state = await repoState(project, gitOpts(st, project));
|
|
35
|
+
if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
|
|
36
|
+
const host = hostFor(state.remote);
|
|
37
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
38
|
+
return { state, host, account };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const failText = (e, lang, host = null) => {
|
|
42
|
+
if (e instanceof GitConfigError) return th('git.unsafeConfig', lang, { keys: e.keys.join(', ') });
|
|
43
|
+
if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
|
|
44
|
+
return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const gitLocks = new Map();
|
|
48
|
+
const lockKey = (cwd) => {
|
|
49
|
+
const p = resolve(String(cwd ?? ''));
|
|
50
|
+
return process.platform === 'win32' ? p.toLowerCase() : p;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function acquireGitLock(st, cwd) {
|
|
54
|
+
const key = lockKey(cwd);
|
|
55
|
+
if (gitLocks.has(key)) return null;
|
|
56
|
+
const token = Symbol('git');
|
|
57
|
+
gitLocks.set(key, token);
|
|
58
|
+
st.gitBusy = true;
|
|
59
|
+
return { key, token };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function releaseGitLock(st, lock) {
|
|
63
|
+
if (!lock) return;
|
|
64
|
+
if (gitLocks.get(lock.key) === lock.token) gitLocks.delete(lock.key);
|
|
65
|
+
st.gitBusy = false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const isGitLocked = (cwd) => gitLocks.has(lockKey(cwd));
|
package/src/gitInspect.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// безопасными настройками и, при включённой песочнице, внутри неё.
|
|
4
4
|
import { lstatSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
|
-
import { GitError, runGit } from './git.mjs';
|
|
6
|
+
import { assertPlainConfig, GitError, runGit } from './git.mjs';
|
|
7
7
|
import { samePath } from './projects.mjs';
|
|
8
8
|
|
|
9
9
|
/** Сколько изменённых файлов показывать (в большом несобранном проекте их могут быть тысячи). */
|
|
@@ -158,12 +158,16 @@ export async function branchName(input, { cwd, ...opts }) {
|
|
|
158
158
|
*/
|
|
159
159
|
export async function switchBranch(cwd, branch, opts = {}) {
|
|
160
160
|
if (!branch?.name || branch.name.startsWith('-')) throw new GitError('некорректное название ветки');
|
|
161
|
+
await assertPlainConfig(cwd, opts);
|
|
161
162
|
if (branch.local) return runGit(['switch', '--quiet', branch.name], { cwd, ...opts });
|
|
162
163
|
return runGit(['switch', '--quiet', '--track', `origin/${branch.name}`], { cwd, ...opts });
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
/** Создаёт ветку от текущего коммита и переключается на неё (несохранённые изменения остаются в рабочей папке). */
|
|
166
|
-
export
|
|
167
|
+
export async function createBranch(cwd, name, opts = {}) {
|
|
168
|
+
await assertPlainConfig(cwd, opts);
|
|
169
|
+
return runGit(['switch', '--quiet', '-c', name], { cwd, ...opts });
|
|
170
|
+
}
|
|
167
171
|
|
|
168
172
|
/**
|
|
169
173
|
* Отменяет несохранённые изменения файлов (записи из changedFiles): изменённые и удалённые возвращаются к последнему
|
|
@@ -172,6 +176,7 @@ export const createBranch = (cwd, name, opts = {}) => runGit(['switch', '--quiet
|
|
|
172
176
|
*/
|
|
173
177
|
export async function discardFiles(cwd, files, opts = {}) {
|
|
174
178
|
if (!files.length) return 0;
|
|
179
|
+
await assertPlainConfig(cwd, opts);
|
|
175
180
|
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
176
181
|
const at = { cwd: top, ...opts };
|
|
177
182
|
const paths = [...new Set(files.flatMap((f) => [f.path, f.from]).filter(Boolean))];
|
package/src/gitPublishUi.mjs
CHANGED
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
// Публикация: папка, которая ещё не связана с сервером, становится репозиторием — пользователь выбирает сервис, место
|
|
3
3
|
// (личное пространство, группа или организация), видимость и название; бот создаёт репозиторий, делает первый коммит
|
|
4
4
|
// (без файлов с секретами) и отправляет. Запрос на слияние: из текущей ветки в основную ветку репозитория.
|
|
5
|
-
//
|
|
5
|
+
// Общие помощники (проект, репозиторий, запуск git) живут в gitCtx.mjs.
|
|
6
6
|
import { basename } from 'node:path';
|
|
7
7
|
import { db, log, say } from './ctx.mjs';
|
|
8
8
|
import { canManageFiles } from './filesUi.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { commitAll, pushRepo, repoState } from './git.mjs';
|
|
10
10
|
import { accountsOf, findHost, hostFor } from './gitAccess.mjs';
|
|
11
|
+
import { acquireGitLock, failText, gitNetOpts, gitOpts, releaseGitLock, repoOf } from './gitCtx.mjs';
|
|
11
12
|
import { recall, remember } from './gitKeys.mjs';
|
|
12
13
|
import { createRepo, listNamespaces, openMergeRequest, repoInfo, repoSlug, visibilities } from './gitApi.mjs';
|
|
13
14
|
import { HostError, showRemote } from './gitHosts.mjs';
|
|
14
15
|
import { ensureRepo, hasCommits, isRepoRoot, lastSubject, setRemote } from './gitInspect.mjs';
|
|
15
|
-
import {
|
|
16
|
+
import { t } from './i18n.mjs';
|
|
16
17
|
import { userPath } from './state.mjs';
|
|
17
18
|
import { hCode, th } from './ui.mjs';
|
|
18
19
|
|
|
@@ -27,16 +28,10 @@ const VIS_MARK = { private: '🔒', internal: '🏢', public: '🌍' };
|
|
|
27
28
|
const backRow = (lang) => [{ text: t('btn.back', lang), callback_data: 'gt:v' }];
|
|
28
29
|
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
29
30
|
|
|
30
|
-
/** Текст ошибки: не хватило прав токена — отдельной подсказкой (нужен токен с правом api). */
|
|
31
|
-
const failText = (e, lang, host) => {
|
|
32
|
-
if (e instanceof HostError && e.code === 'forbidden') return th('git.needApi', lang, { host: host?.label ?? 'Git', msg: e.message });
|
|
33
|
-
return th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
34
|
-
};
|
|
35
|
-
|
|
36
31
|
/** Можно ли публиковать проект: это ещё не репозиторий с адресом сервера (свой репозиторий без origin — тоже можно). */
|
|
37
|
-
export async function canPublish(st, project
|
|
32
|
+
export async function canPublish(st, project) {
|
|
38
33
|
if (!canManageFiles(st.userId) || !accountsOf(st.userId).length) return false;
|
|
39
|
-
const opts =
|
|
34
|
+
const opts = gitOpts(st, project);
|
|
40
35
|
if (!(await isRepoRoot(project, opts))) return true;
|
|
41
36
|
return !(await repoState(project, opts))?.remote;
|
|
42
37
|
}
|
|
@@ -72,11 +67,13 @@ function summaryView(st, project, lang) {
|
|
|
72
67
|
}
|
|
73
68
|
|
|
74
69
|
/** Создаёт репозиторий на сервисе, делает первый коммит и отправляет. */
|
|
75
|
-
async function publish(st, project, lang, edit,
|
|
70
|
+
async function publish(st, project, lang, edit, view) {
|
|
76
71
|
const pub = st.gitPublish;
|
|
77
72
|
const { host, account } = accountOf(st, pub);
|
|
78
|
-
const opts =
|
|
79
|
-
|
|
73
|
+
const opts = gitOpts(st, project, account);
|
|
74
|
+
const net = gitNetOpts(st, project, { host, account });
|
|
75
|
+
const lock = acquireGitLock(st, project);
|
|
76
|
+
if (!lock) return edit({ text: t('git.busy', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
80
77
|
try {
|
|
81
78
|
await edit({ text: th('git.pb.working', lang) });
|
|
82
79
|
// сначала локальная часть: если публиковать нечего, репозиторий на сервере не создаётся
|
|
@@ -88,7 +85,7 @@ async function publish(st, project, lang, edit, h) {
|
|
|
88
85
|
// адрес из ответа сервиса уходит в настройки репозитория: чужой адрес (или не адрес вовсе) не принимаем
|
|
89
86
|
if (hostFor(created.url)?.id !== host.id) throw new HostError('http', `${host.label}: unexpected repository address`);
|
|
90
87
|
await setRemote(project, created.url, opts);
|
|
91
|
-
await pushRepo(project,
|
|
88
|
+
await pushRepo(project, net);
|
|
92
89
|
log('git: проект опубликован:', st.userId, project, '→', created.path);
|
|
93
90
|
st.gitPublish = null;
|
|
94
91
|
const note = [
|
|
@@ -96,21 +93,21 @@ async function publish(st, project, lang, edit, h) {
|
|
|
96
93
|
...(first.tracked.length ? [th('git.tracked', lang, { files: first.tracked.join(', ') })] : []),
|
|
97
94
|
...(first.ignoreWarning ? [th('git.ignoreLink', lang)] : []),
|
|
98
95
|
].map((s) => `\n${s}`).join('');
|
|
99
|
-
const v = await
|
|
96
|
+
const v = await view();
|
|
100
97
|
const open = created.web ? [[{ text: t('git.open', lang), url: created.web }]] : [];
|
|
101
98
|
return await edit({ text: `${th('git.pb.done', lang, { address: hCode(showRemote(created.url)) })}${note}\n\n${v.text}`, markup: { inline_keyboard: [...open, ...v.markup.inline_keyboard] } });
|
|
102
99
|
} catch (e) {
|
|
103
100
|
log('git: публикация:', e.message, '| пользователь', st.userId);
|
|
104
101
|
return await edit({ text: failText(e, lang, host), markup: { inline_keyboard: [backRow(lang)] } });
|
|
105
102
|
} finally {
|
|
106
|
-
st
|
|
103
|
+
releaseGitLock(st, lock);
|
|
107
104
|
}
|
|
108
105
|
}
|
|
109
106
|
|
|
110
107
|
/** Создаёт запрос на слияние текущей ветки в основную (или находит уже открытый) и даёт ссылку. */
|
|
111
|
-
async function mergeRequest(st, project, title, lang, edit
|
|
108
|
+
async function mergeRequest(st, project, title, lang, edit) {
|
|
112
109
|
const mr = st.gitMr;
|
|
113
|
-
const repo = await
|
|
110
|
+
const repo = await repoOf(st, project);
|
|
114
111
|
if (!mr || !repo?.account) return edit({ text: th('git.diff.gone', lang), markup: { inline_keyboard: [backRow(lang)] } });
|
|
115
112
|
st.gitMr = null;
|
|
116
113
|
try {
|
|
@@ -124,9 +121,9 @@ async function mergeRequest(st, project, title, lang, edit, h) {
|
|
|
124
121
|
}
|
|
125
122
|
}
|
|
126
123
|
|
|
127
|
-
/** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…).
|
|
124
|
+
/** Кнопки «Опубликовать проект» (pb…) и «Запрос на слияние» (mr…). */
|
|
128
125
|
export async function onPublishCallback(st, cb, h) {
|
|
129
|
-
const { action, arg, lang, ack, edit, project } = h;
|
|
126
|
+
const { action, arg, lang, ack, edit, project, view } = h;
|
|
130
127
|
if (!project) return ack(t('state.projectGone', lang));
|
|
131
128
|
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
132
129
|
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
@@ -134,14 +131,14 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
134
131
|
try {
|
|
135
132
|
// ---- запрос на слияние ----
|
|
136
133
|
if (action === 'mr') {
|
|
137
|
-
const repo = await
|
|
134
|
+
const repo = await repoOf(st, project);
|
|
138
135
|
if (!repo?.account || !repo.state.branch) return ack(t('proj.stale', lang));
|
|
139
136
|
await ack();
|
|
140
137
|
const info = await repoInfo(repo.host, repo.account.token, repo.state.remote);
|
|
141
138
|
const s = repo.state;
|
|
142
139
|
if (s.branch === info.defaultBranch) return edit({ text: th('git.mr.onDefault', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }], backRow(lang)] } });
|
|
143
140
|
if (!s.upstream || s.ahead) return edit({ text: th('git.mr.pushFirst', lang, { branch: hCode(s.branch) }), markup: { inline_keyboard: [[{ text: t('git.push', lang), callback_data: 'gt:push' }], backRow(lang)] } });
|
|
144
|
-
const suggested = (await lastSubject(project,
|
|
141
|
+
const suggested = (await lastSubject(project, gitOpts(st, project, repo.account))) || s.branch;
|
|
145
142
|
st.gitMr = { branch: s.branch, target: info.defaultBranch, suggested };
|
|
146
143
|
st.pendingInput = { kind: 'gitMrTitle', at: Date.now() };
|
|
147
144
|
const markup = { inline_keyboard: [[{ text: [...`«${suggested}»`].slice(0, 60).join(''), callback_data: 'gt:mrgo' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
|
|
@@ -150,10 +147,10 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
150
147
|
if (action === 'mrgo') {
|
|
151
148
|
st.pendingInput = null;
|
|
152
149
|
await ack();
|
|
153
|
-
return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit
|
|
150
|
+
return await mergeRequest(st, project, st.gitMr?.suggested ?? '', lang, edit);
|
|
154
151
|
}
|
|
155
152
|
// ---- публикация ----
|
|
156
|
-
if (!(await canPublish(st, project
|
|
153
|
+
if (!(await canPublish(st, project))) return ack(t('proj.stale', lang));
|
|
157
154
|
const accounts = accountsOf(st.userId);
|
|
158
155
|
if (action === 'pb') {
|
|
159
156
|
await ack();
|
|
@@ -200,7 +197,7 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
200
197
|
if (action === 'pbgo') {
|
|
201
198
|
if (!pub.slug) return ack(t('git.pb.nameBad', lang));
|
|
202
199
|
await ack();
|
|
203
|
-
return await publish(st, project, lang, edit,
|
|
200
|
+
return await publish(st, project, lang, edit, view);
|
|
204
201
|
}
|
|
205
202
|
return ack(t('proj.stale', lang));
|
|
206
203
|
} catch (e) {
|
|
@@ -212,7 +209,7 @@ export async function onPublishCallback(st, cb, h) {
|
|
|
212
209
|
|
|
213
210
|
/**
|
|
214
211
|
* Текст пользователя для публикации и запроса на слияние: строка поиска группы, название репозитория, заголовок запроса.
|
|
215
|
-
* @param {object} h {wait, now, lang, project, send,
|
|
212
|
+
* @param {object} h {wait, now, lang, project, send, view}
|
|
216
213
|
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
217
214
|
*/
|
|
218
215
|
export async function onPublishInput(st, text, h) {
|
|
@@ -222,7 +219,7 @@ export async function onPublishInput(st, text, h) {
|
|
|
222
219
|
if (wait.kind === 'gitMrTitle') {
|
|
223
220
|
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
224
221
|
const title = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || st.gitMr?.suggested || '';
|
|
225
|
-
await mergeRequest(st, project, title, lang, send
|
|
222
|
+
await mergeRequest(st, project, title, lang, send);
|
|
226
223
|
return true;
|
|
227
224
|
}
|
|
228
225
|
const pub = st.gitPublish;
|