odant-work 1.0.103 → 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 (38) 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/system/agent/$handler/class.js +14 -11
  6. package/$server/$folder/$file/$html/handlers/preview/$handler/preview.js +7 -0
  7. package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +11 -0
  8. package/$server/$folder/$file/$md/handlers/preview/$handler/preview.js +29 -8
  9. package/$server/$folder/$file/$office/handlers/preview/$handler/preview.js +6 -0
  10. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +34 -2
  11. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +14 -11
  12. package/$server/$folder/$file/$task/handlers/preview/$handler/preview.js +1 -0
  13. package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +9 -0
  14. package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +15 -0
  15. package/$server/$folder/handlers/pages/form/$handler/class.js +10 -2
  16. package/$server/$folder/handlers/pages/form/folder/$handler/class.js +523 -25
  17. package/$server/$folder/lib/explorer/explorer.js +63 -0
  18. package/$server/$folder/lib/tree/tree.js +45 -14
  19. package/NODES/$node/handlers/pages/form/network/$handler/class.js +552 -36
  20. package/oda/components/icon/icon.js +20 -7
  21. package/package.json +1 -1
  22. package/sources/client.js +24 -0
  23. package/sources/host/websocket.js +17 -0
  24. package/sources/modules/agent/index.js +25 -6
  25. package/sources/modules/agent/permissions.js +4 -2
  26. package/sources/modules/agent/scope.js +72 -5
  27. package/sources/modules/agent/session.js +59 -6
  28. package/sources/modules/agent/tools/work/classes.js +16 -1
  29. package/sources/modules/license/index.js +120 -0
  30. package/sources/modules/nodes/registry.js +57 -7
  31. package/sources/modules/trainer/local-engine.js +22 -9
  32. package/sources/modules/user-profile/user-profile.js +0 -129
  33. package/sources/modules/user-profile/user-tokens.js +426 -85
  34. package/sources/server/access/gateway.js +1 -0
  35. package/sources/server/folder.js +5 -1
  36. package/sources/server/node.js +16 -0
  37. package/sources/server/server.js +14 -5
  38. package/sources/server/user.js +3 -0
@@ -150,16 +150,29 @@ ODA({is: 'oda-icon',
150
150
  this.bb = undefined;
151
151
  if (this.iconTag === 'image')
152
152
  return;
153
- const bb = this.bb;
154
- if ((!bb || !bb.height || !bb.width) && !this[R].states.sleep) {
155
- this._icon.error = e;
156
- this._index += 1;
157
- }
153
+ const checkBox = () => {
154
+ const bb = this.bb;
155
+ if ((!bb || !bb.height || !bb.width) && !this[R]?.states?.sleep) {
156
+ if (this._index + 1 < this._icons_list.length) {
157
+ this._icon.error = e;
158
+ this._index += 1;
159
+ }
160
+ else {
161
+ this.bb = undefined;
162
+ }
163
+ }
164
+ };
165
+ if (typeof requestAnimationFrame === 'function')
166
+ requestAnimationFrame(checkBox);
167
+ else
168
+ checkBox();
158
169
  },
159
170
  _onError(e){
160
171
  this.bb = undefined;
161
- this._icon.error = e;
162
- this._index += 1;
172
+ if (this._icon)
173
+ this._icon.error = e;
174
+ if (this._index + 1 < this._icons_list.length)
175
+ this._index += 1;
163
176
  },
164
177
  // $listeners:{
165
178
  // wake(e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.103",
3
+ "version": "1.0.104",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/sources/client.js CHANGED
@@ -843,6 +843,30 @@ class WebSocketEvents {
843
843
  }
844
844
  WORK.chatEvents.dispatchEvent(new CustomEvent('task.moved', { detail: data }));
845
845
  } break;
846
+ case 'node.deleted': {
847
+ WORK.chatEvents ??= new EventTarget();
848
+ const delPath = String(data.path || '').replace(/\/+$/, '');
849
+ const parentPath = String(data.parentPath || '/').replace(/\/+$/, '') || '/';
850
+ if (delPath) {
851
+ for (const [k, item] of Object.entries(CORE.$item.ITEMS || {})) {
852
+ const ip = String(item?.short || item?.path || k).replace(/\/+$/, '');
853
+ if (ip === delPath || ip.startsWith(delPath + '/')) {
854
+ try { item.fire?.('node.deleted', data); } catch { /* ignore */ }
855
+ delete CORE.$item.ITEMS[k];
856
+ }
857
+ }
858
+ const parentItem = CORE.$item.ITEMS[parentPath] || (parentPath === '/' ? CORE.$item.ITEMS[''] : null);
859
+ if (parentItem) {
860
+ const LISTS = parentItem.constructor.LISTS || CORE.$item.LISTS;
861
+ for (const key of LISTS) {
862
+ delete parentItem[key];
863
+ Reactor.invalidate(parentItem, key);
864
+ }
865
+ parentItem.fire?.('changed');
866
+ }
867
+ }
868
+ WORK.chatEvents.dispatchEvent(new CustomEvent('node.deleted', { detail: data }));
869
+ } break;
846
870
  case 'chat:message':
847
871
  case 'chat:read': {
848
872
  WORK.chatEvents ??= new EventTarget();
@@ -104,6 +104,23 @@ export function broadcastUserSettings(uid, settings) {
104
104
  }
105
105
  }
106
106
 
107
+ /** Разослать активным сессиям событие удаления узла/класса дерева. */
108
+ export function broadcastNodeDeleted(nodePath, parentPath = '/') {
109
+ const clean = String(nodePath || '').replace(/\/+$/, '');
110
+ if (!clean || clean === '/')
111
+ return;
112
+ const parentClean = String(parentPath || '/').replace(/\/+$/, '') || '/';
113
+ const raw = JSON.stringify({ type: 'node.deleted', path: clean, parentPath: parentClean });
114
+ for (const session of allSessions()) {
115
+ if (!session?.uid)
116
+ continue;
117
+ for (const sock of Object.values(session.sockets || {})) {
118
+ if (sock?.ws?.readyState === 1)
119
+ sock.ws.send(raw);
120
+ }
121
+ }
122
+ }
123
+
107
124
  export function onWebSocketConnect(ws, request) {
108
125
  // Настоящий Chrome пользователя через расширение MV3: авторизуется токеном wmcp. (без cookies)
109
126
  if (String(request?.url || '').split('?')[0] === '/~chrome') {
@@ -297,7 +297,11 @@ export async function listAvailableChatModels() {
297
297
  const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
298
298
  const name = String(m.id || m.DATA?.label || m.label || m.path || '');
299
299
  const label = String(m.DATA?.label || m.label || m.id || m.path || '');
300
- const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
300
+ const proto = String(m.protocol || m.DATA?.protocol || '').toLowerCase();
301
+ const wfmt = String(m.weightFormat || m.DATA?.weightFormat || '').toLowerCase();
302
+ const isCompactOrPythonLocal = /(?:^|[-_\s])(4b|2b|1\.7b|0\.6b)(?:$|[-_\s])/i.test(name)
303
+ || (String(provider.id || '').toLowerCase() === 'local' && proto !== 'halogen' && wfmt !== 'gguf' && !/flash-next/i.test(name));
304
+ const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name) && !isCompactOrPythonLocal;
301
305
  out.push({
302
306
  path: m.path,
303
307
  label: provLabel ? `${label} (${provLabel})` : label,
@@ -310,12 +314,15 @@ export async function listAvailableChatModels() {
310
314
  return out;
311
315
  }
312
316
 
313
- /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
317
+ /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор и не Python-малютка). */
314
318
  export async function findFirstAvailableChatModel() {
315
319
  const list = await listAvailableChatModels();
316
320
  const def = list.find(m => m.active && m.default);
317
321
  if (def)
318
322
  return def.path;
323
+ const flash = list.find(m => m.active && /flash-next/i.test(m.path));
324
+ if (flash)
325
+ return flash.path;
319
326
  const primary = list.find(m => m.isPrimary);
320
327
  if (primary)
321
328
  return primary.path;
@@ -629,14 +636,26 @@ export async function createEnv({ place, contextPath, session, host, tz, locatio
629
636
  return [stable, volatile].filter(Boolean).join('\n\n');
630
637
  },
631
638
  async defaultModel() {
632
- const candidate = remapModelPath(config.model || DEFAULT_MODEL);
633
- const item = await WORK.get_item(candidate).catch(() => null);
639
+ if (config.model) {
640
+ const candidate = remapModelPath(config.model);
641
+ const item = await WORK.get_item(candidate).catch(() => null);
642
+ if (item) {
643
+ await item.init?.catch?.(() => {});
644
+ if (typeof item.streamChat === 'function')
645
+ return candidate;
646
+ }
647
+ }
648
+ const first = await findFirstAvailableChatModel();
649
+ if (first)
650
+ return first;
651
+ const fallback = remapModelPath(DEFAULT_MODEL);
652
+ const item = await WORK.get_item(fallback).catch(() => null);
634
653
  if (item) {
635
654
  await item.init?.catch?.(() => {});
636
655
  if (typeof item.streamChat === 'function')
637
- return candidate;
656
+ return fallback;
638
657
  }
639
- return (await findFirstAvailableChatModel()) || candidate;
658
+ return fallback;
640
659
  },
641
660
  /** Память изменена инструментом memory — пересобрать блок на следующем ходе. */
642
661
  resetMemory() {
@@ -193,11 +193,13 @@ export function resolveApprovalScope(tool, args, ctx) {
193
193
  }
194
194
  if (tool.name === 'shell')
195
195
  return classifyShellCommand(args?.command);
196
+ if (tool.risk === 'danger')
197
+ return { noAlways: true, key: tool.name, label: '', buttonLabel: '' };
196
198
  const title = tool.label || tool.name;
197
199
  return {
198
200
  key: tool.name,
199
201
  label: 'все вызовы «' + title + '» в этой задаче',
200
- buttonLabel: 'Разрешить в задаче',
202
+ buttonLabel: 'Больше не спрашивать в этой задаче',
201
203
  };
202
204
  }
203
205
 
@@ -262,7 +264,7 @@ export async function decide(tool, args, ctx) {
262
264
  if (hit)
263
265
  return { verdict: 'ask', noAlways: true, reason: 'изменение системы: ' + hit };
264
266
  if (tool.risk === 'danger')
265
- return { verdict: 'ask', reason: 'необратимое или внешнее действие', ...(scope?.noAlways ? { noAlways: true } : { scope }) };
267
+ return { verdict: 'ask', noAlways: true, reason: 'необратимое или внешнее действие' };
266
268
  if (allowedMatches(host, tool.name, scope))
267
269
  return { verdict: 'allow', autoAllowed: true, scopeKey: scope?.key || tool.name, scopeLabel: scope?.label || '' };
268
270
  if (mode === 'ask')
@@ -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
- return {
240
- targetPath: `/NODES/${segs[1]}`,
241
- reason: `Работа с узлом сети «${segs[1]}» (${p}) должна выполняться в контексте этого узла.`,
242
- needBoss: !tool.readonly,
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
- await WORK.fsp.writeFile(dir, text, 'utf-8');
145
- await WORK.fsp.unlink(tmp).catch(() => {});
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
- session?.send?.({ path: s.file.short });
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) {
@@ -617,13 +661,13 @@ function start(s, session, file, licenseOpts = {}) {
617
661
  body.items.push({ ...u, queued: undefined });
618
662
  }
619
663
  restart = rest.length > 0 && !aborted && body.status !== 'error';
620
- await save(s, session);
664
+ await save(s, session).catch(e => log.debug('task.finalSave', e));
621
665
  s.running = null;
622
666
  }
623
667
  }
624
668
  if (movedAway)
625
669
  return;
626
- if (restart) {
670
+ if (restart && !s.missingOnDisk) {
627
671
  start(s, session, file);
628
672
  return;
629
673
  }
@@ -1176,6 +1220,13 @@ export async function approve(file, params = {}) {
1176
1220
  await assertTaskOwner(file, params);
1177
1221
  const s = stateOf(file);
1178
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
+ }
1179
1230
  const body = await getBody(file);
1180
1231
  const call = p.call || body.waiting?.call;
1181
1232
  const reply = {
@@ -1216,6 +1267,8 @@ export async function approve(file, params = {}) {
1216
1267
  export async function explainCall(file, params = {}) {
1217
1268
  await assertTaskOwner(file, params);
1218
1269
  const s = stateOf(file);
1270
+ if (file?.dir && !fs.existsSync(file.dir))
1271
+ return { ok: false, error: 'Задача или её узел уже удалены' };
1219
1272
  const p = argsOf(params);
1220
1273
  const body = await getBody(file);
1221
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
  });