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.
- package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/agent/$handler/class.js +11 -1
- package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/messengers/$handler/class.js +11 -1
- package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/settings/$handler/class.js +292 -0
- package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/skills/$handler/class.js +11 -1
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +24 -2
- package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +14 -11
- package/$server/$folder/$file/$html/handlers/preview/$handler/preview.js +7 -0
- package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +11 -0
- package/$server/$folder/$file/$md/handlers/preview/$handler/preview.js +29 -8
- package/$server/$folder/$file/$office/handlers/preview/$handler/preview.js +6 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +65 -10
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +14 -11
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
- package/$server/$folder/$file/$task/handlers/preview/$handler/preview.js +1 -0
- package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +9 -0
- package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +15 -0
- package/$server/$folder/handlers/pages/form/$handler/class.js +10 -2
- package/$server/$folder/handlers/pages/form/folder/$handler/class.js +523 -25
- package/$server/$folder/lib/consultant/consultant.js +80 -3
- package/$server/$folder/lib/explorer/explorer.js +63 -0
- package/$server/$folder/lib/tree/tree.js +47 -16
- package/NODES/$node/handlers/pages/form/network/$handler/class.js +552 -36
- package/autostart.bat +28 -0
- package/autostart.sh +17 -0
- package/oda/components/icon/icon.js +20 -7
- package/package.json +1 -1
- package/run.mjs +19 -0
- package/scripts/autostart.mjs +281 -0
- package/scripts/watchdog.mjs +496 -0
- package/sources/client.js +146 -2
- package/sources/host/auth-methods.js +2 -0
- package/sources/host/auto-updater.js +23 -1
- package/sources/host/http-server.js +5 -3
- package/sources/host/push.js +43 -14
- package/sources/host/websocket.js +69 -3
- package/sources/modules/agent/index.js +50 -19
- package/sources/modules/agent/permissions.js +4 -2
- package/sources/modules/agent/scope.js +72 -5
- package/sources/modules/agent/session.js +97 -14
- package/sources/modules/agent/tools/work/classes.js +16 -1
- package/sources/modules/license/index.js +120 -0
- package/sources/modules/nodes/registry.js +57 -7
- package/sources/modules/trainer/local-engine.js +22 -9
- package/sources/modules/user-profile/user-tokens.js +426 -85
- package/sources/server/access/gateway.js +3 -1
- package/sources/server/class/feed.js +6 -0
- package/sources/server/folder.js +5 -1
- package/sources/server/node.js +16 -0
- package/sources/server/server.js +59 -1
- package/sources/server/user.js +48 -0
- package/start.bat +25 -0
- package/start.sh +27 -0
- package/stop.bat +25 -0
- package/stop.sh +16 -0
- package/sw.js +3 -11
|
@@ -186,6 +186,13 @@ function isAllowedUpwardRead(normPath, tool, ctx) {
|
|
|
186
186
|
return false;
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
function parentPathOf(normPath) {
|
|
190
|
+
const segs = String(normPath || '').split('/').filter(Boolean);
|
|
191
|
+
return segs.length > 1 ? '/' + segs.slice(0, -1).join('/') : '/';
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const DESTRUCTIVE_OR_MOVE_TOOLS = new Set(['delete_class', 'move_class', 'delete']);
|
|
195
|
+
|
|
189
196
|
/**
|
|
190
197
|
* Классифицировать выход за границы текущего места задачи.
|
|
191
198
|
* @returns {Promise<{ targetPath: string, reason: string, needAdmin?: boolean, needBoss?: boolean } | null>}
|
|
@@ -207,10 +214,54 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
|
|
|
207
214
|
};
|
|
208
215
|
}
|
|
209
216
|
|
|
217
|
+
// 1б. Создание класса: дочерние элементы создаются внутри текущего контекста (включая филиалы $project в $project),
|
|
218
|
+
// а создание в вышестоящем родителе/домене переносится в ближайшую вышестоящую структуру.
|
|
219
|
+
if (tool.name === 'create_class') {
|
|
220
|
+
const parentNorm = normalizeWorkPath(absPath(args?.parent || '', ctx));
|
|
221
|
+
if (parentNorm
|
|
222
|
+
&& !isOwnCabinetPath(parentNorm, ctx?.session)
|
|
223
|
+
&& !isKernelOrTypifierPath(parentNorm)
|
|
224
|
+
&& !isGlobalSystemBranch(parentNorm)
|
|
225
|
+
&& parentNorm !== placePath
|
|
226
|
+
&& !parentNorm.startsWith(placePath + '/')) {
|
|
227
|
+
if (placePath.startsWith(parentNorm + '/') || parentNorm === '/') {
|
|
228
|
+
const resolvedParent = await resolveTargetPlace(parentNorm);
|
|
229
|
+
const targetPath = resolvedParent?.path || '/';
|
|
230
|
+
return {
|
|
231
|
+
targetPath,
|
|
232
|
+
reason: `Создание структуры внутри «${parentNorm}» должно выполняться из вышестоящего узла («${targetPath}»).`,
|
|
233
|
+
needAdmin: targetPath === '/',
|
|
234
|
+
needBoss: true,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
210
240
|
const paths = extractToolWorkPaths(tool, args, ctx);
|
|
211
241
|
if (!paths.length)
|
|
212
242
|
return null;
|
|
213
243
|
|
|
244
|
+
const isDryRunClassOp = (tool.name === 'delete_class' || tool.name === 'move_class') && args?.dry_run === true;
|
|
245
|
+
if (DESTRUCTIVE_OR_MOVE_TOOLS.has(tool.name) && !isDryRunClassOp) {
|
|
246
|
+
for (const p of paths) {
|
|
247
|
+
if (isOwnCabinetPath(p, ctx?.session) || isKernelOrTypifierPath(p))
|
|
248
|
+
continue;
|
|
249
|
+
if (p === placePath || (p !== '/' && placePath.startsWith(p + '/'))) {
|
|
250
|
+
const up = parentPathOf(p);
|
|
251
|
+
const resolvedUp = await resolveTargetPlace(up);
|
|
252
|
+
const targetPath = resolvedUp?.path || '/';
|
|
253
|
+
return {
|
|
254
|
+
targetPath,
|
|
255
|
+
reason: p === placePath
|
|
256
|
+
? `Удаление или перенос самого текущего узла «${p}» невозможны изнутри него — действие должно выполняться из вышестоящей структуры.`
|
|
257
|
+
: `Удаление или перенос вышестоящего узла «${p}» невозможны из дочернего контекста «${placePath}».`,
|
|
258
|
+
needAdmin: targetPath === '/',
|
|
259
|
+
needBoss: true,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
214
265
|
const placeCone = contextConeOf(placePath);
|
|
215
266
|
const crossTargets = [];
|
|
216
267
|
|
|
@@ -236,11 +287,15 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
|
|
|
236
287
|
continue;
|
|
237
288
|
const segs = p.split('/').filter(Boolean);
|
|
238
289
|
if (segs[0].toUpperCase() === 'NODES' && segs[1] && segs[1][0] !== '$') {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
290
|
+
const nodeRoot = '/' + segs.slice(0, 2).join('/');
|
|
291
|
+
if (placePath !== nodeRoot && !placePath.startsWith(nodeRoot + '/')) {
|
|
292
|
+
return {
|
|
293
|
+
targetPath: nodeRoot,
|
|
294
|
+
reason: `Работа с узлом сети «${segs[1]}» (${p}) должна выполняться в контексте этого узла.`,
|
|
295
|
+
needBoss: !tool.readonly,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
continue;
|
|
244
299
|
}
|
|
245
300
|
return {
|
|
246
301
|
targetPath: '/',
|
|
@@ -277,6 +332,15 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
|
|
|
277
332
|
};
|
|
278
333
|
}
|
|
279
334
|
}
|
|
335
|
+
|
|
336
|
+
// 6. Изменение строго вышестоящего предка (кроме чтения вверх и редактирования самого текущего узла)
|
|
337
|
+
if (!tool.readonly && !isDryRunClassOp && p !== placePath && p !== '/' && placePath.startsWith(p + '/')) {
|
|
338
|
+
return {
|
|
339
|
+
targetPath: p,
|
|
340
|
+
reason: `Изменение вышестоящего узла «${p}» должно выполняться в его собственном контексте.`,
|
|
341
|
+
needBoss: ['create_class', 'update_class', 'move_class', 'delete_class', 'assign'].includes(tool.name),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
280
344
|
}
|
|
281
345
|
|
|
282
346
|
if (!crossTargets.length)
|
|
@@ -373,6 +437,9 @@ export async function checkOutOfScopeForMove(tool, args = {}, ctx = {}) {
|
|
|
373
437
|
if (!scope)
|
|
374
438
|
return null;
|
|
375
439
|
const resolved = await resolveTargetPlace(scope.targetPath);
|
|
440
|
+
const placeNorm = normalizeWorkPath(ctx?.contextPath || ctx?.place?.path || '/') || '/';
|
|
441
|
+
if (resolved.path === placeNorm)
|
|
442
|
+
return null;
|
|
376
443
|
const access = await checkTargetMoveAccess(resolved.node, ctx?.session, {
|
|
377
444
|
needAdmin: scope.needAdmin,
|
|
378
445
|
needBoss: scope.needBoss,
|
|
@@ -17,7 +17,9 @@
|
|
|
17
17
|
* События в UI (session.send): chat.start / chat.done (занятость), task.state { status },
|
|
18
18
|
* task.delta { item, field, token } (стрим), { path } — файл изменился (перечитать).
|
|
19
19
|
*/
|
|
20
|
+
import fs from 'node:fs';
|
|
20
21
|
import fsp from 'node:fs/promises';
|
|
22
|
+
import path from 'node:path';
|
|
21
23
|
import { log } from './log.js';
|
|
22
24
|
import { runLoop, maybeCompact } from './loop.js';
|
|
23
25
|
import { createEnv, shouldEnforceAgentLicense } from './index.js';
|
|
@@ -125,6 +127,8 @@ export async function getBody(file) {
|
|
|
125
127
|
/** Атомарная запись (tmp + rename), с коалесцированием частых сохранений.
|
|
126
128
|
* На Windows при занятом целевом файле пишем напрямую без unlink, чтобы файл ни на мс не исчезал с диска. */
|
|
127
129
|
async function save(s, session) {
|
|
130
|
+
if (s.missingOnDisk)
|
|
131
|
+
return;
|
|
128
132
|
if (s.writing) {
|
|
129
133
|
s.again = true;
|
|
130
134
|
return s.writing;
|
|
@@ -135,14 +139,31 @@ async function save(s, session) {
|
|
|
135
139
|
s.body.updated = Date.now();
|
|
136
140
|
const text = JSON.stringify(s.body, null, 2);
|
|
137
141
|
const dir = s.file.dir;
|
|
142
|
+
if (!dir || !fs.existsSync(path.dirname(dir))) {
|
|
143
|
+
s.missingOnDisk = true;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
138
146
|
const tmp = dir + '.tmp';
|
|
139
147
|
try {
|
|
140
148
|
await WORK.fsp.writeFile(tmp, text, 'utf-8');
|
|
141
149
|
await WORK.fsp.rename(tmp, dir);
|
|
142
150
|
}
|
|
143
|
-
catch {
|
|
144
|
-
|
|
145
|
-
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (e?.code === 'ENOENT' || !fs.existsSync(path.dirname(dir))) {
|
|
153
|
+
s.missingOnDisk = true;
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await WORK.fsp.writeFile(dir, text, 'utf-8');
|
|
158
|
+
await WORK.fsp.unlink(tmp).catch(() => {});
|
|
159
|
+
}
|
|
160
|
+
catch (e2) {
|
|
161
|
+
if (e2?.code === 'ENOENT') {
|
|
162
|
+
s.missingOnDisk = true;
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
throw e2;
|
|
166
|
+
}
|
|
146
167
|
}
|
|
147
168
|
try {
|
|
148
169
|
s.file.reset?.(undefined, { selfOnly: true });
|
|
@@ -156,7 +177,30 @@ async function save(s, session) {
|
|
|
156
177
|
finally {
|
|
157
178
|
s.writing = null;
|
|
158
179
|
}
|
|
159
|
-
|
|
180
|
+
if (!s.missingOnDisk)
|
|
181
|
+
session?.send?.({ path: s.file.short });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Остановить и очистить в памяти активные задачи внутри удалённого узла. */
|
|
185
|
+
export function invalidateTasksUnder(nodePath) {
|
|
186
|
+
const norm = String(nodePath || '').replace(/\/+$/, '');
|
|
187
|
+
if (!norm || norm === '/')
|
|
188
|
+
return 0;
|
|
189
|
+
let count = 0;
|
|
190
|
+
for (const [k, s] of RUNS.entries()) {
|
|
191
|
+
const p = String(s?.file?.path || s?.body?.contextPath || '').replace(/\/+$/, '');
|
|
192
|
+
if (p === norm || p.startsWith(norm + '/')) {
|
|
193
|
+
count++;
|
|
194
|
+
s.missingOnDisk = true;
|
|
195
|
+
try { s.controller?.abort(); } catch { /* ignore */ }
|
|
196
|
+
for (const resolve of s.waiters?.values?.() || []) {
|
|
197
|
+
try { resolve({ accept: false, content: 'Узел удалён' }); } catch { /* ignore */ }
|
|
198
|
+
}
|
|
199
|
+
s.waiters?.clear?.();
|
|
200
|
+
RUNS.delete(k);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return count;
|
|
160
204
|
}
|
|
161
205
|
|
|
162
206
|
function send(s, session, event) {
|
|
@@ -254,25 +298,49 @@ export function pushMessageOf(s, kind, text, detail = {}) {
|
|
|
254
298
|
};
|
|
255
299
|
}
|
|
256
300
|
|
|
301
|
+
/**
|
|
302
|
+
* Считать ли завершение хода «выполненной задачей» для отправки push/мессенджера:
|
|
303
|
+
* только если работа шла не быстрее PUSH_DONE_MIN_MS И были реальные действия
|
|
304
|
+
* (вызовы инструментов агента или фоновый/плановый запуск), чтобы обычный диалог
|
|
305
|
+
* вроде «привет» (даже при долгом прогреве локальной модели) не слал пуши.
|
|
306
|
+
*/
|
|
307
|
+
export function shouldNotifyTaskDone(s, session, startItemCount = 0, now = Date.now()) {
|
|
308
|
+
const started = Number(s?.runStartedAt || s?.startedAt || 0);
|
|
309
|
+
if (!started || now - started < PUSH_DONE_MIN_MS)
|
|
310
|
+
return false;
|
|
311
|
+
if (session?.scheduled || session?.background || s?.body?.childAgent)
|
|
312
|
+
return true;
|
|
313
|
+
const from = Number.isFinite(s?.runStartItemCount) ? s.runStartItemCount : startItemCount;
|
|
314
|
+
const items = Array.isArray(s?.body?.items) ? s.body.items.slice(Math.max(0, from)) : [];
|
|
315
|
+
return items.some(it => Array.isArray(it?.tools) && it.tools.length > 0);
|
|
316
|
+
}
|
|
317
|
+
|
|
257
318
|
/**
|
|
258
319
|
* Push пользователю: задача ждёт его / закончила долгую работу / упала.
|
|
259
320
|
* Показывать ли — решает service worker: если эта задача уже открыта на экране (в видимой
|
|
260
|
-
* вкладке — в проводнике или отдельной страницей), уведомление не
|
|
261
|
-
* и сфокусированный проводник тоже подавляет push.
|
|
321
|
+
* вкладке — в проводнике или отдельной страницей), уведомление не показывается.
|
|
262
322
|
* 9.7: ожидающее разрешение — с кнопками «Разрешить/Отклонить» прямо в уведомлении.
|
|
263
323
|
*/
|
|
264
324
|
async function pushNotify(s, session, kind, text, detail = {}) {
|
|
265
325
|
const uid = session?.uid;
|
|
266
326
|
if (!uid || process.env.WORK_TEST)
|
|
267
327
|
return;
|
|
328
|
+
let visibleOnScreen = false;
|
|
268
329
|
try {
|
|
269
|
-
const {
|
|
270
|
-
|
|
330
|
+
const { isTaskVisibleToUser } = await import('../../host/websocket.js');
|
|
331
|
+
visibleOnScreen = isTaskVisibleToUser(uid, s.file?.path);
|
|
271
332
|
}
|
|
272
|
-
catch
|
|
273
|
-
|
|
333
|
+
catch { /* ignore */ }
|
|
334
|
+
if (!visibleOnScreen) {
|
|
335
|
+
try {
|
|
336
|
+
const { sendPushNotification, removePushSubscription } = await import('../../host/push.js');
|
|
337
|
+
await sendPushNotification({ receivers: [uid], message: pushMessageOf(s, kind, text, detail) }, removePushSubscription);
|
|
338
|
+
}
|
|
339
|
+
catch (e) {
|
|
340
|
+
console.warn('[task push]', e.message);
|
|
341
|
+
}
|
|
274
342
|
}
|
|
275
|
-
if (!(session?.scheduled && kind === 'done')) {
|
|
343
|
+
if (!(session?.scheduled && kind === 'done') && !visibleOnScreen) {
|
|
276
344
|
try {
|
|
277
345
|
const { notifyTaskEvent } = await import('../notify/index.js');
|
|
278
346
|
await notifyTaskEvent({ file: s.file, uid, kind, text, detail });
|
|
@@ -502,6 +570,10 @@ function start(s, session, file, licenseOpts = {}) {
|
|
|
502
570
|
s.movedAway = false;
|
|
503
571
|
s.controller = new AbortController();
|
|
504
572
|
s.startedAt = Date.now();
|
|
573
|
+
if (!s.runStartedAt) {
|
|
574
|
+
s.runStartedAt = s.startedAt;
|
|
575
|
+
s.runStartItemCount = Array.isArray(body.items) ? body.items.length : 0;
|
|
576
|
+
}
|
|
505
577
|
setStatus(s, session, 'running');
|
|
506
578
|
send(s, session, { type: 'chat.start' });
|
|
507
579
|
const host = makeHost(s, session);
|
|
@@ -589,13 +661,13 @@ function start(s, session, file, licenseOpts = {}) {
|
|
|
589
661
|
body.items.push({ ...u, queued: undefined });
|
|
590
662
|
}
|
|
591
663
|
restart = rest.length > 0 && !aborted && body.status !== 'error';
|
|
592
|
-
await save(s, session);
|
|
664
|
+
await save(s, session).catch(e => log.debug('task.finalSave', e));
|
|
593
665
|
s.running = null;
|
|
594
666
|
}
|
|
595
667
|
}
|
|
596
668
|
if (movedAway)
|
|
597
669
|
return;
|
|
598
|
-
if (restart) {
|
|
670
|
+
if (restart && !s.missingOnDisk) {
|
|
599
671
|
start(s, session, file);
|
|
600
672
|
return;
|
|
601
673
|
}
|
|
@@ -605,8 +677,10 @@ function start(s, session, file, licenseOpts = {}) {
|
|
|
605
677
|
await publishTaskResults(file, session).catch(e => console.warn('[task publish]', e?.message || e));
|
|
606
678
|
if (!aborted && body.status === 'error')
|
|
607
679
|
pushNotify(s, session, 'error', [...body.items].reverse().find(i => i.type === 'error' || i.error)?.content);
|
|
608
|
-
else if (!aborted && body.status === 'idle' &&
|
|
680
|
+
else if (!aborted && body.status === 'idle' && shouldNotifyTaskDone(s, session))
|
|
609
681
|
pushNotify(s, session, 'done', lastAnswer(body));
|
|
682
|
+
s.runStartedAt = 0;
|
|
683
|
+
s.runStartItemCount = undefined;
|
|
610
684
|
})();
|
|
611
685
|
return s.running;
|
|
612
686
|
}
|
|
@@ -1146,6 +1220,13 @@ export async function approve(file, params = {}) {
|
|
|
1146
1220
|
await assertTaskOwner(file, params);
|
|
1147
1221
|
const s = stateOf(file);
|
|
1148
1222
|
const p = argsOf(params);
|
|
1223
|
+
if (file?.dir && !fs.existsSync(file.dir)) {
|
|
1224
|
+
for (const resolve of s.waiters.values()) {
|
|
1225
|
+
try { resolve({ accept: false, content: 'Задача или её узел уже удалены' }); } catch { /* ignore */ }
|
|
1226
|
+
}
|
|
1227
|
+
s.waiters.clear();
|
|
1228
|
+
return { ok: false, error: 'Задача или её узел уже удалены' };
|
|
1229
|
+
}
|
|
1149
1230
|
const body = await getBody(file);
|
|
1150
1231
|
const call = p.call || body.waiting?.call;
|
|
1151
1232
|
const reply = {
|
|
@@ -1186,6 +1267,8 @@ export async function approve(file, params = {}) {
|
|
|
1186
1267
|
export async function explainCall(file, params = {}) {
|
|
1187
1268
|
await assertTaskOwner(file, params);
|
|
1188
1269
|
const s = stateOf(file);
|
|
1270
|
+
if (file?.dir && !fs.existsSync(file.dir))
|
|
1271
|
+
return { ok: false, error: 'Задача или её узел уже удалены' };
|
|
1189
1272
|
const p = argsOf(params);
|
|
1190
1273
|
const body = await getBody(file);
|
|
1191
1274
|
const callId = p.call || p.post?.call || body.waiting?.call;
|
|
@@ -831,7 +831,7 @@ export const moveClass = {
|
|
|
831
831
|
if (isSystemTypifierPath(p))
|
|
832
832
|
return { verdict: 'ask', noAlways: true, reason: 'перенос/переименование системного типизатора ' + p + ' затронет все классы и формы' };
|
|
833
833
|
if (isGlobalModulePath(p))
|
|
834
|
-
return { verdict: 'ask', reason: 'перенос/переименование общего модуля ' + p + ' затронет все организации' };
|
|
834
|
+
return { verdict: 'ask', noAlways: true, reason: 'перенос/переименование общего модуля ' + p + ' затронет все организации' };
|
|
835
835
|
return null;
|
|
836
836
|
},
|
|
837
837
|
async run(args, ctx) {
|
|
@@ -1076,11 +1076,26 @@ export const deleteClass = {
|
|
|
1076
1076
|
});
|
|
1077
1077
|
}
|
|
1078
1078
|
|
|
1079
|
+
const taskPath = String(ctx?.task?.path || '').replace(/\/+$/, '');
|
|
1080
|
+
if (taskPath && (taskPath === p || taskPath.startsWith(p + '/'))) {
|
|
1081
|
+
throw new Error(`delete_class: нельзя удалить ${p} из задачи, расположенной внутри этого же узла — перенеси задачу в вышестоящую структуру`);
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1079
1084
|
if (fs.existsSync(itemRealDir))
|
|
1080
1085
|
await fsp.rm(itemRealDir, { recursive: true, force: true });
|
|
1081
1086
|
globalThis.WORK_RAG?.invalidate?.(itemRealDir);
|
|
1082
1087
|
itemParent?.reset?.();
|
|
1083
1088
|
await invalidateWorkCaches(p);
|
|
1089
|
+
try {
|
|
1090
|
+
const { invalidateTasksUnder } = await import('../../session.js');
|
|
1091
|
+
invalidateTasksUnder(p);
|
|
1092
|
+
}
|
|
1093
|
+
catch { /* ignore */ }
|
|
1094
|
+
try {
|
|
1095
|
+
const { broadcastNodeDeleted } = await import('../../../../host/websocket.js');
|
|
1096
|
+
broadcastNodeDeleted(p, itemParent?.path || '/');
|
|
1097
|
+
}
|
|
1098
|
+
catch { /* ignore */ }
|
|
1084
1099
|
|
|
1085
1100
|
return `удалён класс ${p} (${itemType}); удалено подклассов: ${subCids.length}`;
|
|
1086
1101
|
},
|
|
@@ -17,6 +17,7 @@ import path from 'node:path';
|
|
|
17
17
|
import crypto from 'node:crypto';
|
|
18
18
|
import { serverKeys, fingerprint } from '../nodes/identity.js';
|
|
19
19
|
import { serverId } from '../../host/server-id.js';
|
|
20
|
+
import { PUBLIC_ORIGIN } from '../../host/config.js';
|
|
20
21
|
import {
|
|
21
22
|
ensurePackageManifest,
|
|
22
23
|
loadAutoUpdateState,
|
|
@@ -975,6 +976,120 @@ export function calculateLicenseQuote({
|
|
|
975
976
|
};
|
|
976
977
|
}
|
|
977
978
|
|
|
979
|
+
function resolvePublishOrigin(explicit = '') {
|
|
980
|
+
const raw = String(explicit || PUBLIC_ORIGIN || '').trim();
|
|
981
|
+
if (!raw)
|
|
982
|
+
return '';
|
|
983
|
+
try {
|
|
984
|
+
const u = new URL(raw);
|
|
985
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:')
|
|
986
|
+
return '';
|
|
987
|
+
const h = u.hostname.toLowerCase();
|
|
988
|
+
if (!h || h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '0.0.0.0' || h.endsWith('.local') || h.startsWith('127.'))
|
|
989
|
+
return '';
|
|
990
|
+
return u.origin;
|
|
991
|
+
}
|
|
992
|
+
catch {
|
|
993
|
+
return '';
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function resolveSelfServerName() {
|
|
998
|
+
const lbl = String(globalThis.WORK?.label || globalThis.WORK?.DATA?.label || '').trim();
|
|
999
|
+
return lbl && lbl !== 'WORK' ? lbl : 'Сервер WORK';
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/**
|
|
1003
|
+
* Поиск серверов WORK в каталоге центра поддержки и лицензирования (work.odant.org).
|
|
1004
|
+
*/
|
|
1005
|
+
export async function discoverNetworkServers({
|
|
1006
|
+
query = '',
|
|
1007
|
+
hubUrl = '',
|
|
1008
|
+
systemDir = SYSTEM_DIR,
|
|
1009
|
+
licensePath = LICENSE_FILE,
|
|
1010
|
+
trustedPublicKey = '',
|
|
1011
|
+
fetchImpl = globalThis.fetch,
|
|
1012
|
+
} = {}) {
|
|
1013
|
+
const sysDir = systemDir || (licensePath ? path.dirname(licensePath) : SYSTEM_DIR);
|
|
1014
|
+
const tokenBinding = loadOwnerTokenBinding(sysDir);
|
|
1015
|
+
const lic = loadLocalLicense(licensePath || path.join(sysDir, 'license.json'), { systemDir: sysDir, trustedPublicKey });
|
|
1016
|
+
const hw = getHardwareIdentity();
|
|
1017
|
+
const baseUrl = String(hubUrl || tokenBinding?.hubUrl || lic.hubUrl || DEFAULT_LICENSE_HUB_URL).replace(/\/+$/, '');
|
|
1018
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
1019
|
+
if (tokenBinding?.token)
|
|
1020
|
+
headers.Authorization = `Bearer ${tokenBinding.token}`;
|
|
1021
|
+
|
|
1022
|
+
const res = await fetchImpl(`${baseUrl}/api/network/servers`, {
|
|
1023
|
+
method: 'POST',
|
|
1024
|
+
headers,
|
|
1025
|
+
body: JSON.stringify({
|
|
1026
|
+
query: String(query || '').trim(),
|
|
1027
|
+
token: tokenBinding?.token || '',
|
|
1028
|
+
licenseId: lic.unlicensed ? '' : lic.licenseId,
|
|
1029
|
+
nodeFingerprint: hw.nodeFingerprint,
|
|
1030
|
+
hwid: hw.hwid,
|
|
1031
|
+
}),
|
|
1032
|
+
});
|
|
1033
|
+
if (!res.ok) {
|
|
1034
|
+
const text = await res.text().catch(() => '');
|
|
1035
|
+
throw new Error(`Сервер поддержки (${baseUrl}) ответил HTTP ${res.status}: ${text.slice(0, 200)}`);
|
|
1036
|
+
}
|
|
1037
|
+
const data = await res.json();
|
|
1038
|
+
return {
|
|
1039
|
+
hubUrl: baseUrl,
|
|
1040
|
+
publicOrigin: resolvePublishOrigin(),
|
|
1041
|
+
servers: Array.isArray(data?.servers) ? data.servers : [],
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Обновить статус публикации сервера WORK в каталоге work.odant.org.
|
|
1047
|
+
*/
|
|
1048
|
+
export async function publishNetworkServer({
|
|
1049
|
+
discoverable = true,
|
|
1050
|
+
publicOrigin = '',
|
|
1051
|
+
serverName = '',
|
|
1052
|
+
hubUrl = '',
|
|
1053
|
+
systemDir = SYSTEM_DIR,
|
|
1054
|
+
licensePath = LICENSE_FILE,
|
|
1055
|
+
trustedPublicKey = '',
|
|
1056
|
+
fetchImpl = globalThis.fetch,
|
|
1057
|
+
} = {}) {
|
|
1058
|
+
const sysDir = systemDir || (licensePath ? path.dirname(licensePath) : SYSTEM_DIR);
|
|
1059
|
+
const tokenBinding = loadOwnerTokenBinding(sysDir);
|
|
1060
|
+
const lic = loadLocalLicense(licensePath || path.join(sysDir, 'license.json'), { systemDir: sysDir, trustedPublicKey });
|
|
1061
|
+
const hw = getHardwareIdentity();
|
|
1062
|
+
const baseUrl = String(hubUrl || tokenBinding?.hubUrl || lic.hubUrl || DEFAULT_LICENSE_HUB_URL).replace(/\/+$/, '');
|
|
1063
|
+
const effectiveOrigin = resolvePublishOrigin(publicOrigin);
|
|
1064
|
+
if (discoverable && !effectiveOrigin) {
|
|
1065
|
+
throw new Error('Укажите публичный адрес сервера (PUBLIC_ORIGIN, не localhost) для публикации в каталоге');
|
|
1066
|
+
}
|
|
1067
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
1068
|
+
if (tokenBinding?.token)
|
|
1069
|
+
headers.Authorization = `Bearer ${tokenBinding.token}`;
|
|
1070
|
+
|
|
1071
|
+
const res = await fetchImpl(`${baseUrl}/api/network/publish`, {
|
|
1072
|
+
method: 'POST',
|
|
1073
|
+
headers,
|
|
1074
|
+
body: JSON.stringify({
|
|
1075
|
+
token: tokenBinding?.token || '',
|
|
1076
|
+
licenseId: lic.unlicensed ? '' : lic.licenseId,
|
|
1077
|
+
hwid: hw.hwid,
|
|
1078
|
+
nodeFingerprint: hw.nodeFingerprint,
|
|
1079
|
+
nodePublicKey: hw.nodePublicKey,
|
|
1080
|
+
serverId: hw.serverId,
|
|
1081
|
+
publicOrigin: effectiveOrigin,
|
|
1082
|
+
serverName: String(serverName || resolveSelfServerName()),
|
|
1083
|
+
discoverable: Boolean(discoverable),
|
|
1084
|
+
}),
|
|
1085
|
+
});
|
|
1086
|
+
if (!res.ok) {
|
|
1087
|
+
const text = await res.text().catch(() => '');
|
|
1088
|
+
throw new Error(`Сервер поддержки (${baseUrl}) отклонил публикацию (HTTP ${res.status}): ${text.slice(0, 200)}`);
|
|
1089
|
+
}
|
|
1090
|
+
return res.json();
|
|
1091
|
+
}
|
|
1092
|
+
|
|
978
1093
|
/**
|
|
979
1094
|
* Привязать токен владельца (owk1...) к локальному WORK и сразу скачать файлы лицензий из личного кабинета в #system.
|
|
980
1095
|
*/
|
|
@@ -1001,6 +1116,8 @@ export async function bindOwnerTokenAndSync({
|
|
|
1001
1116
|
nodeFingerprint: hw.nodeFingerprint,
|
|
1002
1117
|
nodePublicKey: hw.nodePublicKey,
|
|
1003
1118
|
serverId: hw.serverId,
|
|
1119
|
+
publicOrigin: resolvePublishOrigin(),
|
|
1120
|
+
serverName: resolveSelfServerName(),
|
|
1004
1121
|
}),
|
|
1005
1122
|
});
|
|
1006
1123
|
|
|
@@ -1091,6 +1208,9 @@ export async function syncWithLicenseHub({ hubUrl, licensePath, systemDir, token
|
|
|
1091
1208
|
hwid: hw.hwid,
|
|
1092
1209
|
nodeFingerprint: hw.nodeFingerprint,
|
|
1093
1210
|
nodePublicKey: hw.nodePublicKey,
|
|
1211
|
+
serverId: hw.serverId,
|
|
1212
|
+
publicOrigin: resolvePublishOrigin(),
|
|
1213
|
+
serverName: resolveSelfServerName(),
|
|
1094
1214
|
customer: lic.customer,
|
|
1095
1215
|
}),
|
|
1096
1216
|
});
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* ROLES — роли удалённого сервера: в локальном классе узла на них назначаются наши
|
|
6
6
|
* представители (`#security.CUSTOMERS: [uid]` — представитель по закупкам у этого узла).
|
|
7
7
|
*/
|
|
8
|
-
import { fingerprint, PROTOCOL, wellKnown } from './identity.js';
|
|
8
|
+
import { fingerprint, PROTOCOL, wellKnown, serverKeys } from './identity.js';
|
|
9
9
|
import { serverId } from '../../host/server-id.js';
|
|
10
10
|
import { guardedRequest } from '../../host/net-guard.js';
|
|
11
11
|
|
|
@@ -136,24 +136,32 @@ function rolesFrom(card) {
|
|
|
136
136
|
* @param {object} params {origin, fingerprint (подтверждение), label?, announce?}
|
|
137
137
|
*/
|
|
138
138
|
export async function addNode(root, params = {}) {
|
|
139
|
-
const
|
|
139
|
+
const opts = (params.post && typeof params.post === 'object' && !Buffer.isBuffer(params.post))
|
|
140
|
+
? { ...params.post, ...params }
|
|
141
|
+
: params;
|
|
142
|
+
const card = await fetchCard(opts.origin, { trusted: true }); // адрес от администратора (LAN легальна)
|
|
140
143
|
if (card.id.toUpperCase() === serverId)
|
|
141
144
|
throw new Error('Это наш собственный сервер');
|
|
142
|
-
|
|
143
|
-
|
|
145
|
+
const wantFp = String(opts.fingerprint || '').trim().toUpperCase();
|
|
146
|
+
if (!wantFp || wantFp !== card.fingerprint)
|
|
147
|
+
return {
|
|
148
|
+
confirm: true,
|
|
149
|
+
fingerprintMismatch: Boolean(wantFp && wantFp !== card.fingerprint),
|
|
150
|
+
card: { id: card.id, label: card.label, origin: card.origin, fingerprint: card.fingerprint, roles: card.roles },
|
|
151
|
+
};
|
|
144
152
|
const existing = await findNode(card.id);
|
|
145
153
|
if (existing)
|
|
146
154
|
throw new Error('Узел уже в реестре: ' + existing.item.path);
|
|
147
155
|
const { safeNodeName } = await import('../../server/safe-node-name.js');
|
|
148
|
-
const id = safeNodeName(
|
|
156
|
+
const id = safeNodeName(opts.label || new URL(card.origin).host) || card.id;
|
|
149
157
|
const data = {
|
|
150
|
-
label:
|
|
158
|
+
label: opts.label || card.label || id,
|
|
151
159
|
host_id: card.id.toUpperCase(),
|
|
152
160
|
origin: card.origin,
|
|
153
161
|
publicKey: card.publicKey,
|
|
154
162
|
fingerprint: card.fingerprint,
|
|
155
163
|
status: 'active',
|
|
156
|
-
announce: !!
|
|
164
|
+
announce: !!opts.announce,
|
|
157
165
|
added: Date.now(),
|
|
158
166
|
remote: { label: card.label, roles: card.roles || [], peers: card.peers || [], at: Date.now() },
|
|
159
167
|
ROLES: rolesFrom(card),
|
|
@@ -165,6 +173,48 @@ export async function addNode(root, params = {}) {
|
|
|
165
173
|
return { added: (root.path || '') + '/' + id, fingerprint: card.fingerprint };
|
|
166
174
|
}
|
|
167
175
|
|
|
176
|
+
export async function discoverHubNodes(params = {}) {
|
|
177
|
+
const { discoverNetworkServers } = await import('../license/index.js');
|
|
178
|
+
const query = String(params.query || params.q || params.post?.query || '').trim();
|
|
179
|
+
const res = await discoverNetworkServers({ query });
|
|
180
|
+
const known = await listNodes();
|
|
181
|
+
const byId = new Map(known.map(n => [String(n.host_id || '').toUpperCase(), n]));
|
|
182
|
+
const byFp = new Map(known.map(n => [String(n.fingerprint || '').toUpperCase(), n]));
|
|
183
|
+
const selfFp = fingerprint(serverKeys().publicKey);
|
|
184
|
+
const selfRow = (res.servers || []).find(s =>
|
|
185
|
+
(s.serverId && s.serverId.toUpperCase() === serverId)
|
|
186
|
+
|| (s.fingerprint && s.fingerprint.toUpperCase() === selfFp)
|
|
187
|
+
) || null;
|
|
188
|
+
const items = (res.servers || [])
|
|
189
|
+
.filter(s => !(s.serverId && s.serverId.toUpperCase() === serverId) && !(s.fingerprint && s.fingerprint.toUpperCase() === selfFp))
|
|
190
|
+
.map(s => {
|
|
191
|
+
const matched = (s.serverId && byId.get(s.serverId.toUpperCase())) || (s.fingerprint && byFp.get(s.fingerprint.toUpperCase())) || null;
|
|
192
|
+
return {
|
|
193
|
+
...s,
|
|
194
|
+
connected: Boolean(matched),
|
|
195
|
+
nodePath: matched?.item?.path || '',
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
return {
|
|
199
|
+
hubUrl: res.hubUrl,
|
|
200
|
+
publicOrigin: res.publicOrigin || '',
|
|
201
|
+
selfServerId: serverId,
|
|
202
|
+
selfFingerprint: selfFp,
|
|
203
|
+
selfPublished: Boolean(selfRow?.discoverable),
|
|
204
|
+
items,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function publishHubNode(params = {}) {
|
|
209
|
+
const body = (params.post && typeof params.post === 'object' && !Buffer.isBuffer(params.post)) ? params.post : params;
|
|
210
|
+
const { publishNetworkServer } = await import('../license/index.js');
|
|
211
|
+
return publishNetworkServer({
|
|
212
|
+
discoverable: body.discoverable !== false && body.discoverable !== 'false',
|
|
213
|
+
publicOrigin: body.publicOrigin || '',
|
|
214
|
+
serverName: body.serverName || '',
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
168
218
|
/**
|
|
169
219
|
* Обновить карточку узла. Смена ключа не принимается молча: узел блокируется (key_changed)
|
|
170
220
|
* до решения администратора.
|