odant-work 1.0.40 → 1.0.42
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 +26 -26
- 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 +156 -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 +12 -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/halogen.js +402 -10
- package/sources/modules/trainer/index.js +83 -0
- package/sources/modules/trainer/local-engine.js +321 -55
- package/sources/modules/trainer/worker/local_infer_worker.py +34 -12
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
/** Инвентаризация локальной сети; экспортируется через guarded() только администраторам WORK. */
|
|
2
|
-
import os from 'node:os';
|
|
3
|
-
import dns from 'node:dns';
|
|
4
|
-
import { loadConfig,
|
|
5
|
-
import { localNets } from '../../lan/subnet.js';
|
|
6
|
-
import { lanRequest } from '../../lan/net.js';
|
|
7
|
-
import { scan, probe } from '../../lan/scan.js';
|
|
8
|
-
import { discover } from '../../lan/discovery.js';
|
|
9
|
-
import * as candidates from '../../lan/store.js';
|
|
10
|
-
import { register } from '../../lan/register.js';
|
|
11
|
-
|
|
12
|
-
const schema = (properties = {}, required = []) => ({ type: 'object', properties, required });
|
|
13
|
-
|
|
14
|
-
export const netTools = [
|
|
15
|
-
{ name: 'net_info', readonly: true, description: 'Интерфейсы, разрешённые локальные подсети, маршруты/DNS и таблица соседей сервера WORK', parameters: schema(),
|
|
16
|
-
async run(_args, ctx) {
|
|
17
|
-
const info = IS_WIN
|
|
18
|
-
? await powershell('Get-NetIPConfiguration | Format-List InterfaceAlias,IPv4Address,IPv4DefaultGateway,DNSServer; Get-NetNeighbor -AddressFamily IPv4 | Select-Object IPAddress,LinkLayerAddress,State', { timeout: 15000, signal: ctx.signal })
|
|
19
|
-
: await run(process.platform === 'darwin' ? 'ifconfig' : 'ip', process.platform === 'darwin' ? [] : ['address'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message }));
|
|
20
|
-
const neighbors = !IS_WIN ? await run(process.platform === 'darwin' ? 'arp' : 'ip', process.platform === 'darwin' ? ['-a'] : ['neigh'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message })) : null;
|
|
21
|
-
const routes = !IS_WIN ? await run(process.platform === 'darwin' ? 'netstat' : 'ip', process.platform === 'darwin' ? ['-rn'] : ['route'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message })) : null;
|
|
22
|
-
return { hostname: os.hostname(), interfaces: os.networkInterfaces(), dns: dns.getServers(), subnets: localNets(), configured: loadConfig().subnets, info: info.stdout || info.stderr,
|
|
23
|
-
neighbors: neighbors?.stdout || neighbors?.stderr, routes: routes?.stdout || routes?.stderr };
|
|
24
|
-
} },
|
|
25
|
-
// F27: объявления устройств (mDNS TXT, SSDP XML, имена) — чужой текст: <untrusted> + заражение
|
|
26
|
-
{ name: 'net_discover', readonly: true, untrusted: true, concurrent: false, description: 'Обнаружить устройства через mDNS/DNS-SD, SSDP и WS-Discovery (поисковые multicast-запросы без сканирования портов); имена и описания — со слов самих устройств',
|
|
27
|
-
parameters: schema({ duration: { type: 'integer', description: 'Окно ответов, мс (500–10000)' } }),
|
|
28
|
-
async run(args, ctx) { const res = await discover(loadConfig(), { ...args, signal: ctx.signal }); candidates.merge(res.candidates); return res; } },
|
|
29
|
-
{ name: 'net_scan', permission:
|
|
30
|
-
description: 'TCP-проверка разрешённой подсети (до 1024 хостов), профиль: common/printers/scanners/onec/servers. Открытый порт — предположение, уточни net_probe.',
|
|
31
|
-
parameters: schema({ cidr: { type: 'string' }, profile: { type: 'string', enum: ['common', 'printers', 'scanners', 'onec', 'servers'] }, ports: { type: 'array', items: { type: 'integer' } } }, ['cidr']),
|
|
32
|
-
async run(args, ctx) { const res = await scan(args.cidr, loadConfig(), { ...args, signal: ctx.signal }); candidates.merge(res.candidates); return res; } },
|
|
33
|
-
{ name: 'net_probe', readonly: true, untrusted: true, description: 'Уточнить сервис одного хоста: HTTP, IPP-принтер, eSCL-сканер; для OData 1С передай полный URL публикации',
|
|
34
|
-
parameters: schema({ host: { type: 'string' }, port: { type: 'integer' }, url: { type: 'string' } }, ['host']),
|
|
35
|
-
async run(args, ctx) { const res = await probe(args.host, loadConfig(), { ...args, signal: ctx.signal }); if (res.open) candidates.merge([res]); return res; } },
|
|
36
|
-
{ name: 'net_http', readonly: true, untrusted: true, description: 'GET к устройству в разрешённой локальной сети (до 2 МБ, редиректы не выполняются)',
|
|
37
|
-
parameters: schema({ url: { type: 'string' } }, ['url']),
|
|
38
|
-
async run(args, ctx) { const res = await lanRequest(args.url, loadConfig(), { signal: ctx.signal }); return { status: res.status, headers: res.headers, text: res.body.toString('utf8').slice(0, 20000) }; } },
|
|
39
|
-
{ name: 'net_candidates', readonly: true, untrusted: true, description: 'Найденные устройства и сервисы: id для net_register, адреса, предполагаемый/подтверждённый тип и способ обнаружения (имена — со слов устройств)',
|
|
40
|
-
parameters: schema({ kind: { type: 'string' }, limit: { type: 'integer' } }),
|
|
41
|
-
async run(args) { return Object.values(candidates.load()).filter(c => !args.kind || c.kind === args.kind).sort((a, b) => b.seen - a.seen).slice(0, Math.min(500, Math.max(1, Number(args.limit) || 100))); } },
|
|
42
|
-
{ name: 'net_register', permission:
|
|
43
|
-
description: 'Зарегистрировать найденное устройство в /SERVICES/LAN. После назначения ролей доступны svc_* инструменты: IPP-печать, eSCL-сканирование, OData 1С.',
|
|
44
|
-
parameters: schema({ id: { type: 'string' }, name: { type: 'string' }, kind: { type: 'string', enum: ['printer', 'scanner', 'onec', 'web', 'share', 'sql'] }, endpoint: { type: 'string' } }, ['id']), run: register },
|
|
45
|
-
];
|
|
1
|
+
/** Инвентаризация локальной сети; экспортируется через guarded() только администраторам WORK. */
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import dns from 'node:dns';
|
|
4
|
+
import { loadConfig, askScoped, powershell, run, IS_WIN } from '../system.js';
|
|
5
|
+
import { localNets } from '../../lan/subnet.js';
|
|
6
|
+
import { lanRequest } from '../../lan/net.js';
|
|
7
|
+
import { scan, probe } from '../../lan/scan.js';
|
|
8
|
+
import { discover } from '../../lan/discovery.js';
|
|
9
|
+
import * as candidates from '../../lan/store.js';
|
|
10
|
+
import { register } from '../../lan/register.js';
|
|
11
|
+
|
|
12
|
+
const schema = (properties = {}, required = []) => ({ type: 'object', properties, required });
|
|
13
|
+
|
|
14
|
+
export const netTools = [
|
|
15
|
+
{ name: 'net_info', readonly: true, description: 'Интерфейсы, разрешённые локальные подсети, маршруты/DNS и таблица соседей сервера WORK', parameters: schema(),
|
|
16
|
+
async run(_args, ctx) {
|
|
17
|
+
const info = IS_WIN
|
|
18
|
+
? await powershell('Get-NetIPConfiguration | Format-List InterfaceAlias,IPv4Address,IPv4DefaultGateway,DNSServer; Get-NetNeighbor -AddressFamily IPv4 | Select-Object IPAddress,LinkLayerAddress,State', { timeout: 15000, signal: ctx.signal })
|
|
19
|
+
: await run(process.platform === 'darwin' ? 'ifconfig' : 'ip', process.platform === 'darwin' ? [] : ['address'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message }));
|
|
20
|
+
const neighbors = !IS_WIN ? await run(process.platform === 'darwin' ? 'arp' : 'ip', process.platform === 'darwin' ? ['-a'] : ['neigh'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message })) : null;
|
|
21
|
+
const routes = !IS_WIN ? await run(process.platform === 'darwin' ? 'netstat' : 'ip', process.platform === 'darwin' ? ['-rn'] : ['route'], { timeout: 10000, signal: ctx.signal }).catch(e => ({ stderr: e.message })) : null;
|
|
22
|
+
return { hostname: os.hostname(), interfaces: os.networkInterfaces(), dns: dns.getServers(), subnets: localNets(), configured: loadConfig().subnets, info: info.stdout || info.stderr,
|
|
23
|
+
neighbors: neighbors?.stdout || neighbors?.stderr, routes: routes?.stdout || routes?.stderr };
|
|
24
|
+
} },
|
|
25
|
+
// F27: объявления устройств (mDNS TXT, SSDP XML, имена) — чужой текст: <untrusted> + заражение
|
|
26
|
+
{ name: 'net_discover', readonly: true, untrusted: true, concurrent: false, description: 'Обнаружить устройства через mDNS/DNS-SD, SSDP и WS-Discovery (поисковые multicast-запросы без сканирования портов); имена и описания — со слов самих устройств',
|
|
27
|
+
parameters: schema({ duration: { type: 'integer', description: 'Окно ответов, мс (500–10000)' } }),
|
|
28
|
+
async run(args, ctx) { const res = await discover(loadConfig(), { ...args, signal: ctx.signal }); candidates.merge(res.candidates); return res; } },
|
|
29
|
+
{ name: 'net_scan', permission: askScoped(a => 'TCP-проверка локальной сети ' + a.cidr + ' (' + (a.profile || 'common') + ')'),
|
|
30
|
+
description: 'TCP-проверка разрешённой подсети (до 1024 хостов), профиль: common/printers/scanners/onec/servers. Открытый порт — предположение, уточни net_probe.',
|
|
31
|
+
parameters: schema({ cidr: { type: 'string' }, profile: { type: 'string', enum: ['common', 'printers', 'scanners', 'onec', 'servers'] }, ports: { type: 'array', items: { type: 'integer' } } }, ['cidr']),
|
|
32
|
+
async run(args, ctx) { const res = await scan(args.cidr, loadConfig(), { ...args, signal: ctx.signal }); candidates.merge(res.candidates); return res; } },
|
|
33
|
+
{ name: 'net_probe', readonly: true, untrusted: true, description: 'Уточнить сервис одного хоста: HTTP, IPP-принтер, eSCL-сканер; для OData 1С передай полный URL публикации',
|
|
34
|
+
parameters: schema({ host: { type: 'string' }, port: { type: 'integer' }, url: { type: 'string' } }, ['host']),
|
|
35
|
+
async run(args, ctx) { const res = await probe(args.host, loadConfig(), { ...args, signal: ctx.signal }); if (res.open) candidates.merge([res]); return res; } },
|
|
36
|
+
{ name: 'net_http', readonly: true, untrusted: true, description: 'GET к устройству в разрешённой локальной сети (до 2 МБ, редиректы не выполняются)',
|
|
37
|
+
parameters: schema({ url: { type: 'string' } }, ['url']),
|
|
38
|
+
async run(args, ctx) { const res = await lanRequest(args.url, loadConfig(), { signal: ctx.signal }); return { status: res.status, headers: res.headers, text: res.body.toString('utf8').slice(0, 20000) }; } },
|
|
39
|
+
{ name: 'net_candidates', readonly: true, untrusted: true, description: 'Найденные устройства и сервисы: id для net_register, адреса, предполагаемый/подтверждённый тип и способ обнаружения (имена — со слов устройств)',
|
|
40
|
+
parameters: schema({ kind: { type: 'string' }, limit: { type: 'integer' } }),
|
|
41
|
+
async run(args) { return Object.values(candidates.load()).filter(c => !args.kind || c.kind === args.kind).sort((a, b) => b.seen - a.seen).slice(0, Math.min(500, Math.max(1, Number(args.limit) || 100))); } },
|
|
42
|
+
{ name: 'net_register', permission: askScoped(a => 'Зарегистрировать LAN-сервис в WORK: ' + (a.name || a.id)),
|
|
43
|
+
description: 'Зарегистрировать найденное устройство в /SERVICES/LAN. После назначения ролей доступны svc_* инструменты: IPP-печать, eSCL-сканирование, OData 1С.',
|
|
44
|
+
parameters: schema({ id: { type: 'string' }, name: { type: 'string' }, kind: { type: 'string', enum: ['printer', 'scanner', 'onec', 'web', 'share', 'sql'] }, endpoint: { type: 'string' } }, ['id']), run: register },
|
|
45
|
+
];
|
|
@@ -1,169 +1,179 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Система сервера WORK (только админам):
|
|
3
|
-
* os_info, os_processes, os_services — чтение;
|
|
4
|
-
* os_service (start/stop/restart), os_kill, shell, install_package — каждый раз с подтверждением.
|
|
5
|
-
*/
|
|
6
|
-
import os from 'node:os';
|
|
7
|
-
import { clip } from '../util.js';
|
|
8
|
-
import { IS_WIN, checkPath, askEach, run, powershell, psQuote, formatRun, loadConfig } from '../system.js';
|
|
9
|
-
import { size } from './os-files.js';
|
|
10
|
-
|
|
11
|
-
const NAME = /^[\w.@:-]{1,128}$/;
|
|
12
|
-
const PKG = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i;
|
|
13
|
-
|
|
14
|
-
async function disks() {
|
|
15
|
-
try {
|
|
16
|
-
if (IS_WIN) {
|
|
17
|
-
const r = await powershell('Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID,VolumeName,FileSystem,Size,FreeSpace,DriveType | ConvertTo-Json -Compress', { timeout: 20000 });
|
|
18
|
-
const rows = [].concat(JSON.parse(r.stdout || '[]'));
|
|
19
|
-
return rows.map(d => d.DeviceID + ' ' + (d.VolumeName || '') + ' ' + (d.FileSystem || '') + (d.Size ? ' свободно ' + size(d.FreeSpace) + ' из ' + size(d.Size) : '') + (d.DriveType === 4 ? ' (сетевой)' : ''));
|
|
20
|
-
}
|
|
21
|
-
const r = await run('df', ['-hP'], { timeout: 10000 });
|
|
22
|
-
return r.stdout.trim().split('\n');
|
|
23
|
-
}
|
|
24
|
-
catch (e) {
|
|
25
|
-
return ['(нет данных: ' + e.message + ')'];
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export const osProcTools = [
|
|
30
|
-
{
|
|
31
|
-
name: 'os_info',
|
|
32
|
-
readonly: true,
|
|
33
|
-
description: 'Сведения о сервере WORK: ОС, процессор, память, диски (в т.ч. сетевые), сетевые интерфейсы, аптайм, текущий пользователь процесса.',
|
|
34
|
-
parameters: { type: 'object', properties: {} },
|
|
35
|
-
async run() {
|
|
36
|
-
const nets = Object.entries(os.networkInterfaces()).flatMap(([n, list]) => (list || []).filter(a => !a.internal).map(a => n + ': ' + a.address + (a.cidr ? ' (' + a.cidr + ')' : '') + ' ' + a.mac));
|
|
37
|
-
const cpus = os.cpus();
|
|
38
|
-
return [
|
|
39
|
-
'ОС: ' + os.type() + ' ' + os.release() + ' (' + process.platform + ' ' + os.arch() + ')' + (os.version ? ', ' + os.version() : ''),
|
|
40
|
-
'Имя: ' + os.hostname() + ', пользователь процесса: ' + os.userInfo().username + ', домашняя папка: ' + os.homedir(),
|
|
41
|
-
'CPU: ' + (cpus[0]?.model || '?') + ' × ' + cpus.length,
|
|
42
|
-
'Память: свободно ' + size(os.freemem()) + ' из ' + size(os.totalmem()),
|
|
43
|
-
'Аптайм: ' + Math.round(os.uptime() / 3600) + ' ч; Node ' + process.version + '; WORK: ' + process.cwd(),
|
|
44
|
-
'Сеть:\n' + nets.map(s => ' ' + s).join('\n'),
|
|
45
|
-
'Диски:\n' + (await disks()).map(s => ' ' + s).join('\n'),
|
|
46
|
-
].join('\n');
|
|
47
|
-
},
|
|
48
|
-
},
|
|
49
|
-
{
|
|
50
|
-
name: 'os_processes',
|
|
51
|
-
readonly: true,
|
|
52
|
-
description: 'Процессы сервера (по загрузке CPU/памяти), фильтр по имени.',
|
|
53
|
-
parameters: { type: 'object', properties: { filter: { type: 'string', description: 'Часть имени процесса' }, limit: { type: 'integer' } } },
|
|
54
|
-
async run(args) {
|
|
55
|
-
const limit = Math.min(200, Number(args.limit) || 40);
|
|
56
|
-
const f = String(args.filter || '').toLowerCase();
|
|
57
|
-
if (IS_WIN) {
|
|
58
|
-
const r = await powershell('Get-Process | Sort-Object WS -Descending | Select-Object Id,ProcessName,@{n="CPU";e={[math]::Round($_.CPU,1)}},@{n="MB";e={[math]::Round($_.WS/1MB)}} | ConvertTo-Json -Compress', { timeout: 20000 });
|
|
59
|
-
const rows = [].concat(JSON.parse(r.stdout || '[]')).filter(p => !f || String(p.ProcessName).toLowerCase().includes(f)).slice(0, limit);
|
|
60
|
-
return 'PID\tМБ\tCPU,с\tИмя\n' + rows.map(p => p.Id + '\t' + p.MB + '\t' + (p.CPU ?? '') + '\t' + p.ProcessName).join('\n');
|
|
61
|
-
}
|
|
62
|
-
const r = await run('ps', ['-eo', 'pid,rss,pcpu,comm'], { timeout: 10000 });
|
|
63
|
-
const rows = r.stdout.trim().split('\n').slice(1).map(l => l.trim().split(/\s+/))
|
|
64
|
-
.filter(c => !f || c.slice(3).join(' ').toLowerCase().includes(f))
|
|
65
|
-
.sort((a, b) => Number(b[1]) - Number(a[1])).slice(0, limit);
|
|
66
|
-
return 'PID\tМБ\tCPU%\tИмя\n' + rows.map(c => c[0] + '\t' + Math.round(Number(c[1]) / 1024) + '\t' + c[2] + '\t' + c.slice(3).join(' ')).join('\n');
|
|
67
|
-
},
|
|
68
|
-
},
|
|
69
|
-
{
|
|
70
|
-
name: 'os_services',
|
|
71
|
-
readonly: true,
|
|
72
|
-
description: 'Службы сервера (Windows-службы / systemd / launchd): имя, состояние, фильтр по имени.',
|
|
73
|
-
parameters: { type: 'object', properties: { filter: { type: 'string' } } },
|
|
74
|
-
async run(args) {
|
|
75
|
-
const f = String(args.filter || '').toLowerCase();
|
|
76
|
-
let lines;
|
|
77
|
-
if (IS_WIN) {
|
|
78
|
-
const r = await powershell('Get-Service | Select-Object Name,DisplayName,@{n="S";e={"$($_.Status)"}},@{n="T";e={"$($_.StartType)"}} | ConvertTo-Json -Compress', { timeout: 30000 });
|
|
79
|
-
lines = [].concat(JSON.parse(r.stdout || '[]')).map(s => s.Name + '\t' + s.S + '\t' + s.T + '\t' + s.DisplayName);
|
|
80
|
-
}
|
|
81
|
-
else if (process.platform === 'darwin')
|
|
82
|
-
lines = (await run('launchctl', ['list'], { timeout: 10000 })).stdout.trim().split('\n');
|
|
83
|
-
else
|
|
84
|
-
lines = (await run('systemctl', ['list-units', '--type=service', '--all', '--no-pager', '--plain', '--no-legend'], { timeout: 15000 })).stdout.trim().split('\n');
|
|
85
|
-
lines = lines.filter(l => !f || l.toLowerCase().includes(f));
|
|
86
|
-
return clip(lines.join('\n') || 'ничего не найдено', 20000);
|
|
87
|
-
},
|
|
88
|
-
},
|
|
89
|
-
{
|
|
90
|
-
name: 'os_service',
|
|
91
|
-
permission:
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
},
|
|
168
|
-
|
|
169
|
-
]
|
|
1
|
+
/**
|
|
2
|
+
* Система сервера WORK (только админам):
|
|
3
|
+
* os_info, os_processes, os_services — чтение;
|
|
4
|
+
* os_service (start/stop/restart), os_kill, shell, install_package — каждый раз с подтверждением.
|
|
5
|
+
*/
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import { clip } from '../util.js';
|
|
8
|
+
import { IS_WIN, checkPath, askEach, askScoped, run, powershell, psQuote, formatRun, loadConfig } from '../system.js';
|
|
9
|
+
import { size } from './os-files.js';
|
|
10
|
+
|
|
11
|
+
const NAME = /^[\w.@:-]{1,128}$/;
|
|
12
|
+
const PKG = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i;
|
|
13
|
+
|
|
14
|
+
async function disks() {
|
|
15
|
+
try {
|
|
16
|
+
if (IS_WIN) {
|
|
17
|
+
const r = await powershell('Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID,VolumeName,FileSystem,Size,FreeSpace,DriveType | ConvertTo-Json -Compress', { timeout: 20000 });
|
|
18
|
+
const rows = [].concat(JSON.parse(r.stdout || '[]'));
|
|
19
|
+
return rows.map(d => d.DeviceID + ' ' + (d.VolumeName || '') + ' ' + (d.FileSystem || '') + (d.Size ? ' свободно ' + size(d.FreeSpace) + ' из ' + size(d.Size) : '') + (d.DriveType === 4 ? ' (сетевой)' : ''));
|
|
20
|
+
}
|
|
21
|
+
const r = await run('df', ['-hP'], { timeout: 10000 });
|
|
22
|
+
return r.stdout.trim().split('\n');
|
|
23
|
+
}
|
|
24
|
+
catch (e) {
|
|
25
|
+
return ['(нет данных: ' + e.message + ')'];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const osProcTools = [
|
|
30
|
+
{
|
|
31
|
+
name: 'os_info',
|
|
32
|
+
readonly: true,
|
|
33
|
+
description: 'Сведения о сервере WORK: ОС, процессор, память, диски (в т.ч. сетевые), сетевые интерфейсы, аптайм, текущий пользователь процесса.',
|
|
34
|
+
parameters: { type: 'object', properties: {} },
|
|
35
|
+
async run() {
|
|
36
|
+
const nets = Object.entries(os.networkInterfaces()).flatMap(([n, list]) => (list || []).filter(a => !a.internal).map(a => n + ': ' + a.address + (a.cidr ? ' (' + a.cidr + ')' : '') + ' ' + a.mac));
|
|
37
|
+
const cpus = os.cpus();
|
|
38
|
+
return [
|
|
39
|
+
'ОС: ' + os.type() + ' ' + os.release() + ' (' + process.platform + ' ' + os.arch() + ')' + (os.version ? ', ' + os.version() : ''),
|
|
40
|
+
'Имя: ' + os.hostname() + ', пользователь процесса: ' + os.userInfo().username + ', домашняя папка: ' + os.homedir(),
|
|
41
|
+
'CPU: ' + (cpus[0]?.model || '?') + ' × ' + cpus.length,
|
|
42
|
+
'Память: свободно ' + size(os.freemem()) + ' из ' + size(os.totalmem()),
|
|
43
|
+
'Аптайм: ' + Math.round(os.uptime() / 3600) + ' ч; Node ' + process.version + '; WORK: ' + process.cwd(),
|
|
44
|
+
'Сеть:\n' + nets.map(s => ' ' + s).join('\n'),
|
|
45
|
+
'Диски:\n' + (await disks()).map(s => ' ' + s).join('\n'),
|
|
46
|
+
].join('\n');
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: 'os_processes',
|
|
51
|
+
readonly: true,
|
|
52
|
+
description: 'Процессы сервера (по загрузке CPU/памяти), фильтр по имени.',
|
|
53
|
+
parameters: { type: 'object', properties: { filter: { type: 'string', description: 'Часть имени процесса' }, limit: { type: 'integer' } } },
|
|
54
|
+
async run(args) {
|
|
55
|
+
const limit = Math.min(200, Number(args.limit) || 40);
|
|
56
|
+
const f = String(args.filter || '').toLowerCase();
|
|
57
|
+
if (IS_WIN) {
|
|
58
|
+
const r = await powershell('Get-Process | Sort-Object WS -Descending | Select-Object Id,ProcessName,@{n="CPU";e={[math]::Round($_.CPU,1)}},@{n="MB";e={[math]::Round($_.WS/1MB)}} | ConvertTo-Json -Compress', { timeout: 20000 });
|
|
59
|
+
const rows = [].concat(JSON.parse(r.stdout || '[]')).filter(p => !f || String(p.ProcessName).toLowerCase().includes(f)).slice(0, limit);
|
|
60
|
+
return 'PID\tМБ\tCPU,с\tИмя\n' + rows.map(p => p.Id + '\t' + p.MB + '\t' + (p.CPU ?? '') + '\t' + p.ProcessName).join('\n');
|
|
61
|
+
}
|
|
62
|
+
const r = await run('ps', ['-eo', 'pid,rss,pcpu,comm'], { timeout: 10000 });
|
|
63
|
+
const rows = r.stdout.trim().split('\n').slice(1).map(l => l.trim().split(/\s+/))
|
|
64
|
+
.filter(c => !f || c.slice(3).join(' ').toLowerCase().includes(f))
|
|
65
|
+
.sort((a, b) => Number(b[1]) - Number(a[1])).slice(0, limit);
|
|
66
|
+
return 'PID\tМБ\tCPU%\tИмя\n' + rows.map(c => c[0] + '\t' + Math.round(Number(c[1]) / 1024) + '\t' + c[2] + '\t' + c.slice(3).join(' ')).join('\n');
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
name: 'os_services',
|
|
71
|
+
readonly: true,
|
|
72
|
+
description: 'Службы сервера (Windows-службы / systemd / launchd): имя, состояние, фильтр по имени.',
|
|
73
|
+
parameters: { type: 'object', properties: { filter: { type: 'string' } } },
|
|
74
|
+
async run(args) {
|
|
75
|
+
const f = String(args.filter || '').toLowerCase();
|
|
76
|
+
let lines;
|
|
77
|
+
if (IS_WIN) {
|
|
78
|
+
const r = await powershell('Get-Service | Select-Object Name,DisplayName,@{n="S";e={"$($_.Status)"}},@{n="T";e={"$($_.StartType)"}} | ConvertTo-Json -Compress', { timeout: 30000 });
|
|
79
|
+
lines = [].concat(JSON.parse(r.stdout || '[]')).map(s => s.Name + '\t' + s.S + '\t' + s.T + '\t' + s.DisplayName);
|
|
80
|
+
}
|
|
81
|
+
else if (process.platform === 'darwin')
|
|
82
|
+
lines = (await run('launchctl', ['list'], { timeout: 10000 })).stdout.trim().split('\n');
|
|
83
|
+
else
|
|
84
|
+
lines = (await run('systemctl', ['list-units', '--type=service', '--all', '--no-pager', '--plain', '--no-legend'], { timeout: 15000 })).stdout.trim().split('\n');
|
|
85
|
+
lines = lines.filter(l => !f || l.toLowerCase().includes(f));
|
|
86
|
+
return clip(lines.join('\n') || 'ничего не найдено', 20000);
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
name: 'os_service',
|
|
91
|
+
permission: askScoped(a => (a?.action || '?') + ' службы «' + a?.name + '» на сервере'),
|
|
92
|
+
approvalScope: a => ({
|
|
93
|
+
key: 'os_service:' + String(a?.name || '*').trim().toLowerCase(),
|
|
94
|
+
label: 'действия со службой «' + String(a?.name || '*') + '» в этой задаче',
|
|
95
|
+
buttonLabel: 'Разрешить подобные',
|
|
96
|
+
}),
|
|
97
|
+
description: 'Запустить, остановить или перезапустить службу сервера.',
|
|
98
|
+
parameters: {
|
|
99
|
+
type: 'object',
|
|
100
|
+
properties: { name: { type: 'string' }, action: { type: 'string', enum: ['start', 'stop', 'restart', 'status'] } },
|
|
101
|
+
required: ['name', 'action'],
|
|
102
|
+
},
|
|
103
|
+
async run(args, ctx) {
|
|
104
|
+
if (!NAME.test(String(args.name)))
|
|
105
|
+
throw new Error('недопустимое имя службы');
|
|
106
|
+
const a = String(args.action);
|
|
107
|
+
if (!['start', 'stop', 'restart', 'status'].includes(a))
|
|
108
|
+
throw new Error('недопустимая операция службы');
|
|
109
|
+
let r;
|
|
110
|
+
if (IS_WIN) {
|
|
111
|
+
const cmd = { start: 'Start-Service', stop: 'Stop-Service', restart: 'Restart-Service', status: 'Get-Service' }[a];
|
|
112
|
+
r = await powershell(cmd + ' -Name ' + psQuote(args.name) + (a === 'status' ? ' | Format-List Name,Status,StartType' : ' -PassThru | Format-List Name,Status'), { timeout: 120000, signal: ctx?.signal });
|
|
113
|
+
}
|
|
114
|
+
else
|
|
115
|
+
r = await run('systemctl', [a, String(args.name), '--no-pager'], { timeout: 120000, signal: ctx?.signal });
|
|
116
|
+
return formatRun(r);
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: 'os_kill',
|
|
121
|
+
permission: askEach(a => 'завершить процесс PID ' + a?.pid + ' на сервере'),
|
|
122
|
+
description: 'Завершить процесс сервера по PID.',
|
|
123
|
+
parameters: { type: 'object', properties: { pid: { type: 'integer' }, force: { type: 'boolean' } }, required: ['pid'] },
|
|
124
|
+
async run(args) {
|
|
125
|
+
const pid = Number(args.pid);
|
|
126
|
+
if (!Number.isInteger(pid) || pid <= 4)
|
|
127
|
+
throw new Error('недопустимый PID');
|
|
128
|
+
if (pid === process.pid)
|
|
129
|
+
throw new Error('это процесс самого WORK');
|
|
130
|
+
process.kill(pid, args.force ? 'SIGKILL' : 'SIGTERM');
|
|
131
|
+
return 'сигнал отправлен процессу ' + pid;
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
name: 'shell',
|
|
136
|
+
permission: askScoped(a => 'команда на сервере' + (a?.reason ? ' (' + a.reason + ')' : '') + ':\n' + a?.command),
|
|
137
|
+
description: 'Выполнить команду на сервере WORK: PowerShell на Windows, sh на Linux/macOS. Команды требуют подтверждения человека (для безопасного чтения/проверок и повторяющихся утилит можно выдать общее разрешение в задаче). Предпочитай специальные os_*/net_* инструменты; shell — когда их не хватает.',
|
|
138
|
+
parameters: {
|
|
139
|
+
type: 'object',
|
|
140
|
+
properties: {
|
|
141
|
+
command: { type: 'string', description: 'Команда (скрипт)' },
|
|
142
|
+
cwd: { type: 'string', description: 'Рабочая папка ОС (по умолчанию домашняя)' },
|
|
143
|
+
timeout: { type: 'integer', description: 'Секунд (по умолчанию 60, максимум 600)' },
|
|
144
|
+
reason: { type: 'string', description: 'Зачем — для подтверждения' },
|
|
145
|
+
},
|
|
146
|
+
required: ['command'],
|
|
147
|
+
},
|
|
148
|
+
async run(args, ctx) {
|
|
149
|
+
if (loadConfig().shell === 'off')
|
|
150
|
+
throw new Error('shell выключен (#system/os.json shell:"off")');
|
|
151
|
+
const cwd = args.cwd ? checkPath(args.cwd) : os.homedir();
|
|
152
|
+
const timeout = Math.min(600, Math.max(1, Number(args.timeout) || 60)) * 1000;
|
|
153
|
+
const cmd = String(args.command);
|
|
154
|
+
const r = IS_WIN
|
|
155
|
+
? await powershell(cmd, { cwd, timeout, signal: ctx?.signal })
|
|
156
|
+
: await run('/bin/sh', ['-c', cmd], { cwd, timeout, signal: ctx?.signal });
|
|
157
|
+
return formatRun(r);
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
name: 'install_package',
|
|
162
|
+
permission: askScoped(a => 'установить npm-пакет в WORK: ' + a?.name + (a?.reason ? ' — ' + a.reason : '')),
|
|
163
|
+
approvalScope: () => ({
|
|
164
|
+
key: 'install_package',
|
|
165
|
+
label: 'установка npm-пакетов в этой задаче',
|
|
166
|
+
buttonLabel: 'Разрешить в задаче',
|
|
167
|
+
}),
|
|
168
|
+
description: 'Установить npm-пакет в WORK (драйверы SQL и т.п., по мере необходимости): npm install --save.',
|
|
169
|
+
parameters: { type: 'object', properties: { name: { type: 'string', description: 'Пакет, например pg или mssql@11' }, reason: { type: 'string' } }, required: ['name'] },
|
|
170
|
+
async run(args, ctx) {
|
|
171
|
+
const name = String(args.name).trim();
|
|
172
|
+
if (!PKG.test(name))
|
|
173
|
+
throw new Error('недопустимое имя пакета');
|
|
174
|
+
const npm = IS_WIN ? 'npm.cmd' : 'npm';
|
|
175
|
+
const r = await run(npm, ['install', name, '--save', '--no-audit', '--no-fund'], { cwd: process.cwd(), timeout: 300000, signal: ctx?.signal, shell: IS_WIN });
|
|
176
|
+
return formatRun(r, 4000);
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
];
|