odant-work 1.0.78 → 1.0.80

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.
@@ -703,6 +703,222 @@ export async function listNodeNetworkNodes(storage, params = {}) {
703
703
  return { nodes: out };
704
704
  }
705
705
 
706
+ /**
707
+ * Единый контекст для вкладки «Пользователи» и «Классы и модули» подразделения / $base:
708
+ * реальные пользователи, подразделения, серверы сети, унаследованный BOSS,
709
+ * полное дерево классов вышестоящего $base и доступные модули /MODULES.
710
+ */
711
+ export async function getNodeStaffContext(storage, params = {}) {
712
+ await assertBoss(storage, params);
713
+ const WORK = globalThis.WORK;
714
+ if (!WORK)
715
+ return { users: [], structures: [], networkNodes: [], inheritedBoss: null, baseClasses: [], systemModules: [], basePath: '' };
716
+
717
+ // 1. Пользователи /USERS
718
+ const users = [];
719
+ const userMap = new Map();
720
+ const uRoot = (await WORK.get_item('/USERS').catch(() => null)) || (await WORK.get_item('/users').catch(() => null));
721
+ const uItems = await Promise.resolve(uRoot?.items).catch(() => []) || [];
722
+ for (const u of uItems) {
723
+ if (!u?.id || u.id[0] === '$')
724
+ continue;
725
+ await u.init?.catch?.(() => {});
726
+ const entry = {
727
+ id: u.id,
728
+ label: u.DATA?.label || u.label || u.id,
729
+ icon: u.DATA?.icon || u.icon || '',
730
+ iconColor: u.iconColor || '',
731
+ };
732
+ users.push(entry);
733
+ userMap.set(u.id, entry);
734
+ }
735
+
736
+ // 2. Унаследованный руководитель (BOSS) вверх по дереву (включая корень '/')
737
+ let inheritedBoss = null;
738
+ try {
739
+ const chain = [];
740
+ for (let anc = storage?.$parent; anc; anc = anc.$parent) {
741
+ if (anc instanceof FS.$class)
742
+ chain.push(anc);
743
+ }
744
+ if (!chain.some(a => a === WORK || a.path === '/'))
745
+ chain.push(WORK);
746
+ for (const anc of chain) {
747
+ await anc.init?.catch?.(() => {});
748
+ const localIds = typeof anc._roleIds === 'function'
749
+ ? anc._roleIds('BOSS')
750
+ : (Array.isArray(anc.DATA?.['#security']?.BOSS) ? anc.DATA['#security'].BOSS : []);
751
+ const cleanIds = (Array.isArray(localIds) ? localIds : []).filter(v => typeof v === 'string' && v.trim());
752
+ if (cleanIds.length) {
753
+ const resolved = cleanIds.slice(0, 1).map(uid => {
754
+ const found = userMap.get(uid);
755
+ return found
756
+ ? { ...found, missing: false }
757
+ : { id: uid, label: `${uid} (не найден в /USERS)`, icon: 'icons:person', iconColor: '', missing: true };
758
+ });
759
+ const ancPath = anc.path || '/';
760
+ inheritedBoss = {
761
+ fromPath: ancPath,
762
+ fromLabel: anc.DATA?.label || anc.label || anc.id || (ancPath === '/' ? 'WORK' : ancPath),
763
+ users: resolved,
764
+ };
765
+ break;
766
+ }
767
+ }
768
+ }
769
+ catch { /* ignore */ }
770
+
771
+ // 3. Подразделения и серверы сети
772
+ const [structRes, netRes] = await Promise.all([
773
+ listNodeStructures(storage, params).catch(() => ({ structures: [] })),
774
+ listNodeNetworkNodes(storage, params).catch(() => ({ nodes: [] })),
775
+ ]);
776
+
777
+ // 4. Полное дерево всех классов, установленных в вышестоящий $base ($project)
778
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
779
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
780
+ const basePath = baseMatch ? baseMatch[1] : '';
781
+ const modRootPath = basePath ? `${basePath}/MODULES` : '/MODULES';
782
+ const baseClasses = [];
783
+ const installedModIds = new Set();
784
+
785
+ const walkClasses = async (node, depth = 0) => {
786
+ if (!node || depth > 7)
787
+ return null;
788
+ await node.init?.catch?.(() => {});
789
+ if (!node.id || node.id[0] === '$')
790
+ return null;
791
+ const t = node.type;
792
+ const isAllowed = DATA_CLASS_TYPES.has(t) || t === '$module' || t === '$domain' || t === '$class' || t === '$folder';
793
+ if (!isAllowed)
794
+ return null;
795
+ if (t === '$module')
796
+ installedModIds.add(node.id);
797
+ const items = await Promise.resolve(node.items).catch(() => []) || [];
798
+ const children = [];
799
+ for (const ch of items) {
800
+ if (!ch || ch.id?.[0] === '$')
801
+ continue;
802
+ const built = await walkClasses(ch, depth + 1);
803
+ if (built)
804
+ children.push(built);
805
+ }
806
+ return {
807
+ id: node.id,
808
+ path: node.path,
809
+ label: node.DATA?.label || node.label || node.id,
810
+ type: t,
811
+ icon: node.DATA?.icon || node.icon || (t === '$module' ? 'odant:module' : 'odant:class'),
812
+ children,
813
+ };
814
+ };
815
+
816
+ const modRootItem = await WORK.get_item(modRootPath).catch(() => null);
817
+ if (modRootItem) {
818
+ const modKids = await Promise.resolve(modRootItem.items).catch(() => []) || [];
819
+ for (const mk of modKids) {
820
+ if (!mk || mk.id?.[0] === '$')
821
+ continue;
822
+ const built = await walkClasses(mk, 0);
823
+ if (built)
824
+ baseClasses.push(built);
825
+ }
826
+ }
827
+
828
+ // 5. Доступные эталонные модули в корневом /MODULES
829
+ const systemModules = [];
830
+ const sysModRoot = await WORK.get_item('/MODULES').catch(() => null);
831
+ if (sysModRoot) {
832
+ const sysKids = await Promise.resolve(sysModRoot.items).catch(() => []) || [];
833
+ for (const sm of sysKids) {
834
+ if (!sm || sm.id?.[0] === '$' || sm.type !== '$module')
835
+ continue;
836
+ await sm.init?.catch?.(() => {});
837
+ systemModules.push({
838
+ id: sm.id,
839
+ path: sm.path,
840
+ label: sm.DATA?.label || sm.label || sm.id,
841
+ icon: sm.DATA?.icon || sm.icon || 'odant:module',
842
+ installed: installedModIds.has(sm.id),
843
+ });
844
+ }
845
+ }
846
+
847
+ return {
848
+ users,
849
+ structures: structRes.structures || [],
850
+ networkNodes: netRes.nodes || [],
851
+ inheritedBoss,
852
+ basePath,
853
+ modRootPath,
854
+ baseClasses,
855
+ systemModules,
856
+ };
857
+ }
858
+
859
+ /**
860
+ * Подключить эталонный модуль из `/MODULES/<id>` в `<$base>/MODULES`.
861
+ */
862
+ export async function installBaseModule(storage, params = {}) {
863
+ await assertBoss(storage, params);
864
+ const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
865
+ const modId = String(post.moduleId || post.id || '').trim();
866
+ if (!modId || /[\\/.$#]/.test(modId))
867
+ throw new Error('Укажите корректный идентификатор модуля');
868
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
869
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
870
+ if (!baseMatch)
871
+ throw new Error('Подключение модулей выполняется в контексте организации или проекта');
872
+ const baseItem = await globalThis.WORK.get_item(baseMatch[1]).catch(() => null);
873
+ if (!baseItem)
874
+ throw new Error('Не найден корневой объект организации');
875
+ let modDomain = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES`).catch(() => null);
876
+ if (!modDomain && typeof baseItem.create === 'function') {
877
+ await baseItem.create({ ...params, id: 'MODULES', type: '$domain', label: 'Модули' });
878
+ modDomain = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES`).catch(() => null);
879
+ }
880
+ if (!modDomain)
881
+ throw new Error('Не найден домен MODULES');
882
+ const exists = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES/${modId}`).catch(() => null);
883
+ if (exists)
884
+ return { ok: true, alreadyInstalled: true, path: exists.path };
885
+ await modDomain.create({ ...params, id: modId, type: '$module' });
886
+ await recordBossSettingTask(storage, params, {
887
+ title: `Подключён модуль «${modId}»`,
888
+ summary: `В ${baseMatch[1]} подключён модуль /MODULES/${modId}.`,
889
+ });
890
+ return { ok: true, path: `${baseMatch[1]}/MODULES/${modId}` };
891
+ }
892
+
893
+ /**
894
+ * Создать новый класс или подкласс внутри `<$base>/MODULES`.
895
+ */
896
+ export async function createBaseClass(storage, params = {}) {
897
+ await assertBoss(storage, params);
898
+ const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
899
+ const parentPath = String(post.parentPath || '').trim();
900
+ const id = String(post.id || post.label || '').trim();
901
+ const label = String(post.label || id).trim();
902
+ const type = String(post.type || '$catalog').trim();
903
+ if (!id)
904
+ throw new Error('Укажите название класса');
905
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
906
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
907
+ if (!baseMatch)
908
+ throw new Error('Создание класса выполняется в контексте организации или проекта');
909
+ const modPrefix = `${baseMatch[1]}/MODULES`;
910
+ const targetParentPath = parentPath && parentPath.startsWith(modPrefix) ? parentPath : modPrefix;
911
+ const parentItem = await globalThis.WORK.get_item(targetParentPath).catch(() => null);
912
+ if (!parentItem || typeof parentItem.create !== 'function')
913
+ throw new Error('Не найден родительский контейнер: ' + targetParentPath);
914
+ await parentItem.create({ ...params, id, label, type });
915
+ await recordBossSettingTask(storage, params, {
916
+ title: `Создан класс «${label}» (${type})`,
917
+ summary: `В ${targetParentPath} создан класс «${label}» типа ${type}.`,
918
+ });
919
+ return { ok: true, path: `${targetParentPath}/${id}` };
920
+ }
921
+
706
922
  /**
707
923
  * Последние выполненные задачи `.task` подразделения (для повторения по расписанию).
708
924
  */
@@ -46,7 +46,7 @@ export const MEMBERS = Object.freeze({
46
46
  mail_draft_save: L.WRITE, mail_send: L.WRITE, mail_state: L.WRITE, mail_refresh: L.WRITE,
47
47
  calendar_list: L.READ, calendar_save: L.WRITE,
48
48
  agent_rules_list: L.READ, agent_rule_save: L.ADMIN, agent_schedule_save: L.ADMIN, agent_proactivity_save: L.ADMIN,
49
- agent_system_get: L.READ, agent_system_save: L.ADMIN, agent_available_classes: L.READ, agent_structures_list: L.READ, agent_network_nodes: L.READ, agent_tasks_list: L.READ,
49
+ agent_system_get: L.READ, agent_system_save: L.ADMIN, agent_available_classes: L.READ, agent_structures_list: L.READ, agent_network_nodes: L.READ, agent_staff_context: L.READ, agent_base_module_install: L.ADMIN, agent_base_class_create: L.ADMIN, agent_tasks_list: L.READ,
50
50
  security_update: L.ADMIN,
51
51
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
52
52
  work_zone: L.READ, places: L.READ,
@@ -85,10 +85,10 @@ export const MEMBERS = Object.freeze({
85
85
  ...Object.fromEntries(Object.entries(KLADR_METHODS).map(([name, m]) => [name, m.level])),
86
86
  remove_push_subscription: L.WRITE, send_push_notification: L.WRITE,
87
87
  // администрирование
88
- delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, read_secret: L.ADMIN,
88
+ delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, restart_server: L.ADMIN, read_secret: L.ADMIN,
89
89
  save_secret: L.ADMIN, clear_rag: L.ADMIN, security_log: L.ADMIN, agent_panel: L.ADMIN,
90
90
  set_enabled: L.ADMIN, export_archive: L.READ, import_archive: L.ADMIN, delete_log_entry: L.WRITE,
91
- distro_info: L.READ, export_distro: L.READ,
91
+ distro_info: L.READ, export_distro: L.READ, version_status: L.READ, version_update_restart: L.ADMIN,
92
92
  });
93
93
 
94
94
  /** Никогда не вызываются снаружи, даже если объявлены в class.js. */
@@ -130,6 +130,7 @@ export function normalizePlaces(raw, seen = new Set(), depth = 0) {
130
130
  label: typeof r.label === 'string' && r.label ? r.label : id,
131
131
  icon: typeof r.icon === 'string' ? r.icon : '',
132
132
  ...(r.external ? { external: true } : {}),
133
+ ...(r.readonly ? { readonly: true } : {}),
133
134
  USERS: Array.isArray(r.USERS) ? r.USERS.filter(u => typeof u === 'string') : [],
134
135
  LINKS: links,
135
136
  ROLES: normalizePlaces(r.ROLES, seen, depth + 1),
@@ -254,6 +254,24 @@ export const classFeedMethods = {
254
254
  return listNodeNetworkNodes(this, params);
255
255
  },
256
256
 
257
+ /** Единый контекст для вкладки «Пользователи» и «Классы и модули» (только BOSS). */
258
+ async agent_staff_context(params = {}) {
259
+ const { getNodeStaffContext } = await import('../../modules/agent/node-rules.js');
260
+ return getNodeStaffContext(this, params);
261
+ },
262
+
263
+ /** Подключить эталонный модуль из /MODULES в организацию/проект (только BOSS). */
264
+ async agent_base_module_install(params = {}) {
265
+ const { installBaseModule } = await import('../../modules/agent/node-rules.js');
266
+ return installBaseModule(this, params);
267
+ },
268
+
269
+ /** Создать новый класс внутри модулей организации/проекта (только BOSS). */
270
+ async agent_base_class_create(params = {}) {
271
+ const { createBaseClass } = await import('../../modules/agent/node-rules.js');
272
+ return createBaseClass(this, params);
273
+ },
274
+
257
275
  /** Список последних выполненных задач (.task) узла для повторения по расписанию (только BOSS). */
258
276
  async agent_tasks_list(params = {}) {
259
277
  const { listNodeTasks } = await import('../../modules/agent/node-rules.js');
@@ -1,6 +1,7 @@
1
1
  import * as http from "node:http";
2
2
  import * as https from "node:https";
3
3
  import * as fs from "node:fs";
4
+ import * as path from "node:path";
4
5
  import { createHash, randomBytes } from "node:crypto";
5
6
  import * as mime from "mime-types";
6
7
  import * as fsp from "node:fs/promises";
@@ -721,21 +722,84 @@ export class $server extends $class {
721
722
  }
722
723
 
723
724
  /**
724
- * Отложенный штатный перезапуск процесса WORK (например после правки ядра sources/).
725
- * Работает как в DEV_MODE, так и в обычном режиме; доступен только BOSS корневого WORK.
725
+ * Получить статус версии WORK (запущенная, на диске, последняя в npm).
726
+ * Если передан check=1 и пользователь — BOSS корня, выполняет мгновенную проверку npm.
726
727
  */
727
- async restart_server(params = {}) {
728
+ async version_status(params = {}) {
729
+ const rootDir = this.dir || process.cwd();
730
+ const uid = $class.resolveUid(params);
731
+ const roles = uid ? await this.roles(params).catch(() => []) : [];
732
+ const canUpdate = Boolean(DEV_MODE || roles.includes('BOSS'));
733
+ const { checkForNpmUpdates, getVersionStatus } = await import('../host/auto-updater.js');
734
+ let checkError = null;
735
+ if (params.check && params.check !== '0' && params.check !== 'false' && canUpdate) {
736
+ try {
737
+ await checkForNpmUpdates({ rootDir });
738
+ }
739
+ catch (err) {
740
+ checkError = String(err?.message || err);
741
+ }
742
+ }
743
+ const status = getVersionStatus({ rootDir });
744
+ return {
745
+ ...status,
746
+ canUpdate,
747
+ ...(checkError ? { checkError } : {}),
748
+ };
749
+ }
750
+
751
+ /**
752
+ * При наличии новой версии скачать и применить её из npm (с сохранением данных и правок),
753
+ * затем перезапустить сервер уже в новой версии. Доступно только BOSS корневого WORK.
754
+ */
755
+ async version_update_restart(params = {}) {
728
756
  const uid = $class.resolveUid(params);
729
757
  if (!uid)
730
758
  throw new Error('Доступ запрещён');
731
759
  const roles = await this.roles(params).catch(() => []);
732
760
  if (!roles.includes('BOSS'))
733
761
  throw new Error('Доступ запрещён');
762
+
763
+ const rootDir = path.resolve(this.dir || process.cwd());
764
+ const { checkAndApplyNpmUpdate, getVersionStatus } = await import('../host/auto-updater.js');
765
+ const before = getVersionStatus({ rootDir });
766
+ let applyResult = null;
767
+ if (before.needsDownload || !before.updateAvailable) {
768
+ applyResult = await checkAndApplyNpmUpdate({ rootDir, installDeps: true });
769
+ }
770
+ const after = getVersionStatus({ rootDir });
771
+ if (!after.updateAvailable && !applyResult?.updated) {
772
+ return {
773
+ restarted: false,
774
+ updated: false,
775
+ status: after,
776
+ };
777
+ }
778
+
779
+ const localRunMjs = path.join(rootDir, 'run.mjs');
780
+ const extraArgs = process.argv.slice(2);
781
+ const entryArgs = fs.existsSync(localRunMjs)
782
+ ? [localRunMjs, ...extraArgs]
783
+ : (process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs']);
784
+ const delayMs = await this._scheduleProcessRestart({ cwd: rootDir, entryArgs, delayMs: params.delayMs });
785
+ return {
786
+ restarted: true,
787
+ updated: true,
788
+ fromVersion: before.runningVersion,
789
+ toVersion: after.latestVersion,
790
+ delayMs,
791
+ status: after,
792
+ };
793
+ }
794
+
795
+ async _scheduleProcessRestart({ cwd = process.cwd(), entryArgs, delayMs: rawDelay } = {}) {
734
796
  const { spawn } = await import('node:child_process');
735
797
  const env = { ...process.env };
736
798
  delete env.NODE_OPTIONS;
737
- const entryArgs = process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs'];
738
- const delayMs = Math.max(1500, Math.min(10000, Number(params.delayMs) || 2500));
799
+ const args = Array.isArray(entryArgs) && entryArgs.length
800
+ ? entryArgs
801
+ : (process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs']);
802
+ const delayMs = Math.max(1500, Math.min(10000, Number(rawDelay) || 2500));
739
803
  const helper = `
740
804
  const fs = await import('node:fs');
741
805
  const path = await import('node:path');
@@ -756,10 +820,25 @@ export class $server extends $class {
756
820
  child.unref();
757
821
  `;
758
822
  spawn(process.execPath, ['--input-type=module', '-e', helper,
759
- String(process.pid), process.cwd(), JSON.stringify(env), JSON.stringify(entryArgs)], {
823
+ String(process.pid), cwd, JSON.stringify(env), JSON.stringify(args)], {
760
824
  detached: true, stdio: 'ignore', env,
761
825
  }).unref();
762
826
  setTimeout(() => process.exit(0), delayMs).unref?.();
827
+ return delayMs;
828
+ }
829
+
830
+ /**
831
+ * Отложенный штатный перезапуск процесса WORK (например после правки ядра sources/).
832
+ * Работает как в DEV_MODE, так и в обычном режиме; доступен только BOSS корневого WORK.
833
+ */
834
+ async restart_server(params = {}) {
835
+ const uid = $class.resolveUid(params);
836
+ if (!uid)
837
+ throw new Error('Доступ запрещён');
838
+ const roles = await this.roles(params).catch(() => []);
839
+ if (!roles.includes('BOSS'))
840
+ throw new Error('Доступ запрещён');
841
+ const delayMs = await this._scheduleProcessRestart({ delayMs: params.delayMs });
763
842
  return { scheduled: true, delayMs };
764
843
  }
765
844
  }
package/sources/work.js CHANGED
@@ -119,12 +119,17 @@ if (process.env.WORK_SWEEP !== '0') {
119
119
  }, 2 * 60_000).unref?.();
120
120
  }
121
121
 
122
- // Автообновление из npm (с сохранением пользовательских баз, классов, файлов и настроек)
122
+ // Автообновление из npm (проверка каждые 10 мин; применение и перезапуск — по клику на ноде WORK)
123
123
  // и периодическая синхронизация лицензий по привязанному токену владельца (#system/owner-token.json)
124
+ import('./host/auto-updater.js')
125
+ .then(m => {
126
+ m.getRunningVersion('.');
127
+ if (process.env.WORK_AUTO_UPDATE !== '0' && !process.env.WORK_TEST)
128
+ m.startAutoUpdateDaemon();
129
+ })
130
+ .catch(e => console.warn('[auto-updater]', e?.message || e));
131
+
124
132
  if (process.env.WORK_AUTO_UPDATE !== '0' && !process.env.WORK_TEST) {
125
- import('./host/auto-updater.js')
126
- .then(m => m.startAutoUpdateDaemon())
127
- .catch(e => console.warn('[auto-updater]', e?.message || e));
128
133
 
129
134
  // Первичная и адаптивная автосинхронизация лицензий (Q10):
130
135
  // через 5 с после старта; каждые 30 с пока базовая лицензия ожидает активации, затем каждые 15 мин.