odant-work 1.0.39 → 1.0.41
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/#system/package-manifest.json +29 -29
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +212 -72
- package/$server/$folder/$file/$task/class.js +3 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +33 -1
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +65 -1
- package/$server/$folder/lib/consultant/consultant.js +9 -0
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +27 -7
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +2 -2
- package/package.json +1 -1
- package/sources/data/progress.md +11 -0
- package/sources/modules/agent/loop.js +39 -4
- package/sources/modules/agent/permissions.js +271 -111
- package/sources/modules/agent/session.js +89 -2
- package/sources/modules/agent/system.js +10 -3
- package/sources/modules/agent/tools/chrome.js +25 -4
- package/sources/modules/agent/tools/desktop.js +184 -170
- package/sources/modules/agent/tools/dev/checks.js +160 -160
- package/sources/modules/agent/tools/dev/git.js +276 -276
- package/sources/modules/agent/tools/net.js +45 -45
- package/sources/modules/agent/tools/os-proc.js +179 -169
- package/sources/modules/agent/tools/services.js +280 -275
- package/sources/modules/trainer/index.js +1 -0
- package/sources/modules/trainer/local-engine.js +321 -55
- package/sources/modules/trainer/worker/local_infer_worker.py +34 -12
- package/sources/reactor.js +8 -0
- package/sources/server/class/feed.js +21 -12
- package/sources/server/logs.js +50 -8
|
@@ -1,276 +1,276 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Инструменты разработчика (этап 6.4): git — чтение истории, коммиты, ветки, публикация.
|
|
3
|
-
*
|
|
4
|
-
* Арены (архитектура 6.1, инварианты 12–13 в rules/threats.md):
|
|
5
|
-
* work — репозиторий сервера WORK (корень дерева): только корневому ADMIN;
|
|
6
|
-
* spawn с ЯВНЫМИ аргументами (без оболочки), фиксированный cwd, окружение
|
|
7
|
-
* без токенов и с GIT_TERMINAL_PROMPT=0, ref/имена/пути проверяются,
|
|
8
|
-
* «--» перед путями против инъекции опций; таймаут ≤120 с, вывод ≤200 КБ;
|
|
9
|
-
* команды, переписывающие рабочее дерево (checkout/reset/restore/stash/clean/rm),
|
|
10
|
-
* агенту недоступны вовсе — правка файлов идёт через write/edit/apply_patch
|
|
11
|
-
* с историей и откатом ленты (таких инструментов здесь нет — и быть не должно);
|
|
12
|
-
* sandbox — репозиторий пользователя в контейнере (/workspace): те же инструменты,
|
|
13
|
-
* через docker exec с массивом аргументов (без sh), вывод с потолком;
|
|
14
|
-
* при включённом интернете — untrusted (правило sandbox_exec).
|
|
15
|
-
*
|
|
16
|
-
* Разрешения: чтения — readonly (любой режим); git_branch — risk write (в auto свободно,
|
|
17
|
-
* создаёт только указатель ветки); git_commit — подтверждение КАЖДЫЙ раз (изменение системы,
|
|
18
|
-
* без «разрешить всегда»; хеш коммита — в журнал безопасности); git_push — outbound:
|
|
19
|
-
* всегда подтверждение без «разрешить всегда», субагенту не выдаётся (SUBAGENT_DENY).
|
|
20
|
-
*/
|
|
21
|
-
import fs from 'node:fs';
|
|
22
|
-
import path from 'node:path';
|
|
23
|
-
import { run, isAdmin, audit, askEach } from '../../system.js';
|
|
24
|
-
import { ctxRun } from '../sandbox.js';
|
|
25
|
-
import { useSandbox, markSandboxTaint } from './search.js';
|
|
26
|
-
import { execRaw } from '../../../sandbox/manager.js';
|
|
27
|
-
import { clip } from '../../util.js';
|
|
28
|
-
|
|
29
|
-
const GIT_TIMEOUT_MS = 120_000; // потолок команды (арена work)
|
|
30
|
-
const GIT_OUT_MAX = 200_000; // потолок вывода
|
|
31
|
-
const GIT_SBX_SEC = 60; // потолок команды (песочница)
|
|
32
|
-
|
|
33
|
-
/** Окружение для git: без токенов/паролей процесса, без интерактивных вопросов. */
|
|
34
|
-
function gitEnv() {
|
|
35
|
-
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' };
|
|
36
|
-
for (const k of Object.keys(env))
|
|
37
|
-
if (/(TOKEN|PASSPHRASE|PASSWORD|SECRET)/i.test(k))
|
|
38
|
-
delete env[k];
|
|
39
|
-
return env;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** ref/имя ветки/тега или хеш: без опций, «..», пробелов — не превращается в аргумент команды. */
|
|
43
|
-
export function checkGitRef(s, what = 'ref') {
|
|
44
|
-
const v = String(s ?? '').trim();
|
|
45
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._/@+-]{0,99}$/.test(v) || v.includes('..'))
|
|
46
|
-
throw new Error('недопустимое значение ' + what + ' «' + String(s).slice(0, 40) + '»: буквы, цифры, точка, дефис, слэш, @ (без опций и «..»)');
|
|
47
|
-
return v;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** remote: имя или URL — без пробелов и ведущих дефисов (не опция). */
|
|
51
|
-
export function checkGitRemote(s) {
|
|
52
|
-
const v = String(s ?? '').trim();
|
|
53
|
-
if (!/^[A-Za-z0-9@:/._~-]{1,200}$/.test(v) || v.includes('..'))
|
|
54
|
-
throw new Error('недопустимый remote «' + String(s).slice(0, 40) + '»');
|
|
55
|
-
return v;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Путь внутри репозитория: относительный, без «..» и ведущего дефиса. */
|
|
59
|
-
export function checkRepoPath(s) {
|
|
60
|
-
const v = String(s ?? '').trim().replace(/\\/g, '/');
|
|
61
|
-
if (!v || v.startsWith('/') || v.startsWith('-') || v.split('/').some(x => !x || x === '..' || x === '.'))
|
|
62
|
-
throw new Error('недопустимый путь «' + String(s).slice(0, 60) + '»: относительный, внутри репозитория');
|
|
63
|
-
return v;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/** git на сервере WORK: только администратор, и корень дерева — репозиторий. */
|
|
67
|
-
async function assertGitWork(ctx) {
|
|
68
|
-
if (!(await isAdmin(ctx?.session)))
|
|
69
|
-
throw new Error('git репозитория сервера WORK — только администратору; свой проект — в песочнице (where:"sandbox")');
|
|
70
|
-
if (!fs.existsSync(path.join(process.cwd(), '.git')))
|
|
71
|
-
throw new Error('корень WORK не является git-репозиторием (нет .git) — работа с git доступна в песочнице (where:"sandbox")');
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** Запуск git в арене work: явные аргументы, фиксированный cwd, окружение без токенов. */
|
|
75
|
-
async function workGit(argv, ctx) {
|
|
76
|
-
return await run('git', argv, {
|
|
77
|
-
cwd: process.cwd(), timeout: GIT_TIMEOUT_MS, max: GIT_OUT_MAX,
|
|
78
|
-
signal: ctx?.signal, env: gitEnv(),
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Запуск git в арене sandbox: массив аргументов без оболочки, потолок вывода. */
|
|
83
|
-
async function sbxGit(argv, ctx, args) {
|
|
84
|
-
const { cfg, docker, pc } = await useSandbox(args, ctx);
|
|
85
|
-
await markSandboxTaint(docker, pc, cfg, ctx);
|
|
86
|
-
return await execRaw(docker, pc.id, {
|
|
87
|
-
cmd: ['git', ...argv],
|
|
88
|
-
workdir: cfg.workdir || '/workspace', timeoutSec: GIT_SBX_SEC, maxBytes: GIT_OUT_MAX, signal: ctx?.signal,
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Вывод команды: stdout с потолком, ошибка — с stderr. */
|
|
93
|
-
function gitOut(r, o = {}) {
|
|
94
|
-
if (r.aborted)
|
|
95
|
-
return '[остановлено пользователем]';
|
|
96
|
-
if (r.timedOut || r.code === 124)
|
|
97
|
-
return '[таймаут — команда остановлена]\n' + clip(r.stdout || '', GIT_OUT_MAX);
|
|
98
|
-
if (r.code === 0)
|
|
99
|
-
return clip(String(r.stdout || '').trim(), GIT_OUT_MAX) || o.empty || '(пусто)';
|
|
100
|
-
throw new Error('git ' + (o.what || 'команда') + ' вернула код ' + r.code
|
|
101
|
-
+ (String(r.stderr || '').trim() ? ': ' + clip(String(r.stderr).trim(), 400) : ''));
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
const WHERE_PROP = {
|
|
105
|
-
where: {
|
|
106
|
-
type: 'string',
|
|
107
|
-
enum: ['work', 'sandbox'],
|
|
108
|
-
description: 'Репозиторий: work — сервер WORK (только администратор), sandbox — ваш компьютер (песочница, /workspace)',
|
|
109
|
-
},
|
|
110
|
-
};
|
|
111
|
-
const SBX_NAME = { name: { type: 'string', description: 'Компьютер (только sandbox, по умолчанию main)' } };
|
|
112
|
-
|
|
113
|
-
/** Единая обвязка простого инструмента: собрать argv (валидации в fn), выполнить в арене. */
|
|
114
|
-
function gitTool(fn, o = {}) {
|
|
115
|
-
return async (args, ctx) => {
|
|
116
|
-
const argv = fn(args);
|
|
117
|
-
const r = args?.where === 'sandbox'
|
|
118
|
-
? await sbxGit(argv, ctx, args)
|
|
119
|
-
: (await assertGitWork(ctx), await workGit(argv, ctx));
|
|
120
|
-
return gitOut(r, { what: o.what || argv[0], empty: o.empty });
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// ── инструменты ─────────────────────────────────────────────────────────────
|
|
125
|
-
|
|
126
|
-
export const git_status = {
|
|
127
|
-
name: 'git_status',
|
|
128
|
-
readonly: true,
|
|
129
|
-
description: 'Состояние репозитория: ветка, изменённые и новые файлы (git status --porcelain). Арена where: work — репозиторий сервера WORK (администратор), sandbox — ваш компьютер.',
|
|
130
|
-
parameters: { type: 'object', properties: { ...WHERE_PROP, ...SBX_NAME } },
|
|
131
|
-
run: gitTool(() => ['status', '--porcelain=v1', '--branch']),
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
export const git_diff = {
|
|
135
|
-
name: 'git_diff',
|
|
136
|
-
readonly: true,
|
|
137
|
-
description: 'Незафиксированные изменения (git diff; staged:true — подготовленные к коммиту). Пусто — по всему репозиторию.',
|
|
138
|
-
parameters: {
|
|
139
|
-
type: 'object',
|
|
140
|
-
properties: {
|
|
141
|
-
...WHERE_PROP, ...SBX_NAME,
|
|
142
|
-
path: { type: 'string', description: 'Путь внутри репозитория (по умолчанию всё)' },
|
|
143
|
-
staged: { type: 'boolean', description: 'Подготовленные к коммиту (index) вместо рабочей копии' },
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
run: gitTool(a => {
|
|
147
|
-
const paths = a?.path !== undefined ? ['--', checkRepoPath(a.path)] : [];
|
|
148
|
-
return ['diff', ...(a.staged ? ['--cached'] : []), ...paths];
|
|
149
|
-
}, { what: 'diff' }),
|
|
150
|
-
};
|
|
151
|
-
|
|
152
|
-
export const git_log = {
|
|
153
|
-
name: 'git_log',
|
|
154
|
-
readonly: true,
|
|
155
|
-
description: 'История коммитов (git log --oneline), последние сверху. Пусто — по всем путям.',
|
|
156
|
-
parameters: {
|
|
157
|
-
type: 'object',
|
|
158
|
-
properties: {
|
|
159
|
-
...WHERE_PROP, ...SBX_NAME,
|
|
160
|
-
path: { type: 'string', description: 'История одного пути' },
|
|
161
|
-
limit: { type: 'integer', description: 'Сколько коммитов (по умолчанию 30, максимум 200)' },
|
|
162
|
-
},
|
|
163
|
-
},
|
|
164
|
-
run: gitTool(a => ['log', '--oneline', '--decorate', '-n', String(Math.min(200, Math.max(1, Number(a?.limit) || 30))),
|
|
165
|
-
...(a?.path !== undefined ? ['--', checkRepoPath(a.path)] : [])]),
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
export const git_show = {
|
|
169
|
-
name: 'git_show',
|
|
170
|
-
readonly: true,
|
|
171
|
-
description: 'Коммит/тег/ветка: что вошло (git show) — метаданные и изменения. ref — хеш, имя ветки или тега.',
|
|
172
|
-
parameters: {
|
|
173
|
-
type: 'object',
|
|
174
|
-
properties: { ...WHERE_PROP, ...SBX_NAME, ref: { type: 'string', description: 'Хеш/ветка/тег, например HEAD или main' } },
|
|
175
|
-
required: ['ref'],
|
|
176
|
-
},
|
|
177
|
-
run: gitTool(a => ['show', '--oneline', '--stat', checkGitRef(a?.ref)]),
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
export const git_blame = {
|
|
181
|
-
name: 'git_blame',
|
|
182
|
-
readonly: true,
|
|
183
|
-
description: 'Кто и каким коммитом написал каждую строку файла (git blame).',
|
|
184
|
-
parameters: {
|
|
185
|
-
type: 'object',
|
|
186
|
-
properties: { ...WHERE_PROP, ...SBX_NAME, path: { type: 'string', description: 'Путь внутри репозитория' } },
|
|
187
|
-
required: ['path'],
|
|
188
|
-
},
|
|
189
|
-
run: gitTool(a => ['blame', '--', checkRepoPath(a?.path)]),
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
export const git_branch = {
|
|
193
|
-
name: 'git_branch',
|
|
194
|
-
risk: 'write',
|
|
195
|
-
description: 'Создать ветку от текущего HEAD (переключения не происходит: рабочая копия не меняется). Список веток — в git_status/git_log.',
|
|
196
|
-
parameters: {
|
|
197
|
-
type: 'object',
|
|
198
|
-
properties: { ...WHERE_PROP, ...SBX_NAME, branch: { type: 'string', description: 'Имя новой ветки' } },
|
|
199
|
-
required: ['branch'],
|
|
200
|
-
},
|
|
201
|
-
run: gitTool(a => ['branch', checkGitRef(a?.branch, 'имя ветки')]),
|
|
202
|
-
};
|
|
203
|
-
|
|
204
|
-
export const git_commit = {
|
|
205
|
-
name: 'git_commit',
|
|
206
|
-
risk: 'write',
|
|
207
|
-
description: 'Зафиксировать изменения: добавить paths (пусто — все изменения, включая новые файлы) и создать коммит с сообщением. Подтверждение — каждый раз; хеш коммита попадает в журнал безопасности. Правка файлов — через write/edit/apply_patch, git только фиксирует.',
|
|
208
|
-
parameters: {
|
|
209
|
-
type: 'object',
|
|
210
|
-
properties: {
|
|
211
|
-
...WHERE_PROP, ...SBX_NAME,
|
|
212
|
-
message: { type: 'string', description: 'Сообщение коммита' },
|
|
213
|
-
paths: { type: 'array', items: { type: 'string' }, description: 'Что добавить (по умолчанию — все изменения)' },
|
|
214
|
-
},
|
|
215
|
-
required: ['message'],
|
|
216
|
-
},
|
|
217
|
-
permission:
|
|
218
|
-
async run(args, ctx) {
|
|
219
|
-
const message = String(args?.message ?? '').trim();
|
|
220
|
-
if (!message)
|
|
221
|
-
throw new Error('нужно сообщение коммита');
|
|
222
|
-
const argvAdd = args?.paths?.length
|
|
223
|
-
? ['add', '--', ...args.paths.map(p => checkRepoPath(p))]
|
|
224
|
-
: ['add', '-A'];
|
|
225
|
-
if (args?.where === 'sandbox') {
|
|
226
|
-
return ctxRun('git_commit_sandbox', async () => {
|
|
227
|
-
gitOut(await sbxGit(argvAdd, ctx, args), { what: 'add' });
|
|
228
|
-
return gitOut(await sbxGit(['commit', '-m', message], ctx, args), { what: 'commit', empty: 'коммит создан' });
|
|
229
|
-
})(args, ctx);
|
|
230
|
-
}
|
|
231
|
-
return ctxRun('git_commit', async () => {
|
|
232
|
-
const t0 = Date.now();
|
|
233
|
-
await assertGitWork(ctx);
|
|
234
|
-
gitOut(await workGit(argvAdd, ctx), { what: 'add', empty: '' });
|
|
235
|
-
const r = await workGit(['commit', '-m', message], ctx);
|
|
236
|
-
if (r.timedOut || r.code !== 0)
|
|
237
|
-
return gitOut(r, { what: 'commit' });
|
|
238
|
-
const hash = String((await workGit(['rev-parse', '--short', 'HEAD'], ctx)).stdout || '').trim();
|
|
239
|
-
audit({ tool: 'git_commit', hash, ok: true, ms: Date.now() - t0 }, ctx?.session);
|
|
240
|
-
return gitOut(r, { what: 'commit' }) + (hash ? ' (' + hash + ')' : '');
|
|
241
|
-
})(args, ctx);
|
|
242
|
-
},
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
export const git_push = {
|
|
246
|
-
name: 'git_push',
|
|
247
|
-
risk: 'write',
|
|
248
|
-
outbound: true,
|
|
249
|
-
description: 'Отправить коммиты в удалённый репозиторий (git push). Действие наружу: подтверждение человека каждый раз, «разрешить всегда» не предлагается, субагентам недоступно.',
|
|
250
|
-
parameters: {
|
|
251
|
-
type: 'object',
|
|
252
|
-
properties: {
|
|
253
|
-
...WHERE_PROP, ...SBX_NAME,
|
|
254
|
-
remote: { type: 'string', description: 'Имя remote или URL (по умолчанию origin)' },
|
|
255
|
-
ref: { type: 'string', description: 'Что отправлять (по умолчанию HEAD — текущая ветка)' },
|
|
256
|
-
},
|
|
257
|
-
},
|
|
258
|
-
permission: askEach(a => 'отправить коммиты наружу в git («' + String(a?.remote || 'origin') + '», ' + String(a?.ref || 'HEAD') + ') — код покидает сервер'),
|
|
259
|
-
async run(args, ctx) {
|
|
260
|
-
const remote = checkGitRemote(args?.remote || 'origin');
|
|
261
|
-
const ref = checkGitRef(args?.ref || 'HEAD', 'ref');
|
|
262
|
-
const argv = ['push', remote, ref];
|
|
263
|
-
if (args?.where === 'sandbox')
|
|
264
|
-
return ctxRun('git_push_sandbox', () => sbxGit(argv, ctx, args)
|
|
265
|
-
.then(r => gitOut(r, { what: 'push', empty: 'отправлено (без вывода)' })))(args, ctx);
|
|
266
|
-
return ctxRun('git_push', async () => {
|
|
267
|
-
const t0 = Date.now();
|
|
268
|
-
await assertGitWork(ctx);
|
|
269
|
-
const r = await workGit(argv, ctx);
|
|
270
|
-
audit({ tool: 'git_push', remote, ref, ok: r.code === 0, ms: Date.now() - t0 }, ctx?.session);
|
|
271
|
-
return gitOut(r, { what: 'push', empty: 'отправлено (без вывода)' });
|
|
272
|
-
})(args, ctx);
|
|
273
|
-
},
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
export const devGitTools = [git_status, git_diff, git_log, git_show, git_blame, git_branch, git_commit, git_push];
|
|
1
|
+
/**
|
|
2
|
+
* Инструменты разработчика (этап 6.4): git — чтение истории, коммиты, ветки, публикация.
|
|
3
|
+
*
|
|
4
|
+
* Арены (архитектура 6.1, инварианты 12–13 в rules/threats.md):
|
|
5
|
+
* work — репозиторий сервера WORK (корень дерева): только корневому ADMIN;
|
|
6
|
+
* spawn с ЯВНЫМИ аргументами (без оболочки), фиксированный cwd, окружение
|
|
7
|
+
* без токенов и с GIT_TERMINAL_PROMPT=0, ref/имена/пути проверяются,
|
|
8
|
+
* «--» перед путями против инъекции опций; таймаут ≤120 с, вывод ≤200 КБ;
|
|
9
|
+
* команды, переписывающие рабочее дерево (checkout/reset/restore/stash/clean/rm),
|
|
10
|
+
* агенту недоступны вовсе — правка файлов идёт через write/edit/apply_patch
|
|
11
|
+
* с историей и откатом ленты (таких инструментов здесь нет — и быть не должно);
|
|
12
|
+
* sandbox — репозиторий пользователя в контейнере (/workspace): те же инструменты,
|
|
13
|
+
* через docker exec с массивом аргументов (без sh), вывод с потолком;
|
|
14
|
+
* при включённом интернете — untrusted (правило sandbox_exec).
|
|
15
|
+
*
|
|
16
|
+
* Разрешения: чтения — readonly (любой режим); git_branch — risk write (в auto свободно,
|
|
17
|
+
* создаёт только указатель ветки); git_commit — подтверждение КАЖДЫЙ раз (изменение системы,
|
|
18
|
+
* без «разрешить всегда»; хеш коммита — в журнал безопасности); git_push — outbound:
|
|
19
|
+
* всегда подтверждение без «разрешить всегда», субагенту не выдаётся (SUBAGENT_DENY).
|
|
20
|
+
*/
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { run, isAdmin, audit, askEach, askScoped } from '../../system.js';
|
|
24
|
+
import { ctxRun } from '../sandbox.js';
|
|
25
|
+
import { useSandbox, markSandboxTaint } from './search.js';
|
|
26
|
+
import { execRaw } from '../../../sandbox/manager.js';
|
|
27
|
+
import { clip } from '../../util.js';
|
|
28
|
+
|
|
29
|
+
const GIT_TIMEOUT_MS = 120_000; // потолок команды (арена work)
|
|
30
|
+
const GIT_OUT_MAX = 200_000; // потолок вывода
|
|
31
|
+
const GIT_SBX_SEC = 60; // потолок команды (песочница)
|
|
32
|
+
|
|
33
|
+
/** Окружение для git: без токенов/паролей процесса, без интерактивных вопросов. */
|
|
34
|
+
function gitEnv() {
|
|
35
|
+
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' };
|
|
36
|
+
for (const k of Object.keys(env))
|
|
37
|
+
if (/(TOKEN|PASSPHRASE|PASSWORD|SECRET)/i.test(k))
|
|
38
|
+
delete env[k];
|
|
39
|
+
return env;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** ref/имя ветки/тега или хеш: без опций, «..», пробелов — не превращается в аргумент команды. */
|
|
43
|
+
export function checkGitRef(s, what = 'ref') {
|
|
44
|
+
const v = String(s ?? '').trim();
|
|
45
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._/@+-]{0,99}$/.test(v) || v.includes('..'))
|
|
46
|
+
throw new Error('недопустимое значение ' + what + ' «' + String(s).slice(0, 40) + '»: буквы, цифры, точка, дефис, слэш, @ (без опций и «..»)');
|
|
47
|
+
return v;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** remote: имя или URL — без пробелов и ведущих дефисов (не опция). */
|
|
51
|
+
export function checkGitRemote(s) {
|
|
52
|
+
const v = String(s ?? '').trim();
|
|
53
|
+
if (!/^[A-Za-z0-9@:/._~-]{1,200}$/.test(v) || v.includes('..'))
|
|
54
|
+
throw new Error('недопустимый remote «' + String(s).slice(0, 40) + '»');
|
|
55
|
+
return v;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Путь внутри репозитория: относительный, без «..» и ведущего дефиса. */
|
|
59
|
+
export function checkRepoPath(s) {
|
|
60
|
+
const v = String(s ?? '').trim().replace(/\\/g, '/');
|
|
61
|
+
if (!v || v.startsWith('/') || v.startsWith('-') || v.split('/').some(x => !x || x === '..' || x === '.'))
|
|
62
|
+
throw new Error('недопустимый путь «' + String(s).slice(0, 60) + '»: относительный, внутри репозитория');
|
|
63
|
+
return v;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** git на сервере WORK: только администратор, и корень дерева — репозиторий. */
|
|
67
|
+
async function assertGitWork(ctx) {
|
|
68
|
+
if (!(await isAdmin(ctx?.session)))
|
|
69
|
+
throw new Error('git репозитория сервера WORK — только администратору; свой проект — в песочнице (where:"sandbox")');
|
|
70
|
+
if (!fs.existsSync(path.join(process.cwd(), '.git')))
|
|
71
|
+
throw new Error('корень WORK не является git-репозиторием (нет .git) — работа с git доступна в песочнице (where:"sandbox")');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Запуск git в арене work: явные аргументы, фиксированный cwd, окружение без токенов. */
|
|
75
|
+
async function workGit(argv, ctx) {
|
|
76
|
+
return await run('git', argv, {
|
|
77
|
+
cwd: process.cwd(), timeout: GIT_TIMEOUT_MS, max: GIT_OUT_MAX,
|
|
78
|
+
signal: ctx?.signal, env: gitEnv(),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Запуск git в арене sandbox: массив аргументов без оболочки, потолок вывода. */
|
|
83
|
+
async function sbxGit(argv, ctx, args) {
|
|
84
|
+
const { cfg, docker, pc } = await useSandbox(args, ctx);
|
|
85
|
+
await markSandboxTaint(docker, pc, cfg, ctx);
|
|
86
|
+
return await execRaw(docker, pc.id, {
|
|
87
|
+
cmd: ['git', ...argv],
|
|
88
|
+
workdir: cfg.workdir || '/workspace', timeoutSec: GIT_SBX_SEC, maxBytes: GIT_OUT_MAX, signal: ctx?.signal,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Вывод команды: stdout с потолком, ошибка — с stderr. */
|
|
93
|
+
function gitOut(r, o = {}) {
|
|
94
|
+
if (r.aborted)
|
|
95
|
+
return '[остановлено пользователем]';
|
|
96
|
+
if (r.timedOut || r.code === 124)
|
|
97
|
+
return '[таймаут — команда остановлена]\n' + clip(r.stdout || '', GIT_OUT_MAX);
|
|
98
|
+
if (r.code === 0)
|
|
99
|
+
return clip(String(r.stdout || '').trim(), GIT_OUT_MAX) || o.empty || '(пусто)';
|
|
100
|
+
throw new Error('git ' + (o.what || 'команда') + ' вернула код ' + r.code
|
|
101
|
+
+ (String(r.stderr || '').trim() ? ': ' + clip(String(r.stderr).trim(), 400) : ''));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const WHERE_PROP = {
|
|
105
|
+
where: {
|
|
106
|
+
type: 'string',
|
|
107
|
+
enum: ['work', 'sandbox'],
|
|
108
|
+
description: 'Репозиторий: work — сервер WORK (только администратор), sandbox — ваш компьютер (песочница, /workspace)',
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
const SBX_NAME = { name: { type: 'string', description: 'Компьютер (только sandbox, по умолчанию main)' } };
|
|
112
|
+
|
|
113
|
+
/** Единая обвязка простого инструмента: собрать argv (валидации в fn), выполнить в арене. */
|
|
114
|
+
function gitTool(fn, o = {}) {
|
|
115
|
+
return async (args, ctx) => {
|
|
116
|
+
const argv = fn(args);
|
|
117
|
+
const r = args?.where === 'sandbox'
|
|
118
|
+
? await sbxGit(argv, ctx, args)
|
|
119
|
+
: (await assertGitWork(ctx), await workGit(argv, ctx));
|
|
120
|
+
return gitOut(r, { what: o.what || argv[0], empty: o.empty });
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ── инструменты ─────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
export const git_status = {
|
|
127
|
+
name: 'git_status',
|
|
128
|
+
readonly: true,
|
|
129
|
+
description: 'Состояние репозитория: ветка, изменённые и новые файлы (git status --porcelain). Арена where: work — репозиторий сервера WORK (администратор), sandbox — ваш компьютер.',
|
|
130
|
+
parameters: { type: 'object', properties: { ...WHERE_PROP, ...SBX_NAME } },
|
|
131
|
+
run: gitTool(() => ['status', '--porcelain=v1', '--branch']),
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export const git_diff = {
|
|
135
|
+
name: 'git_diff',
|
|
136
|
+
readonly: true,
|
|
137
|
+
description: 'Незафиксированные изменения (git diff; staged:true — подготовленные к коммиту). Пусто — по всему репозиторию.',
|
|
138
|
+
parameters: {
|
|
139
|
+
type: 'object',
|
|
140
|
+
properties: {
|
|
141
|
+
...WHERE_PROP, ...SBX_NAME,
|
|
142
|
+
path: { type: 'string', description: 'Путь внутри репозитория (по умолчанию всё)' },
|
|
143
|
+
staged: { type: 'boolean', description: 'Подготовленные к коммиту (index) вместо рабочей копии' },
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
run: gitTool(a => {
|
|
147
|
+
const paths = a?.path !== undefined ? ['--', checkRepoPath(a.path)] : [];
|
|
148
|
+
return ['diff', ...(a.staged ? ['--cached'] : []), ...paths];
|
|
149
|
+
}, { what: 'diff' }),
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export const git_log = {
|
|
153
|
+
name: 'git_log',
|
|
154
|
+
readonly: true,
|
|
155
|
+
description: 'История коммитов (git log --oneline), последние сверху. Пусто — по всем путям.',
|
|
156
|
+
parameters: {
|
|
157
|
+
type: 'object',
|
|
158
|
+
properties: {
|
|
159
|
+
...WHERE_PROP, ...SBX_NAME,
|
|
160
|
+
path: { type: 'string', description: 'История одного пути' },
|
|
161
|
+
limit: { type: 'integer', description: 'Сколько коммитов (по умолчанию 30, максимум 200)' },
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
run: gitTool(a => ['log', '--oneline', '--decorate', '-n', String(Math.min(200, Math.max(1, Number(a?.limit) || 30))),
|
|
165
|
+
...(a?.path !== undefined ? ['--', checkRepoPath(a.path)] : [])]),
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
export const git_show = {
|
|
169
|
+
name: 'git_show',
|
|
170
|
+
readonly: true,
|
|
171
|
+
description: 'Коммит/тег/ветка: что вошло (git show) — метаданные и изменения. ref — хеш, имя ветки или тега.',
|
|
172
|
+
parameters: {
|
|
173
|
+
type: 'object',
|
|
174
|
+
properties: { ...WHERE_PROP, ...SBX_NAME, ref: { type: 'string', description: 'Хеш/ветка/тег, например HEAD или main' } },
|
|
175
|
+
required: ['ref'],
|
|
176
|
+
},
|
|
177
|
+
run: gitTool(a => ['show', '--oneline', '--stat', checkGitRef(a?.ref)]),
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export const git_blame = {
|
|
181
|
+
name: 'git_blame',
|
|
182
|
+
readonly: true,
|
|
183
|
+
description: 'Кто и каким коммитом написал каждую строку файла (git blame).',
|
|
184
|
+
parameters: {
|
|
185
|
+
type: 'object',
|
|
186
|
+
properties: { ...WHERE_PROP, ...SBX_NAME, path: { type: 'string', description: 'Путь внутри репозитория' } },
|
|
187
|
+
required: ['path'],
|
|
188
|
+
},
|
|
189
|
+
run: gitTool(a => ['blame', '--', checkRepoPath(a?.path)]),
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
export const git_branch = {
|
|
193
|
+
name: 'git_branch',
|
|
194
|
+
risk: 'write',
|
|
195
|
+
description: 'Создать ветку от текущего HEAD (переключения не происходит: рабочая копия не меняется). Список веток — в git_status/git_log.',
|
|
196
|
+
parameters: {
|
|
197
|
+
type: 'object',
|
|
198
|
+
properties: { ...WHERE_PROP, ...SBX_NAME, branch: { type: 'string', description: 'Имя новой ветки' } },
|
|
199
|
+
required: ['branch'],
|
|
200
|
+
},
|
|
201
|
+
run: gitTool(a => ['branch', checkGitRef(a?.branch, 'имя ветки')]),
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
export const git_commit = {
|
|
205
|
+
name: 'git_commit',
|
|
206
|
+
risk: 'write',
|
|
207
|
+
description: 'Зафиксировать изменения: добавить paths (пусто — все изменения, включая новые файлы) и создать коммит с сообщением. Подтверждение — каждый раз; хеш коммита попадает в журнал безопасности. Правка файлов — через write/edit/apply_patch, git только фиксирует.',
|
|
208
|
+
parameters: {
|
|
209
|
+
type: 'object',
|
|
210
|
+
properties: {
|
|
211
|
+
...WHERE_PROP, ...SBX_NAME,
|
|
212
|
+
message: { type: 'string', description: 'Сообщение коммита' },
|
|
213
|
+
paths: { type: 'array', items: { type: 'string' }, description: 'Что добавить (по умолчанию — все изменения)' },
|
|
214
|
+
},
|
|
215
|
+
required: ['message'],
|
|
216
|
+
},
|
|
217
|
+
permission: askScoped(a => 'создать git-коммит' + (a?.message ? ' «' + String(a.message).slice(0, 80) + '»' : '') + ' — изменение системы'),
|
|
218
|
+
async run(args, ctx) {
|
|
219
|
+
const message = String(args?.message ?? '').trim();
|
|
220
|
+
if (!message)
|
|
221
|
+
throw new Error('нужно сообщение коммита');
|
|
222
|
+
const argvAdd = args?.paths?.length
|
|
223
|
+
? ['add', '--', ...args.paths.map(p => checkRepoPath(p))]
|
|
224
|
+
: ['add', '-A'];
|
|
225
|
+
if (args?.where === 'sandbox') {
|
|
226
|
+
return ctxRun('git_commit_sandbox', async () => {
|
|
227
|
+
gitOut(await sbxGit(argvAdd, ctx, args), { what: 'add' });
|
|
228
|
+
return gitOut(await sbxGit(['commit', '-m', message], ctx, args), { what: 'commit', empty: 'коммит создан' });
|
|
229
|
+
})(args, ctx);
|
|
230
|
+
}
|
|
231
|
+
return ctxRun('git_commit', async () => {
|
|
232
|
+
const t0 = Date.now();
|
|
233
|
+
await assertGitWork(ctx);
|
|
234
|
+
gitOut(await workGit(argvAdd, ctx), { what: 'add', empty: '' });
|
|
235
|
+
const r = await workGit(['commit', '-m', message], ctx);
|
|
236
|
+
if (r.timedOut || r.code !== 0)
|
|
237
|
+
return gitOut(r, { what: 'commit' });
|
|
238
|
+
const hash = String((await workGit(['rev-parse', '--short', 'HEAD'], ctx)).stdout || '').trim();
|
|
239
|
+
audit({ tool: 'git_commit', hash, ok: true, ms: Date.now() - t0 }, ctx?.session);
|
|
240
|
+
return gitOut(r, { what: 'commit' }) + (hash ? ' (' + hash + ')' : '');
|
|
241
|
+
})(args, ctx);
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
export const git_push = {
|
|
246
|
+
name: 'git_push',
|
|
247
|
+
risk: 'write',
|
|
248
|
+
outbound: true,
|
|
249
|
+
description: 'Отправить коммиты в удалённый репозиторий (git push). Действие наружу: подтверждение человека каждый раз, «разрешить всегда» не предлагается, субагентам недоступно.',
|
|
250
|
+
parameters: {
|
|
251
|
+
type: 'object',
|
|
252
|
+
properties: {
|
|
253
|
+
...WHERE_PROP, ...SBX_NAME,
|
|
254
|
+
remote: { type: 'string', description: 'Имя remote или URL (по умолчанию origin)' },
|
|
255
|
+
ref: { type: 'string', description: 'Что отправлять (по умолчанию HEAD — текущая ветка)' },
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
permission: askEach(a => 'отправить коммиты наружу в git («' + String(a?.remote || 'origin') + '», ' + String(a?.ref || 'HEAD') + ') — код покидает сервер'),
|
|
259
|
+
async run(args, ctx) {
|
|
260
|
+
const remote = checkGitRemote(args?.remote || 'origin');
|
|
261
|
+
const ref = checkGitRef(args?.ref || 'HEAD', 'ref');
|
|
262
|
+
const argv = ['push', remote, ref];
|
|
263
|
+
if (args?.where === 'sandbox')
|
|
264
|
+
return ctxRun('git_push_sandbox', () => sbxGit(argv, ctx, args)
|
|
265
|
+
.then(r => gitOut(r, { what: 'push', empty: 'отправлено (без вывода)' })))(args, ctx);
|
|
266
|
+
return ctxRun('git_push', async () => {
|
|
267
|
+
const t0 = Date.now();
|
|
268
|
+
await assertGitWork(ctx);
|
|
269
|
+
const r = await workGit(argv, ctx);
|
|
270
|
+
audit({ tool: 'git_push', remote, ref, ok: r.code === 0, ms: Date.now() - t0 }, ctx?.session);
|
|
271
|
+
return gitOut(r, { what: 'push', empty: 'отправлено (без вывода)' });
|
|
272
|
+
})(args, ctx);
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
export const devGitTools = [git_status, git_diff, git_log, git_show, git_blame, git_branch, git_commit, git_push];
|