odant-work 1.0.102 → 1.0.104

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.
Files changed (56) hide show
  1. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/agent/$handler/class.js +11 -1
  2. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/messengers/$handler/class.js +11 -1
  3. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/settings/$handler/class.js +292 -0
  4. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/skills/$handler/class.js +11 -1
  5. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
  6. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +24 -2
  7. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +14 -11
  8. package/$server/$folder/$file/$html/handlers/preview/$handler/preview.js +7 -0
  9. package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +11 -0
  10. package/$server/$folder/$file/$md/handlers/preview/$handler/preview.js +29 -8
  11. package/$server/$folder/$file/$office/handlers/preview/$handler/preview.js +6 -0
  12. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +65 -10
  13. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +14 -11
  14. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
  15. package/$server/$folder/$file/$task/handlers/preview/$handler/preview.js +1 -0
  16. package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +9 -0
  17. package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +15 -0
  18. package/$server/$folder/handlers/pages/form/$handler/class.js +10 -2
  19. package/$server/$folder/handlers/pages/form/folder/$handler/class.js +523 -25
  20. package/$server/$folder/lib/consultant/consultant.js +80 -3
  21. package/$server/$folder/lib/explorer/explorer.js +63 -0
  22. package/$server/$folder/lib/tree/tree.js +47 -16
  23. package/NODES/$node/handlers/pages/form/network/$handler/class.js +552 -36
  24. package/autostart.bat +28 -0
  25. package/autostart.sh +17 -0
  26. package/oda/components/icon/icon.js +20 -7
  27. package/package.json +1 -1
  28. package/run.mjs +19 -0
  29. package/scripts/autostart.mjs +281 -0
  30. package/scripts/watchdog.mjs +496 -0
  31. package/sources/client.js +146 -2
  32. package/sources/host/auth-methods.js +2 -0
  33. package/sources/host/auto-updater.js +23 -1
  34. package/sources/host/http-server.js +5 -3
  35. package/sources/host/push.js +43 -14
  36. package/sources/host/websocket.js +69 -3
  37. package/sources/modules/agent/index.js +50 -19
  38. package/sources/modules/agent/permissions.js +4 -2
  39. package/sources/modules/agent/scope.js +72 -5
  40. package/sources/modules/agent/session.js +97 -14
  41. package/sources/modules/agent/tools/work/classes.js +16 -1
  42. package/sources/modules/license/index.js +120 -0
  43. package/sources/modules/nodes/registry.js +57 -7
  44. package/sources/modules/trainer/local-engine.js +22 -9
  45. package/sources/modules/user-profile/user-tokens.js +426 -85
  46. package/sources/server/access/gateway.js +3 -1
  47. package/sources/server/class/feed.js +6 -0
  48. package/sources/server/folder.js +5 -1
  49. package/sources/server/node.js +16 -0
  50. package/sources/server/server.js +59 -1
  51. package/sources/server/user.js +48 -0
  52. package/start.bat +25 -0
  53. package/start.sh +27 -0
  54. package/stop.bat +25 -0
  55. package/stop.sh +16 -0
  56. package/sw.js +3 -11
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Фоновый супервизор (watchdog) процесса ODANT-WORK:
4
+ * - --start : запустить watchdog в фоне (detached, без консоли) и дождаться порта WORK
5
+ * - --stop : поставить маркер ручной остановки (#system/work.stopped), остановить сервис/задачу ОС, watchdog и сервер
6
+ * - --run : цикл супервизора (перезапуск при падении с backoff, поддержка #system/restart-request.json)
7
+ * - --boot : запуск супервизора из автозагрузки ОС (сбрасывает старый маркер остановки)
8
+ * - --status : вывести статус процесса, watchdog и порта
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import net from 'node:net';
13
+ import http from 'node:http';
14
+ import childProcess from 'node:child_process';
15
+ import { pathToFileURL } from 'node:url';
16
+
17
+ export const RESTART_EXIT_CODE = 75;
18
+ const MAX_LOG_BYTES = 10 * 1024 * 1024;
19
+ const BACKOFF_MS = [3000, 5000, 10000, 20000, 30000];
20
+ const HEALTHY_RUN_MS = 60_000;
21
+
22
+ export function resolveWorkRoot(explicitRoot = '') {
23
+ if (explicitRoot)
24
+ return path.resolve(explicitRoot);
25
+ return path.resolve(process.cwd());
26
+ }
27
+
28
+ export function resolveEntryScript(workRoot) {
29
+ const localRun = path.join(workRoot, 'run.mjs');
30
+ if (fs.existsSync(localRun))
31
+ return localRun;
32
+ const pkgRun = path.resolve(import.meta.dirname, '..', 'run.mjs');
33
+ if (fs.existsSync(pkgRun))
34
+ return pkgRun;
35
+ const nmRun = path.join(workRoot, 'node_modules', 'odant-work', 'run.mjs');
36
+ if (fs.existsSync(nmRun))
37
+ return nmRun;
38
+ return localRun;
39
+ }
40
+
41
+ export function resolveWorkPort(workRoot, env = process.env) {
42
+ try {
43
+ const cfgFile = path.join(workRoot, 'config.json');
44
+ if (fs.existsSync(cfgFile)) {
45
+ const cfg = JSON.parse(fs.readFileSync(cfgFile, 'utf8'));
46
+ const p = Number(cfg?.PORT);
47
+ if (Number.isInteger(p) && p > 0)
48
+ return p;
49
+ }
50
+ }
51
+ catch { /* ignore */ }
52
+ const envPort = Number(env.WORK_PORT);
53
+ return (Number.isInteger(envPort) && envPort > 0) ? envPort : 8001;
54
+ }
55
+
56
+ export function pathsOf(workRoot) {
57
+ const sysDir = path.join(workRoot, '#system');
58
+ return {
59
+ sysDir,
60
+ watchdogPid: path.join(sysDir, 'watchdog.pid'),
61
+ runPid: path.join(sysDir, 'run.pid'),
62
+ stoppedMarker: path.join(sysDir, 'work.stopped'),
63
+ restartRequest: path.join(sysDir, 'restart-request.json'),
64
+ logFile: path.join(sysDir, 'work-server.log'),
65
+ };
66
+ }
67
+
68
+ export function isPidAlive(pid) {
69
+ const n = Number(pid);
70
+ if (!Number.isInteger(n) || n <= 0)
71
+ return false;
72
+ try {
73
+ process.kill(n, 0);
74
+ return true;
75
+ }
76
+ catch (err) {
77
+ return err?.code === 'EPERM';
78
+ }
79
+ }
80
+
81
+ export function readPidFile(filePath) {
82
+ try {
83
+ if (!fs.existsSync(filePath))
84
+ return 0;
85
+ const raw = fs.readFileSync(filePath, 'utf8').trim();
86
+ if (!raw)
87
+ return 0;
88
+ if (raw.startsWith('{')) {
89
+ const parsed = JSON.parse(raw);
90
+ const pid = Number(parsed?.pid);
91
+ return Number.isInteger(pid) && pid > 0 ? pid : 0;
92
+ }
93
+ const pid = Number(raw);
94
+ return Number.isInteger(pid) && pid > 0 ? pid : 0;
95
+ }
96
+ catch {
97
+ return 0;
98
+ }
99
+ }
100
+
101
+ export function isPortOpen(port, host = '127.0.0.1', timeoutMs = 1000) {
102
+ return new Promise((resolve) => {
103
+ const sock = net.createConnection({ host, port });
104
+ let done = false;
105
+ const finish = (v) => {
106
+ if (done)
107
+ return;
108
+ done = true;
109
+ try { sock.destroy(); } catch { /* ignore */ }
110
+ resolve(v);
111
+ };
112
+ sock.setTimeout(timeoutMs);
113
+ sock.once('connect', () => finish(true));
114
+ sock.once('timeout', () => finish(false));
115
+ sock.once('error', () => finish(false));
116
+ });
117
+ }
118
+
119
+ function checkHttpReady(port, host = '127.0.0.1', timeoutMs = 1500) {
120
+ return new Promise((resolve) => {
121
+ const req = http.get({ host, port, path: '/favicon.ico', timeout: timeoutMs }, (res) => {
122
+ res.resume();
123
+ resolve(res.statusCode > 0 && res.statusCode < 500);
124
+ });
125
+ req.on('timeout', () => { req.destroy(); resolve(false); });
126
+ req.on('error', () => resolve(false));
127
+ });
128
+ }
129
+
130
+ function rotateLogIfNeeded(logFile) {
131
+ try {
132
+ if (!fs.existsSync(logFile))
133
+ return;
134
+ const st = fs.statSync(logFile);
135
+ if (st.size < MAX_LOG_BYTES)
136
+ return;
137
+ const prev = logFile + '.1';
138
+ try { fs.rmSync(prev, { force: true }); } catch { /* ignore */ }
139
+ fs.renameSync(logFile, prev);
140
+ }
141
+ catch { /* ignore */ }
142
+ }
143
+
144
+ function appendLog(logFile, msg) {
145
+ try {
146
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
147
+ rotateLogIfNeeded(logFile);
148
+ fs.appendFileSync(logFile, `[${new Date().toISOString()}] ${msg}\n`, 'utf8');
149
+ }
150
+ catch { /* ignore */ }
151
+ }
152
+
153
+ function listPortListeningPids(port) {
154
+ const outPids = new Set();
155
+ if (!port)
156
+ return outPids;
157
+ try {
158
+ if (process.platform === 'win32') {
159
+ const out = childProcess.execSync(`netstat -ano | findstr :${port}`, {
160
+ encoding: 'utf8',
161
+ stdio: ['ignore', 'pipe', 'ignore'],
162
+ });
163
+ for (const line of out.split(/\r?\n/)) {
164
+ const m = line.trim().match(new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)$`, 'i'));
165
+ const pid = m ? Number(m[1]) : 0;
166
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
167
+ outPids.add(pid);
168
+ }
169
+ }
170
+ else {
171
+ const cmds = [
172
+ `lsof -tiTCP:${port} -sTCP:LISTEN`,
173
+ `fuser ${port}/tcp`,
174
+ ];
175
+ for (const cmd of cmds) {
176
+ try {
177
+ const out = childProcess.execSync(cmd, {
178
+ encoding: 'utf8',
179
+ stdio: ['ignore', 'pipe', 'ignore'],
180
+ });
181
+ for (const tok of out.split(/\s+/)) {
182
+ const pid = Number(tok.trim());
183
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
184
+ outPids.add(pid);
185
+ }
186
+ if (outPids.size)
187
+ break;
188
+ }
189
+ catch { /* try next */ }
190
+ }
191
+ }
192
+ }
193
+ catch { /* ignore */ }
194
+ return outPids;
195
+ }
196
+
197
+ async function terminatePid(pid, timeoutMs = 5000) {
198
+ if (!isPidAlive(pid) || pid === process.pid)
199
+ return true;
200
+ try {
201
+ process.kill(pid, 'SIGTERM');
202
+ }
203
+ catch { /* ignore */ }
204
+ const deadline = Date.now() + timeoutMs;
205
+ while (Date.now() < deadline) {
206
+ if (!isPidAlive(pid))
207
+ return true;
208
+ await new Promise(r => setTimeout(r, 150));
209
+ }
210
+ try {
211
+ if (process.platform === 'win32')
212
+ childProcess.execSync(`taskkill /PID ${pid} /T /F`, { stdio: 'ignore' });
213
+ else
214
+ process.kill(pid, 'SIGKILL');
215
+ }
216
+ catch { /* ignore */ }
217
+ return !isPidAlive(pid);
218
+ }
219
+
220
+ function stopSystemAutostartUnitIfRunning() {
221
+ try {
222
+ if (process.platform === 'linux' && fs.existsSync('/run/systemd/system')) {
223
+ for (const cmd of [
224
+ 'systemctl is-active --quiet odant-work && systemctl stop odant-work',
225
+ 'systemctl --user is-active --quiet odant-work && systemctl --user stop odant-work',
226
+ ]) {
227
+ try { childProcess.execSync(cmd, { stdio: 'ignore' }); } catch { /* ignore */ }
228
+ }
229
+ }
230
+ else if (process.platform === 'win32') {
231
+ try {
232
+ childProcess.execSync('schtasks /End /TN "ODANT-WORK"', { stdio: 'ignore' });
233
+ }
234
+ catch { /* ignore */ }
235
+ }
236
+ }
237
+ catch { /* ignore */ }
238
+ }
239
+
240
+ export function backoffForAttempt(attempt) {
241
+ const idx = Math.max(0, Math.min(BACKOFF_MS.length - 1, attempt));
242
+ return BACKOFF_MS[idx];
243
+ }
244
+
245
+ export async function runSupervisor({ workRoot = resolveWorkRoot(), boot = false } = {}) {
246
+ const p = pathsOf(workRoot);
247
+ fs.mkdirSync(p.sysDir, { recursive: true });
248
+
249
+ const existingWatchdog = readPidFile(p.watchdogPid);
250
+ if (existingWatchdog && existingWatchdog !== process.pid && isPidAlive(existingWatchdog)) {
251
+ appendLog(p.logFile, `[watchdog] уже запущен (pid=${existingWatchdog}), дубликат завершён.`);
252
+ return 0;
253
+ }
254
+
255
+ if (boot || !fs.existsSync(p.stoppedMarker)) {
256
+ try { fs.rmSync(p.stoppedMarker, { force: true }); } catch { /* ignore */ }
257
+ }
258
+ try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
259
+
260
+ fs.writeFileSync(p.watchdogPid, JSON.stringify({
261
+ pid: process.pid,
262
+ cwd: workRoot,
263
+ startedAt: new Date().toISOString(),
264
+ }), 'utf8');
265
+
266
+ const cleanupPidFile = () => {
267
+ try {
268
+ if (readPidFile(p.watchdogPid) === process.pid)
269
+ fs.rmSync(p.watchdogPid, { force: true });
270
+ }
271
+ catch { /* ignore */ }
272
+ };
273
+
274
+ let currentChild = null;
275
+ let stopping = false;
276
+ const handleSignal = (sig) => {
277
+ stopping = true;
278
+ appendLog(p.logFile, `[watchdog] получен сигнал ${sig}, остановка сервера.`);
279
+ try {
280
+ fs.writeFileSync(p.stoppedMarker, JSON.stringify({ pid: process.pid, reason: sig, time: Date.now() }), 'utf8');
281
+ }
282
+ catch { /* ignore */ }
283
+ if (currentChild && !currentChild.killed) {
284
+ try { currentChild.kill('SIGTERM'); } catch { /* ignore */ }
285
+ }
286
+ };
287
+ process.on('SIGINT', () => handleSignal('SIGINT'));
288
+ process.on('SIGTERM', () => handleSignal('SIGTERM'));
289
+
290
+ const entryScript = resolveEntryScript(workRoot);
291
+ let nextExtraEnv = {};
292
+ let attempt = 0;
293
+
294
+ try {
295
+ while (!stopping) {
296
+ if (fs.existsSync(p.stoppedMarker)) {
297
+ appendLog(p.logFile, '[watchdog] найден маркер ручной остановки work.stopped, выход.');
298
+ break;
299
+ }
300
+
301
+ rotateLogIfNeeded(p.logFile);
302
+ const logFd = fs.openSync(p.logFile, 'a');
303
+ const startedAt = Date.now();
304
+ const childEnv = {
305
+ ...process.env,
306
+ ...nextExtraEnv,
307
+ WORK_WATCHDOG: '1',
308
+ };
309
+ delete childEnv.NODE_OPTIONS;
310
+ nextExtraEnv = {};
311
+
312
+ appendLog(p.logFile, `[watchdog] старт сервера: ${entryScript} (attempt=${attempt})`);
313
+
314
+ let exitCode = 0;
315
+ let exitSignal = null;
316
+ try {
317
+ await new Promise((resolve) => {
318
+ const child = childProcess.spawn(process.execPath, [entryScript], {
319
+ cwd: workRoot,
320
+ env: childEnv,
321
+ windowsHide: true,
322
+ stdio: ['ignore', logFd, logFd],
323
+ });
324
+ currentChild = child;
325
+ child.once('exit', (code, sig) => {
326
+ exitCode = code ?? 1;
327
+ exitSignal = sig || null;
328
+ currentChild = null;
329
+ resolve();
330
+ });
331
+ child.once('error', (err) => {
332
+ appendLog(p.logFile, `[watchdog] ошибка запуска child: ${err?.message || err}`);
333
+ exitCode = 1;
334
+ currentChild = null;
335
+ resolve();
336
+ });
337
+ });
338
+ }
339
+ finally {
340
+ try { fs.closeSync(logFd); } catch { /* ignore */ }
341
+ }
342
+
343
+ if (stopping || fs.existsSync(p.stoppedMarker)) {
344
+ appendLog(p.logFile, '[watchdog] остановка подтверждена (work.stopped).');
345
+ break;
346
+ }
347
+
348
+ // Штатный запрос перезапуска из UI (restart_normal / version_update_restart)
349
+ if (fs.existsSync(p.restartRequest)) {
350
+ try {
351
+ const req = JSON.parse(fs.readFileSync(p.restartRequest, 'utf8'));
352
+ if (req?.env && typeof req.env === 'object')
353
+ nextExtraEnv = req.env;
354
+ }
355
+ catch { /* ignore */ }
356
+ try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
357
+ attempt = 0;
358
+ appendLog(p.logFile, `[watchdog] штатный перезапуск (code=${exitCode}, sig=${exitSignal || '-'})`);
359
+ await new Promise(r => setTimeout(r, 400));
360
+ continue;
361
+ }
362
+
363
+ if (exitCode === RESTART_EXIT_CODE) {
364
+ attempt = 0;
365
+ appendLog(p.logFile, `[watchdog] перезапуск по коду ${RESTART_EXIT_CODE}`);
366
+ await new Promise(r => setTimeout(r, 400));
367
+ continue;
368
+ }
369
+
370
+ // Если сервер вышел чисто с кодом 0 без restart-request (например, другой процесс перехватил порт или SIGTERM)
371
+ if (exitCode === 0 && !exitSignal) {
372
+ appendLog(p.logFile, '[watchdog] сервер завершился с кодом 0, watchdog останавливается.');
373
+ break;
374
+ }
375
+
376
+ const livedMs = Date.now() - startedAt;
377
+ if (livedMs >= HEALTHY_RUN_MS)
378
+ attempt = 0;
379
+ const waitMs = backoffForAttempt(attempt);
380
+ attempt++;
381
+ appendLog(p.logFile, `[watchdog] аварийное завершение (code=${exitCode}, sig=${exitSignal || '-'}, uptime=${Math.round(livedMs / 1000)}с). Перезапуск через ${Math.round(waitMs / 1000)}с...`);
382
+ await new Promise(r => setTimeout(r, waitMs));
383
+ }
384
+ }
385
+ finally {
386
+ cleanupPidFile();
387
+ }
388
+ return 0;
389
+ }
390
+
391
+ export async function startDetached({ workRoot = resolveWorkRoot(), timeoutMs = 35_000 } = {}) {
392
+ const p = pathsOf(workRoot);
393
+ const port = resolveWorkPort(workRoot);
394
+ fs.mkdirSync(p.sysDir, { recursive: true });
395
+ try { fs.rmSync(p.stoppedMarker, { force: true }); } catch { /* ignore */ }
396
+
397
+ const existingWatchdog = readPidFile(p.watchdogPid);
398
+ const existingServer = readPidFile(p.runPid);
399
+ if (existingWatchdog && isPidAlive(existingWatchdog) && existingServer && isPidAlive(existingServer) && await isPortOpen(port)) {
400
+ console.log(`ODANT-WORK уже запущен: http://localhost:${port}/ (watchdog PID ${existingWatchdog}, сервер PID ${existingServer})`);
401
+ return { alreadyRunning: true, port, watchdogPid: existingWatchdog, serverPid: existingServer };
402
+ }
403
+
404
+ const watchdogScript = path.resolve(import.meta.dirname, 'watchdog.mjs');
405
+ const child = childProcess.spawn(process.execPath, [watchdogScript, '--run', `--root=${workRoot}`], {
406
+ cwd: workRoot,
407
+ env: { ...process.env, WORK_WATCHDOG: '1' },
408
+ detached: true,
409
+ windowsHide: true,
410
+ stdio: 'ignore',
411
+ });
412
+ child.unref();
413
+
414
+ const deadline = Date.now() + timeoutMs;
415
+ while (Date.now() < deadline) {
416
+ await new Promise(r => setTimeout(r, 400));
417
+ if (await checkHttpReady(port)) {
418
+ const srvPid = readPidFile(p.runPid);
419
+ const wdPid = readPidFile(p.watchdogPid) || child.pid;
420
+ console.log(`ODANT-WORK запущен в фоне: http://localhost:${port}/ (сервер PID ${srvPid || '?'}, watchdog PID ${wdPid})`);
421
+ console.log(`Лог сервера: ${p.logFile}`);
422
+ return { alreadyRunning: false, port, watchdogPid: wdPid, serverPid: srvPid };
423
+ }
424
+ }
425
+ console.error(`ODANT-WORK не ответил на порту ${port} за ${Math.round(timeoutMs / 1000)}с. Проверьте лог: ${p.logFile}`);
426
+ return { alreadyRunning: false, timeout: true, port };
427
+ }
428
+
429
+ export async function stopWork({ workRoot = resolveWorkRoot() } = {}) {
430
+ const p = pathsOf(workRoot);
431
+ const port = resolveWorkPort(workRoot);
432
+ fs.mkdirSync(p.sysDir, { recursive: true });
433
+ fs.writeFileSync(p.stoppedMarker, JSON.stringify({ pid: process.pid, time: Date.now(), reason: 'stop-command' }), 'utf8');
434
+ try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
435
+
436
+ stopSystemAutostartUnitIfRunning();
437
+
438
+ const wdPid = readPidFile(p.watchdogPid);
439
+ if (wdPid && isPidAlive(wdPid))
440
+ await terminatePid(wdPid, 4000);
441
+ try { fs.rmSync(p.watchdogPid, { force: true }); } catch { /* ignore */ }
442
+
443
+ const srvPid = readPidFile(p.runPid);
444
+ if (srvPid && isPidAlive(srvPid))
445
+ await terminatePid(srvPid, 6000);
446
+
447
+ for (const pid of listPortListeningPids(port))
448
+ await terminatePid(pid, 4000);
449
+
450
+ try { fs.rmSync(p.runPid, { force: true }); } catch { /* ignore */ }
451
+
452
+ const stillBusy = await isPortOpen(port, '127.0.0.1', 500);
453
+ if (stillBusy) {
454
+ console.warn(`Предупреждение: порт ${port} всё ещё занят.`);
455
+ return false;
456
+ }
457
+ console.log(`ODANT-WORK остановлен (порт ${port} свободен).`);
458
+ return true;
459
+ }
460
+
461
+ export async function printStatus({ workRoot = resolveWorkRoot() } = {}) {
462
+ const p = pathsOf(workRoot);
463
+ const port = resolveWorkPort(workRoot);
464
+ const wdPid = readPidFile(p.watchdogPid);
465
+ const srvPid = readPidFile(p.runPid);
466
+ const wdAlive = isPidAlive(wdPid);
467
+ const srvAlive = isPidAlive(srvPid);
468
+ const portOpen = await isPortOpen(port);
469
+ console.log(`Каталог WORK: ${workRoot}`);
470
+ console.log(`Порт ${port}: ${portOpen ? 'СЛУШАЕТ' : 'свободен'}`);
471
+ console.log(`Сервер (${p.runPid}): ${srvAlive ? `работает (PID ${srvPid})` : 'остановлен'}`);
472
+ console.log(`Watchdog (${p.watchdogPid}): ${wdAlive ? `работает (PID ${wdPid})` : 'остановлен'}`);
473
+ console.log(`Маркер остановки: ${fs.existsSync(p.stoppedMarker) ? 'да' : 'нет'}`);
474
+ }
475
+
476
+ const isMain = process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
477
+ if (isMain) {
478
+ const args = process.argv.slice(2);
479
+ const rootArg = args.find(a => a.startsWith('--root='))?.slice(7) || '';
480
+ const workRoot = resolveWorkRoot(rootArg);
481
+ if (args.includes('--stop')) {
482
+ const ok = await stopWork({ workRoot });
483
+ process.exit(ok ? 0 : 1);
484
+ }
485
+ else if (args.includes('--status')) {
486
+ await printStatus({ workRoot });
487
+ }
488
+ else if (args.includes('--run') || args.includes('--boot')) {
489
+ const code = await runSupervisor({ workRoot, boot: args.includes('--boot') });
490
+ process.exit(code);
491
+ }
492
+ else {
493
+ const res = await startDetached({ workRoot });
494
+ process.exit(res?.timeout ? 1 : 0);
495
+ }
496
+ }