odant-work 1.0.101 → 1.0.103

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 (83) hide show
  1. package/$server/$folder/$class/$structure/$department/ai/config.js +9 -0
  2. package/$server/$folder/$class/$structure/$department/ai/system.md +11 -0
  3. package/$server/$folder/$class/$structure/$department/class.js +9 -0
  4. package/$server/$folder/$class/$structure/$project/ai/config.js +9 -0
  5. package/$server/$folder/$class/$structure/$project/ai/system.md +12 -0
  6. package/$server/$folder/$class/$structure/$project/class.js +4 -1
  7. package/$server/$folder/$class/$structure/$project/handlers/pages/site/$handler/class.js +1 -1
  8. package/$server/$folder/$class/$structure/$server/ai/config.js +9 -0
  9. package/$server/$folder/$class/$structure/$server/ai/system.md +10 -0
  10. package/$server/$folder/$class/$structure/$server/class.js +2 -0
  11. package/$server/$folder/$class/$structure/$user/ai/config.js +9 -0
  12. package/$server/$folder/$class/$structure/$user/ai/system.md +8 -0
  13. package/$server/$folder/$class/$structure/$user/class.js +2 -0
  14. package/$server/$folder/$class/$structure/ai/system.md +1 -1
  15. package/$server/$folder/$class/$structure/class.js +4 -2
  16. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
  17. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +91 -22
  18. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +132 -3
  19. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2 -2
  20. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +2 -1
  21. package/$server/$folder/$class/ai/system.md +2 -2
  22. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +38 -8
  23. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +22 -31
  24. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
  25. package/$server/$folder/handlers/pages/form/$handler/class.js +47 -5
  26. package/$server/$folder/lib/chat-item/chat-item.js +14 -2
  27. package/$server/$folder/lib/consultant/consultant.js +81 -4
  28. package/$server/$folder/lib/explorer/explorer.js +20 -11
  29. package/$server/$folder/lib/icon/icon.js +1 -1
  30. package/$server/$folder/lib/node/node.js +3 -3
  31. package/$server/$folder/lib/site-loc/site-loc.js +8 -3
  32. package/$server/$folder/lib/tree/tree.js +8 -8
  33. package/AGENTS.md +3 -3
  34. package/autostart.bat +28 -0
  35. package/autostart.sh +17 -0
  36. package/package.json +1 -1
  37. package/run.mjs +19 -0
  38. package/scripts/autostart.mjs +281 -0
  39. package/scripts/import-bis.mjs +5 -5
  40. package/scripts/import-delovaya.mjs +5 -5
  41. package/scripts/watchdog.mjs +496 -0
  42. package/sources/client/class.js +1 -1
  43. package/sources/client.js +141 -8
  44. package/sources/data/api.js +1 -1
  45. package/sources/data/classes.js +2 -1
  46. package/sources/data/schema.js +2 -0
  47. package/sources/host/auth-methods.js +3 -1
  48. package/sources/host/auto-updater.js +23 -1
  49. package/sources/host/http-server.js +5 -3
  50. package/sources/host/push.js +43 -14
  51. package/sources/host/websocket.js +52 -3
  52. package/sources/modules/agent/index.js +38 -10
  53. package/sources/modules/agent/node-rules.js +353 -9
  54. package/sources/modules/agent/scheduler.js +7 -0
  55. package/sources/modules/agent/scope.js +8 -6
  56. package/sources/modules/agent/session.js +38 -8
  57. package/sources/modules/agent/tools/work/access.js +1 -1
  58. package/sources/modules/agent/tools/work/classes.js +1 -1
  59. package/sources/modules/agent/triggers.js +1 -1
  60. package/sources/modules/agent/twin-bus.js +2 -1
  61. package/sources/modules/notify/index.js +5 -2
  62. package/sources/modules/trainer/local-engine.js +3 -1
  63. package/sources/modules/user-profile/user-profile.js +129 -0
  64. package/sources/server/access/gateway.js +5 -3
  65. package/sources/server/access/links.js +9 -6
  66. package/sources/server/chat-threads.js +1 -1
  67. package/sources/server/class/base-template.js +3 -2
  68. package/sources/server/class/feed.js +36 -0
  69. package/sources/server/class/scaffold.js +137 -0
  70. package/sources/server/class/search.js +2 -2
  71. package/sources/server/class/security.js +1 -1
  72. package/sources/server/class.js +5 -3
  73. package/sources/server/folder.js +10 -6
  74. package/sources/server/logs.js +14 -0
  75. package/sources/server/node.js +1 -1
  76. package/sources/server/server.js +50 -1
  77. package/sources/server/user.js +45 -0
  78. package/sources/work.js +7 -0
  79. package/start.bat +25 -0
  80. package/start.sh +27 -0
  81. package/stop.bat +25 -0
  82. package/stop.sh +16 -0
  83. package/sw.js +3 -11
@@ -13,6 +13,7 @@ import crypto from 'node:crypto';
13
13
  import { spawn } from 'node:child_process';
14
14
  import { dataStore } from '../../data/api.js';
15
15
  import { classesOfType } from '../../data/classes.js';
16
+ import { departmentMetaNameSync } from '../../server/class/scaffold.js';
16
17
  import { classSchema } from '../../data/schema.js';
17
18
  import { trialBalance } from '../../data/reports.js';
18
19
  import { ensureHalogenBackendRunning, recordHalogenSessionHandle, stopHalogenBackend } from './halogen.js';
@@ -563,7 +564,8 @@ async function buildCompactGrounding(question, basePath = '/PROJECTS/Масло
563
564
  }
564
565
 
565
566
  if (/организац|подразделен|модул|структур|доступн|систем|отдел/i.test(q)) {
566
- const structs = classesOfType(db, '$structure').map(s => `${s.label} (${s.path})`).join(', ');
567
+ const deptType = departmentMetaNameSync();
568
+ const structs = (deptType ? classesOfType(db, deptType) : []).map(s => `${s.label} (${s.path})`).join(', ');
567
569
  facts.push(
568
570
  `Данные системы WORK: в домене /PROJECTS находится организация ООО «Маслоторг» (/PROJECTS/Маслоторг, тип $project). ` +
569
571
  `Её подразделения: ${structs}. ` +
@@ -49,6 +49,49 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
49
49
  border-radius: 8px;
50
50
  padding: 6px 8px;
51
51
  }
52
+ .settings-card {
53
+ gap: 10px;
54
+ border: 1px solid var(--border-color, #cbd5e1);
55
+ border-radius: 10px;
56
+ padding: 12px 14px;
57
+ background: var(--content-background, #fff);
58
+ box-sizing: border-box;
59
+ }
60
+ .settings-title {
61
+ font-weight: 600;
62
+ font-size: 15px;
63
+ }
64
+ .settings-field {
65
+ gap: 4px;
66
+ font-size: 14px;
67
+ }
68
+ .settings-field select {
69
+ border: 1px solid gray;
70
+ padding: 8px;
71
+ border-radius: 8px;
72
+ font-size: 14px;
73
+ width: 100%;
74
+ box-sizing: border-box;
75
+ background: inherit;
76
+ color: inherit;
77
+ }
78
+ .settings-toggle {
79
+ gap: 8px;
80
+ align-items: center;
81
+ font-size: 14px;
82
+ cursor: pointer;
83
+ }
84
+ .settings-toggle input {
85
+ width: 18px;
86
+ height: 18px;
87
+ margin: 0;
88
+ flex-shrink: 0;
89
+ cursor: pointer;
90
+ }
91
+ .settings-hint {
92
+ font-size: 12px;
93
+ color: #10b981;
94
+ }
52
95
  </style>
53
96
  <div no-flex vertical class="profile-wrap">
54
97
  <div ~if="pendingInvite?.valid" style="padding:10px 12px;border-radius:8px;border:1px solid #10b981;background:rgba(16,185,129,0.1);font-size:small;line-height:1.4;text-align:center;">
@@ -70,6 +113,21 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
70
113
  </div>
71
114
  <div flex style="text-align: center;" ~html="state.legend"></div>
72
115
  <div flex style="text-align: center;" :error="!!error" @tap="fill_code">{{text}}</div>
116
+ <div class="settings-card" vertical ~if="!isOtherUser && isLogin">
117
+ <div class="settings-title">Личные настройки</div>
118
+ <label class="settings-field" vertical>
119
+ <span>Главная модель ИИ</span>
120
+ <select :value="settingModel" @change="_onSettingModelChange($event)">
121
+ <option value="">По умолчанию системы</option>
122
+ <option ~for="m in chatModels" :value="m.path" :selected="m.path === settingModel">{{m.label}}</option>
123
+ </select>
124
+ </label>
125
+ <label class="settings-toggle" horizontal>
126
+ <input type="checkbox" :checked="settingChatSound" @change="_onSettingChatSoundChange($event)">
127
+ <span>Звуковой щелчок по завершении ответа в открытом чате</span>
128
+ </label>
129
+ <div class="settings-hint" ~if="settingsStatus">{{settingsStatus}}</div>
130
+ </div>
73
131
  </div>
74
132
  `,
75
133
  $item: {
@@ -81,6 +139,10 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
81
139
  error: null,
82
140
  text: '',
83
141
  isLoggingIn: false,
142
+ chatModels: [],
143
+ settingModel: '',
144
+ settingChatSound: true,
145
+ settingsStatus: '',
84
146
  get isOtherUser() {
85
147
  return Boolean(this.$item?.id && WORK?.uid && this.$item.id !== WORK.uid);
86
148
  },
@@ -206,6 +268,7 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
206
268
  attached() {
207
269
  this._syncFromItem(this.$item);
208
270
  this._loadPendingInvite();
271
+ this._loadSettingsAndModels();
209
272
  this._onAuthState = () => {
210
273
  if (this.isOtherUser)
211
274
  return;
@@ -217,18 +280,84 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
217
280
  else if (this.isLogin) {
218
281
  this.error = null;
219
282
  this.text = '';
283
+ this._loadSettingsAndModels();
220
284
  }
221
285
  this.isLogin = undefined;
222
286
  this.render?.();
223
287
  };
288
+ this._onUserSettings = () => {
289
+ if (this.isOtherUser)
290
+ return;
291
+ this._applyLocalUserSettings();
292
+ };
224
293
  WORK.authEvents?.addEventListener?.('auth', this._onAuthState);
225
294
  WORK.authEvents?.addEventListener?.('login-state', this._onAuthState);
295
+ WORK.authEvents?.addEventListener?.('user-settings', this._onUserSettings);
226
296
  },
227
297
  detached() {
228
298
  if (this._onAuthState) {
229
299
  WORK.authEvents?.removeEventListener?.('auth', this._onAuthState);
230
300
  WORK.authEvents?.removeEventListener?.('login-state', this._onAuthState);
231
301
  }
302
+ if (this._onUserSettings) {
303
+ WORK.authEvents?.removeEventListener?.('user-settings', this._onUserSettings);
304
+ }
305
+ },
306
+ _applyLocalUserSettings() {
307
+ const s = WORK.userSettings || this.$item?.DATA?.settings || {};
308
+ this.settingModel = typeof s.aiModel === 'string' ? s.aiModel : '';
309
+ this.settingChatSound = s.chatSound !== false;
310
+ },
311
+ async _loadSettingsAndModels() {
312
+ if (this.isOtherUser || !this.isLogin)
313
+ return;
314
+ this._applyLocalUserSettings();
315
+ try {
316
+ if (typeof WORK.loadUserSettings === 'function') {
317
+ await WORK.loadUserSettings();
318
+ this._applyLocalUserSettings();
319
+ }
320
+ if (typeof WORK.fetch === 'function') {
321
+ const list = await WORK.fetch('/', 'agent_chat_models').catch(() => []);
322
+ if (Array.isArray(list))
323
+ this.chatModels = list;
324
+ }
325
+ }
326
+ catch { /* ignore */ }
327
+ },
328
+ async _saveProfileSetting(patch) {
329
+ this.settingsStatus = '';
330
+ try {
331
+ if (typeof WORK.saveUserSettings === 'function')
332
+ await WORK.saveUserSettings(patch);
333
+ if (patch && 'aiModel' in patch && patch.aiModel && typeof BroadcastChannel !== 'undefined') {
334
+ try { new BroadcastChannel('work-user-ai-model').postMessage({ model: patch.aiModel }); } catch {}
335
+ }
336
+ this._applyLocalUserSettings();
337
+ this.settingsStatus = 'Сохранено';
338
+ clearTimeout(this._settingsTimer);
339
+ this._settingsTimer = setTimeout(() => { this.settingsStatus = ''; }, 2000);
340
+ }
341
+ catch (err) {
342
+ this.settingsStatus = err?.message || 'Ошибка сохранения';
343
+ }
344
+ },
345
+ _onSettingModelChange(e) {
346
+ const val = String(e?.target?.value || '');
347
+ this.settingModel = val;
348
+ if (!val && typeof localStorage !== 'undefined') {
349
+ try {
350
+ const uid = WORK.uid || this.$item?.id || 'default';
351
+ localStorage.removeItem(`work.user.ai:${uid}:model`);
352
+ localStorage.removeItem('work.user.ai:default:model');
353
+ } catch {}
354
+ }
355
+ this._saveProfileSetting({ aiModel: val });
356
+ },
357
+ _onSettingChatSoundChange(e) {
358
+ const checked = Boolean(e?.target?.checked);
359
+ this.settingChatSound = checked;
360
+ this._saveProfileSetting({ chatSound: checked });
232
361
  },
233
362
  async _syncFromItem(item) {
234
363
  if (item?.id && WORK?.uid && item.id !== WORK.uid) {
@@ -46,7 +46,7 @@ export const MEMBERS = Object.freeze({
46
46
  mail_accounts: L.READ, mail_list: L.READ, mail_read: L.READ,
47
47
  mail_draft_save: L.WRITE, mail_send: L.WRITE, mail_state: L.WRITE, mail_refresh: L.WRITE,
48
48
  calendar_list: L.READ, calendar_save: L.WRITE,
49
- agent_rules_list: L.READ, agent_rule_save: L.BOSS, agent_schedule_save: L.BOSS, agent_proactivity_save: L.BOSS,
49
+ agent_rules_list: L.READ, agent_rule_save: L.BOSS, agent_schedule_save: L.BOSS, agent_proactivity_save: L.BOSS, agent_audit_run: L.BOSS,
50
50
  agent_system_get: L.READ, agent_system_save: L.BOSS, 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.BOSS, agent_base_class_create: L.BOSS, agent_tasks_list: L.READ,
51
51
  security_update: L.BOSS,
52
52
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
@@ -65,13 +65,15 @@ export const MEMBERS = Object.freeze({
65
65
  types: L.READ, system_types: L.READ, allowed_child_types: L.READ,
66
66
  // вошедший
67
67
  proxy: L.AUTH, node_grants: L.AUTH, mcp_token_create: L.AUTH, mcp_token_list: L.AUTH, mcp_token_revoke: L.AUTH,
68
+ store_push_subscription: L.AUTH, remove_push_subscription: L.AUTH, agent_default_model: L.AUTH, agent_chat_models: L.AUTH,
69
+ user_settings_get: L.AUTH, user_settings_save: L.AUTH,
68
70
  // сеть WORK
69
71
  network_graph: L.READ, remote: L.WRITE, node_add: L.BOSS, node_refresh: L.BOSS,
70
72
  // запись (точное право — внутри метода)
71
73
  save_file: L.WRITE, save_files: L.WRITE, save_includes: L.WRITE, save_message: L.WRITE, office_save: L.WRITE,
72
74
  append_log_includes: L.WRITE, save: L.WRITE, edit: L.WRITE, edit_file: L.WRITE,
73
75
  ensure_folder: L.WRITE, create: L.WRITE, write_to_stream: L.WRITE, close_write_stream: L.WRITE,
74
- restore_from_history: L.WRITE, store_push_subscription: L.WRITE,
76
+ restore_from_history: L.WRITE,
75
77
  // учётное ядро (sources/data/api.js): точное право — внутри метода
76
78
  ...Object.fromEntries(Object.entries(DATA_METHODS).map(([name, m]) => [name, m.level])),
77
79
  // локальные модели Hugging Face и дообучение Unsloth (sources/modules/trainer/index.js)
@@ -86,7 +88,7 @@ export const MEMBERS = Object.freeze({
86
88
  ...Object.fromEntries(Object.entries(INVITE_METHODS).map(([name, m]) => [name, m.level])),
87
89
  // адресный классификатор РФ и подразделения МВД (sources/modules/kladr/index.js)
88
90
  ...Object.fromEntries(Object.entries(KLADR_METHODS).map(([name, m]) => [name, m.level])),
89
- remove_push_subscription: L.WRITE, send_push_notification: L.WRITE,
91
+ send_push_notification: L.WRITE,
90
92
  // администрирование
91
93
  delete: L.BOSS, npm: L.BOSS, restart_normal: L.BOSS, restart_server: L.BOSS, read_secret: L.BOSS,
92
94
  save_secret: L.BOSS, clear_rag: L.BOSS, security_log: L.BOSS, agent_panel: L.BOSS,
@@ -12,9 +12,11 @@ import { FS } from '../index.js';
12
12
  import { DEV_MODE } from '../../host/config.js';
13
13
  import * as POLICY from './policy.js';
14
14
  import * as WORKPLACES from './workplaces.js';
15
+ import { departmentMetaNameSync } from '../class/scaffold.js';
15
16
 
16
17
  /** Типы, на которые ссылки не действуют (структура видна по своим правилам). */
17
18
  export const NO_LINK_TYPES = new Set(['$structure', '$group', '$user', '$project', '$server']);
19
+ const isNoLinkNode = (cls) => NO_LINK_TYPES.has(cls?.type) || cls?.DATA?.isStructure === true;
18
20
 
19
21
  /** Имена метапапок, в которых лежит class.js подразделения. */
20
22
  const STRUCTURE_METAS = WORKPLACES.STRUCTURE_META_NAMES;
@@ -59,7 +61,8 @@ async function collectSets() {
59
61
  && (e.name !== 'DATA' && e.name !== 'INDEX' || rel.split('/').some(s => s.startsWith('$'))))
60
62
  continue;
61
63
  const sub = rel ? rel + '/' + e.name : e.name;
62
- if (STRUCTURE_METAS.includes(e.name)) {
64
+ const deptMeta = departmentMetaNameSync(root);
65
+ if (STRUCTURE_METAS.includes(e.name) || (deptMeta && e.name === deptMeta)) {
63
66
  const segs = rel.split('/').filter(Boolean);
64
67
  if (segs.some(s => s.startsWith('$')))
65
68
  continue;
@@ -146,7 +149,7 @@ function linkSubject(cls, params = {}) {
146
149
  * между разными ролями права объединяются по максимуму.
147
150
  */
148
151
  export async function linkLevel(cls, params = {}) {
149
- if (NO_LINK_TYPES.has(cls.type))
152
+ if (isNoLinkNode(cls))
150
153
  return null;
151
154
  const subject = linkSubject(cls, params);
152
155
  const seenStruct = new Map();
@@ -234,7 +237,7 @@ async function structureItem(path) {
234
237
  * Учитывает RWCD, переопределение вниз по дереву классов и исключения `deniedPaths` (`none` или понижение ниже `minAccess`).
235
238
  */
236
239
  export async function scopeLinks(cls, params = {}, minAccess = 'read') {
237
- if (NO_LINK_TYPES.has(cls.type))
240
+ if (isNoLinkNode(cls))
238
241
  return [];
239
242
  const subject = linkSubject(cls, params);
240
243
  const p = String(cls.path || '').replace(/\/+$/, '');
@@ -331,7 +334,7 @@ export async function scopeLinks(cls, params = {}, minAccess = 'read') {
331
334
  * но его DATA/INDEX/LOGS ссылки не открывают.
332
335
  */
333
336
  export async function grants(cls, item, params) {
334
- if (NO_LINK_TYPES.has(cls.type))
337
+ if (isNoLinkNode(cls))
335
338
  return false;
336
339
  const area = cls.areaOf(item).kind;
337
340
  try {
@@ -388,7 +391,7 @@ export async function isLinkAncestor(clsPath, params = {}, itemPath = null) {
388
391
 
389
392
  /** Запись в прикладной класс по ссылкам (уровень `write` и выше, или заданный `requiredLevel`). */
390
393
  export async function grantsWrite(cls, params, requiredLevel = 'write') {
391
- if (NO_LINK_TYPES.has(cls.type))
394
+ if (isNoLinkNode(cls))
392
395
  return false;
393
396
  try {
394
397
  const level = await linkLevel(cls, params);
@@ -403,7 +406,7 @@ export async function grantsWrite(cls, params, requiredLevel = 'write') {
403
406
  * пользователю как каркас дерева (SYSTEM/NESTED), не открывая чужие ветки и MODULES.
404
407
  */
405
408
  export async function isStructureAncestor(cls, item, params = {}) {
406
- if (!cls || !['$domain', '$project', '$structure'].includes(cls.type))
409
+ if (!cls || (!['$domain', '$project', '$structure'].includes(cls.type) && cls.DATA?.isStructure !== true))
407
410
  return false;
408
411
  if (item?.type === '$module' || (item?.type === '$domain' && item?.id === 'MODULES'))
409
412
  return false;
@@ -583,7 +583,7 @@ export async function visibleContacts(storage, params = {}) {
583
583
  const units = [base];
584
584
  const sub = await base.items?.catch?.(() => []) || [];
585
585
  for (const s of sub) {
586
- if (s?.type === '$structure')
586
+ if (s?.type === '$structure' || s?.DATA?.isDepartment)
587
587
  units.push(s);
588
588
  }
589
589
  let callerInBase = false;
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import * as fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import { ensureBaseModulesDomainSync, extractStubClassJsSync, scaffoldModuleTreeSync } from './scaffold.js';
9
+ import { ensureBaseModulesDomainSync, extractStubClassJsSync, scaffoldModuleTreeSync, departmentMetaNameSync } from './scaffold.js';
10
10
  import { scanModulesDirSync } from './module-status.js';
11
11
 
12
12
  export const BASE_TEMPLATE_PRESETS = Object.freeze([
@@ -594,8 +594,9 @@ export function scaffoldBaseOrganizationSync({
594
594
  }
595
595
 
596
596
  if (preset === 'standard' || preset === 'demo') {
597
+ const deptMeta = departmentMetaNameSync(process.cwd()) || '$structure';
597
598
  for (const dept of buildTemplateDepartments(orgId)) {
598
- const deptClassFile = path.join(targetDir, dept.id, '$structure', 'class.js');
599
+ const deptClassFile = path.join(targetDir, dept.id, deptMeta, 'class.js');
599
600
  if (!fs.existsSync(deptClassFile)) {
600
601
  fs.mkdirSync(path.dirname(deptClassFile), { recursive: true });
601
602
  fs.writeFileSync(deptClassFile, `export default ${JSON.stringify(dept.data, null, 4)}\n`, 'utf-8');
@@ -206,6 +206,42 @@ export const classFeedMethods = {
206
206
  return listNodeRules(this, params);
207
207
  },
208
208
 
209
+ /** Список доступных чат-моделей для профиля и выбора модели по умолчанию. */
210
+ async agent_chat_models() {
211
+ const { listAvailableChatModels } = await import('../../modules/agent/index.js');
212
+ return listAvailableChatModels();
213
+ },
214
+
215
+ /** Безопасный выбор модели по умолчанию для чата нового пользователя. */
216
+ async agent_default_model(params = {}) {
217
+ const { loadConfig } = await import('../../modules/agent/resources.js');
218
+ const { findFirstAvailableChatModel } = await import('../../modules/agent/index.js');
219
+ let place = this;
220
+ if (params.nodePath && globalThis.WORK) {
221
+ const target = await globalThis.WORK.get_item(String(params.nodePath)).catch(() => null);
222
+ const resolved = Array.isArray(target) ? target.at(-1) : target;
223
+ if (resolved)
224
+ place = resolved;
225
+ }
226
+ const cfg = await loadConfig(place).catch(() => ({}));
227
+ if (cfg?.model) {
228
+ const item = await globalThis.WORK?.get_item(cfg.model).catch(() => null);
229
+ if (item) {
230
+ await item.init?.catch?.(() => {});
231
+ if (item.DATA?.enabled !== false && (item.aiActive ?? item.DATA?.aiActive) !== false && typeof item.streamChat === 'function')
232
+ return cfg.model;
233
+ }
234
+ }
235
+ return (await findFirstAvailableChatModel()) || '';
236
+ },
237
+
238
+ /** Запустить автономный аудит узла прямо сейчас (только BOSS). */
239
+ async agent_audit_run(params = {}) {
240
+ await this.assertAccess(params, FS.$class.ACCESS_LEVEL.BOSS);
241
+ const { runNodeAutonomousAudit } = await import('../../modules/agent/node-rules.js');
242
+ return runNodeAutonomousAudit(this, { force: true, session: params.session });
243
+ },
244
+
209
245
  /** Сохранить/удалить правило проактивности узла (только BOSS). */
210
246
  async agent_rule_save(params = {}) {
211
247
  const { saveNodeRule } = await import('../../modules/agent/node-rules.js');
@@ -110,6 +110,143 @@ export function readDeclaredChildTypesSync(branchDir) {
110
110
  return out;
111
111
  }
112
112
 
113
+ function rootClassBranchSync(rootDir = process.cwd()) {
114
+ const base = String(rootDir || process.cwd());
115
+ try {
116
+ for (const ent of fs.readdirSync(base, { withFileTypes: true })) {
117
+ if (!(ent.isDirectory() || ent.isSymbolicLink()) || ent.name[0] !== '$' || ent.name === '$folder' || ent.name === '$file')
118
+ continue;
119
+ const candidate = path.join(base, ent.name, '$folder', '$class');
120
+ if (fs.existsSync(candidate))
121
+ return candidate;
122
+ }
123
+ }
124
+ catch { /* ignore */ }
125
+ return '';
126
+ }
127
+
128
+ /** Прочитать дочерние типы из ветки структуры в корневом типизаторе. */
129
+ export function structureSubtypesSync(rootDir = process.cwd()) {
130
+ const baseBranch = rootClassBranchSync(rootDir);
131
+ if (!baseBranch)
132
+ return [];
133
+ try {
134
+ for (const ent of fs.readdirSync(baseBranch, { withFileTypes: true })) {
135
+ if (!ent.isDirectory() || ent.name[0] !== '$' || ent.name === '$folder' || ent.name === '$file')
136
+ continue;
137
+ const subDir = path.join(baseBranch, ent.name);
138
+ const clsFile = path.join(subDir, 'class.js');
139
+ if (readOwnBoolSync(clsFile, 'isStructure') === true)
140
+ return readDeclaredChildTypesSync(subDir);
141
+ }
142
+ }
143
+ catch { /* ignore */ }
144
+ return [];
145
+ }
146
+
147
+ /** Имя метапапки подразделения (подтипа с `isDepartment: true` в ветке структур). */
148
+ export function departmentMetaNameSync(rootDir = process.cwd()) {
149
+ const baseBranch = rootClassBranchSync(rootDir);
150
+ if (!baseBranch)
151
+ return '';
152
+ try {
153
+ for (const ent of fs.readdirSync(baseBranch, { withFileTypes: true })) {
154
+ if (!ent.isDirectory() || ent.name[0] !== '$' || ent.name === '$folder' || ent.name === '$file')
155
+ continue;
156
+ const subDir = path.join(baseBranch, ent.name);
157
+ if (readOwnBoolSync(path.join(subDir, 'class.js'), 'isStructure') !== true)
158
+ continue;
159
+ for (const sub of fs.readdirSync(subDir, { withFileTypes: true })) {
160
+ if (!sub.isDirectory() || sub.name[0] !== '$')
161
+ continue;
162
+ if (readOwnBoolSync(path.join(subDir, sub.name, 'class.js'), 'isDepartment') === true)
163
+ return sub.name;
164
+ }
165
+ }
166
+ }
167
+ catch { /* ignore */ }
168
+ return '';
169
+ }
170
+
171
+ /** Проверить булево свойство в class.js объявления типа внутри ветки `$folder/$class`. */
172
+ export function readTypePropSync(classBranchDir, type, key) {
173
+ const chain = findTypePathOnDisk(classBranchDir, type);
174
+ if (!chain || chain.length < 2)
175
+ return undefined;
176
+ return readOwnBoolSync(path.join(classBranchDir, ...chain.slice(1), 'class.js'), key);
177
+ }
178
+
179
+ /**
180
+ * Одноразовая миграция при старте: папки подразделений с прежней метапапкой
181
+ * базовой структуры переводим на выделенный суб-тип подразделений (`isDepartment: true`).
182
+ * Системный типизатор ($server/$folder/$class/...) и ветки $folder не затрагиваются.
183
+ */
184
+ export function migrateDepartmentMetasSync(rootDir = process.cwd()) {
185
+ const deptMeta = departmentMetaNameSync(rootDir);
186
+ if (!deptMeta)
187
+ return [];
188
+ const baseBranch = rootClassBranchSync(rootDir);
189
+ if (!baseBranch)
190
+ return [];
191
+ let structMeta = '';
192
+ try {
193
+ for (const ent of fs.readdirSync(baseBranch, { withFileTypes: true })) {
194
+ if (ent.isDirectory() && ent.name[0] === '$' && readOwnBoolSync(path.join(baseBranch, ent.name, 'class.js'), 'isStructure') === true) {
195
+ structMeta = ent.name;
196
+ break;
197
+ }
198
+ }
199
+ }
200
+ catch { /* ignore */ }
201
+ if (!structMeta || structMeta === deptMeta)
202
+ return [];
203
+ const migrated = [];
204
+ const walkProject = (dir) => {
205
+ let entries;
206
+ try {
207
+ entries = fs.readdirSync(dir, { withFileTypes: true });
208
+ }
209
+ catch {
210
+ return;
211
+ }
212
+ for (const ent of entries) {
213
+ if (!ent.isDirectory())
214
+ continue;
215
+ if (ent.name.startsWith('$') || ent.name.startsWith('.') || ent.name.startsWith('#') || ent.name === 'MODULES' || SCAFFOLD_SKIP.has(ent.name))
216
+ continue;
217
+ const childDir = path.join(dir, ent.name);
218
+ const oldMeta = path.join(childDir, structMeta);
219
+ const newMeta = path.join(childDir, deptMeta);
220
+ if (fs.existsSync(oldMeta) && !fs.existsSync(newMeta)) {
221
+ try {
222
+ fs.renameSync(oldMeta, newMeta);
223
+ migrated.push(childDir);
224
+ }
225
+ catch { /* ignore */ }
226
+ }
227
+ walkProject(childDir);
228
+ }
229
+ };
230
+ const rootAbs = String(rootDir || process.cwd());
231
+ try {
232
+ for (const top of fs.readdirSync(rootAbs, { withFileTypes: true })) {
233
+ if (!top.isDirectory() || top.name.startsWith('$') || top.name.startsWith('.'))
234
+ continue;
235
+ const containerDir = path.join(rootAbs, top.name);
236
+ const domainDirs = fs.readdirSync(containerDir, { withFileTypes: true }).filter(e => e.isDirectory() && e.name[0] === '$');
237
+ if (!domainDirs.some(d => readOwnBoolSync(path.join(containerDir, d.name, 'class.js'), 'archiveType') !== undefined || /\barchiveType\s*:/.test(fs.existsSync(path.join(containerDir, d.name, 'class.js')) ? fs.readFileSync(path.join(containerDir, d.name, 'class.js'), 'utf-8') : '')))
238
+ continue;
239
+ for (const proj of fs.readdirSync(containerDir, { withFileTypes: true })) {
240
+ if (!proj.isDirectory() || proj.name.startsWith('$') || proj.name.startsWith('.'))
241
+ continue;
242
+ walkProject(path.join(containerDir, proj.name));
243
+ }
244
+ }
245
+ }
246
+ catch { /* ignore */ }
247
+ return migrated;
248
+ }
249
+
113
250
  /** Прочитать собственные объявления дочерних $-типов из `<dir>/<type>/$folder/$class`. */
114
251
  export function readOwnChildTypesSync(realDir, type) {
115
252
  if (!realDir || !type)
@@ -113,7 +113,7 @@ export const classSearchMethods = {
113
113
  if ((clsItem.type === '$catalog' || clsItem.type === '$operation') && typeof clsItem.db_query === 'function') {
114
114
  try {
115
115
  const qParams = { ...params, search: rawQ, limit: 25 };
116
- if (this.type === '$structure' && clsItem.type === '$operation')
116
+ if ((this.type === '$structure' || this.DATA?.isDepartment) && clsItem.type === '$operation')
117
117
  qParams.unit = this.path;
118
118
  const res = await clsItem.db_query(qParams);
119
119
  for (const it of res?.items || []) {
@@ -172,7 +172,7 @@ export const classSearchMethods = {
172
172
  await scanFolderFiles(cur.meta_folder, cur, 0);
173
173
  }
174
174
 
175
- if (cur.type === '$project' || cur.type === '$project' || cur.type === '$structure') {
175
+ if (cur.type === '$project' || cur.type === '$structure' || cur.DATA?.isStructure) {
176
176
  const sec = cur.DATA?.['#security'];
177
177
  if (sec) {
178
178
  const { common, places } = WORKPLACES.normalizeSecurity(sec);
@@ -739,7 +739,7 @@ export const classSecurityMethods = {
739
739
  continue;
740
740
  const sub = await Promise.resolve(node.items).catch(() => []) || [];
741
741
  for (const s of sub) {
742
- if (s?.type === '$structure' && s.id?.[0] !== '$')
742
+ if (s && (s.type === '$structure' || s.DATA?.isDepartment) && s.id?.[0] !== '$')
743
743
  stack.push({ node: s, depth: depth + 1 });
744
744
  }
745
745
  }
@@ -51,6 +51,7 @@ import {
51
51
  ensureModelField,
52
52
  parseCreateDevice,
53
53
  findChildWithModel,
54
+ departmentMetaNameSync,
54
55
  } from './class/scaffold.js';
55
56
  import {
56
57
  buildBasePassportClassJs,
@@ -166,7 +167,7 @@ export class $class extends $folder {
166
167
  return 'odant:module';
167
168
  if (this.type === '$domain' && this.id === 'MODULES')
168
169
  return 'odant:folder';
169
- if (this.type === '$structure')
170
+ if (this.type === '$structure' || this.DATA?.isDepartment)
170
171
  return this.DATA?.icon || 'odant:structure';
171
172
  return this.DATA?.icon;
172
173
  },
@@ -445,7 +446,7 @@ export class $class extends $folder {
445
446
 
446
447
  const self_to_save = this.constructor.getDifference(self_data, baseSelf);
447
448
 
448
- const fileParams = Object.assign({}, params, { filename: 'class.js' });
449
+ const fileParams = Object.assign({ ignore_save_logs: true }, params, { filename: 'class.js' });
449
450
  const toDataScript = data => 'export default ' + this.constructor.toScript(data);
450
451
 
451
452
  const writes = [
@@ -816,7 +817,8 @@ export class $class extends $folder {
816
817
 
817
818
  let post = p.post;
818
819
  const explicitIcon = typeof p.icon === 'string' ? p.icon.trim() : '';
819
- const defaultIcon = explicitIcon || (type === '$structure' ? inferStructureIcon(p.label, id) : '');
820
+ const deptType = departmentMetaNameSync(globalThis.WORK?.real_dir || process.cwd());
821
+ const defaultIcon = explicitIcon || ((type === '$structure' || (deptType && type === deptType)) ? inferStructureIcon(p.label, id) : '');
820
822
  if (post == null) {
821
823
  if (srcModClassFile && fs.existsSync(srcModClassFile)) {
822
824
  const customLabel = (p.label && p.label !== id && p.label !== rawId) ? p.label : '';
@@ -12,6 +12,7 @@ import { DEV_MODE } from '../host/config.js';
12
12
  import { assertNotMemory } from './memory-mark.js';
13
13
  import { markClassesDirty, classObjectCount } from '../data/api.js';
14
14
  import { isModuleType } from './class/module-status.js';
15
+ import { departmentMetaNameSync } from './class/scaffold.js';
15
16
 
16
17
  function readOwnAncestorSync(metaRealDir) {
17
18
  if (!metaRealDir)
@@ -1333,6 +1334,8 @@ export class $folder extends $item{
1333
1334
  return null;
1334
1335
  if (Array.isArray(this.DATA?.mainTreeChildren))
1335
1336
  return new Set(this.DATA.mainTreeChildren);
1337
+ if (typeof this.DATA?.mainTreeChildren === 'string')
1338
+ return new Set(this.DATA.mainTreeChildren.trim().split(/\s+/).filter(Boolean));
1336
1339
  const p = String(this.path || '');
1337
1340
  if ((this.type === '$domain' && (this.id === 'MODULES' || /\/MODULES$/.test(p)))
1338
1341
  || (this.type === '$folder' && /(?:^|\/)MODULES(?:\/|$)/.test(p)))
@@ -1341,8 +1344,8 @@ export class $folder extends $item{
1341
1344
  return null;
1342
1345
  if (this.parent?.type === '$server')
1343
1346
  return null;
1344
- if (this.type === '$project' || this.type === '$structure')
1345
- return new Set(['$structure', '$project']);
1347
+ if (this.type === '$project' || this.type === '$structure' || this.DATA?.isDepartment)
1348
+ return new Set([this.type, '$structure', '$project', departmentMetaNameSync()].filter(Boolean));
1346
1349
  if (this.type === '$module' || this.type === '$mcp' || this.type === '$user' || this.type === '$node' || this.type === '$ai')
1347
1350
  return new Set();
1348
1351
  if (this.type === '$provider')
@@ -2443,10 +2446,11 @@ export class $folder extends $item{
2443
2446
 
2444
2447
  sortItems(files, reverse = false, isType = this.isType) {
2445
2448
  const rootOrder = { PROJECTS: 0, USERS: 1, NODES: 2, nodes: 2, MODULES: 3 };
2446
- const typeGroup = (t) => {
2449
+ const typeGroup = (item) => {
2450
+ const t = item?.type;
2447
2451
  if (t === '$catalog' || t === '$virtual' || t === '$struct' || t === '$operation' || t === '$register' || t === '$account')
2448
2452
  return 0;
2449
- if (t === '$structure' || t === '$project')
2453
+ if (t === '$structure' || t === '$project' || item?.DATA?.isDepartment)
2450
2454
  return 1;
2451
2455
  if (t === '$module' || t === '$provider' || t === '$mcp' || t === '$domain')
2452
2456
  return 3;
@@ -2477,8 +2481,8 @@ export class $folder extends $item{
2477
2481
  return ra - rb;
2478
2482
  }
2479
2483
  if (aCls && bCls && a.type !== b.type) {
2480
- const ga = typeGroup(a.type);
2481
- const gb = typeGroup(b.type);
2484
+ const ga = typeGroup(a);
2485
+ const gb = typeGroup(b);
2482
2486
  if (ga !== gb)
2483
2487
  return ga - gb;
2484
2488
  }
@@ -125,7 +125,21 @@ export function logExt(row) {
125
125
  return dot > 0 ? id.slice(dot + 1).toLowerCase() : '';
126
126
  }
127
127
 
128
+ export function isSystemMetaLogRow(row) {
129
+ const p = String(row?.path || '').trim().replace(/\\/g, '/');
130
+ if (!p)
131
+ return false;
132
+ if (/(?:^|\/)class\.js$/i.test(p))
133
+ return true;
134
+ // Снимки метафайлов внутри $.../#... (кроме пользовательских документов и задач .task)
135
+ if (/\/#(?:secret|system)\//i.test(p) && !/\.task$/i.test(p))
136
+ return true;
137
+ return false;
138
+ }
139
+
128
140
  export function matchesFilter(row, params) {
141
+ if (params.feedMode === 'dialog' && isSystemMetaLogRow(row))
142
+ return false;
129
143
  if (!params.exts?.length)
130
144
  return true;
131
145
  return params.exts.includes(logExt(row));