odant-work 1.0.74 → 1.0.76
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/#system/package-manifest.json +18 -18
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +26 -4
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +511 -73
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/staff.js +851 -435
- package/package.json +1 -1
- package/sources/client/folder.js +2 -0
- package/sources/modules/agent/index.js +1 -1
- package/sources/modules/agent/node-rules.js +403 -20
- package/sources/modules/agent/scheduler.js +135 -4
- package/sources/modules/agent/triggers.js +38 -7
- package/sources/modules/agent/twin-bus.js +66 -5
- package/sources/server/access/gateway.js +2 -0
- package/sources/server/access/links.js +16 -6
- package/sources/server/access/workplaces.js +35 -2
- package/sources/server/class/feed.js +36 -0
- package/sources/server/class/security.js +40 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.76",
|
|
4
4
|
"description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "sources/work.js",
|
package/sources/client/folder.js
CHANGED
|
@@ -274,6 +274,8 @@ export class $folder extends $item {
|
|
|
274
274
|
|| method.startsWith('license_')
|
|
275
275
|
|| method.startsWith('messenger_')
|
|
276
276
|
|| method.startsWith('distro_')
|
|
277
|
+
|| method.startsWith('agent_')
|
|
278
|
+
|| method === 'security_update'
|
|
277
279
|
|| method === 'export_distro'
|
|
278
280
|
))
|
|
279
281
|
|| (method === 'logs' && params.mode && params.mode !== 'folder' && params.mode !== 'files');
|
|
@@ -477,7 +477,7 @@ export async function createEnv({ place, contextPath, session, host, tz, locatio
|
|
|
477
477
|
const TWIN_SERVICE_DENY = new Set([
|
|
478
478
|
'create_class', 'update_class', 'move_class', 'delete_class',
|
|
479
479
|
'assign', 'escalate', 'delete',
|
|
480
|
-
'twin_rule_list', 'twin_rule_save', 'twin_schedule_save',
|
|
480
|
+
'twin_rule_list', 'twin_rule_save', 'twin_schedule_save', 'twin_system_save', 'twin_security_save',
|
|
481
481
|
'mail_send', 'mail_draft', 'mail_refresh',
|
|
482
482
|
'dev_write', 'dev_edit', 'dev_patch', 'dev_git', 'dev_shell',
|
|
483
483
|
'shell', 'restart_server', 'os_write', 'os_rm',
|
|
@@ -5,11 +5,13 @@
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import fsp from 'node:fs/promises';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
-
import { loadDocs } from './resources.js';
|
|
8
|
+
import { loadDocs, aiDirs } from './resources.js';
|
|
9
|
+
import { parseFrontmatter } from './util.js';
|
|
9
10
|
import { resetTriggerCache } from './triggers.js';
|
|
10
11
|
import { createSchedule, listSchedules, toggleSchedule, cancelSchedule } from './scheduler.js';
|
|
11
12
|
import { DEV_MODE } from '../../host/config.js';
|
|
12
13
|
import { audit } from '../../server/access/audit.js';
|
|
14
|
+
import { FS } from '../../server/index.js';
|
|
13
15
|
|
|
14
16
|
const ACCESS_DENIED = 'Доступ запрещён';
|
|
15
17
|
const SAFE_RULE_NAME_RE = /^[A-Za-z0-9\u0400-\u04FF_-]{1,64}$/;
|
|
@@ -17,9 +19,10 @@ const SAFE_RULE_NAME_RE = /^[A-Za-z0-9\u0400-\u04FF_-]{1,64}$/;
|
|
|
17
19
|
async function assertBoss(storage, params = {}) {
|
|
18
20
|
if (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK)
|
|
19
21
|
return;
|
|
20
|
-
const
|
|
21
|
-
if (
|
|
22
|
-
|
|
22
|
+
const roles = await storage.roles?.(params).catch(() => []) || [];
|
|
23
|
+
if (roles.includes('BOSS') || await storage._isWorkBoss?.(params).catch(() => false))
|
|
24
|
+
return;
|
|
25
|
+
throw new Error(ACCESS_DENIED);
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
function ownTriggersDir(storage) {
|
|
@@ -41,16 +44,17 @@ function yamlScalar(v) {
|
|
|
41
44
|
return s;
|
|
42
45
|
}
|
|
43
46
|
|
|
44
|
-
function serializeTriggerMd({ name, on, class: cls, ext, when, template, approval, as, notify, cooldownSec, maxPerHour, enabled, body }) {
|
|
47
|
+
function serializeTriggerMd({ name, label, on, class: cls, ext, when, template, approval, as, notify, cooldownSec, maxPerHour, enabled, body }) {
|
|
45
48
|
const lines = ['---'];
|
|
46
49
|
lines.push(`name: ${yamlScalar(name)}`);
|
|
50
|
+
if (label && label !== name) lines.push(`label: ${yamlScalar(label)}`);
|
|
47
51
|
lines.push(`on: ${yamlScalar(Array.isArray(on) ? on.join(', ') : (on || 'db:register'))}`);
|
|
48
52
|
if (cls) lines.push(`class: ${yamlScalar(cls)}`);
|
|
49
53
|
if (ext) lines.push(`ext: ${yamlScalar(ext)}`);
|
|
50
54
|
if (when) lines.push(`when: ${yamlScalar(when)}`);
|
|
51
55
|
if (template) lines.push(`template: ${yamlScalar(template)}`);
|
|
52
56
|
if (approval) lines.push(`approval: true`);
|
|
53
|
-
|
|
57
|
+
lines.push(`as: ${yamlScalar(as || 'BOSS')}`);
|
|
54
58
|
const notifyList = Array.isArray(notify) ? notify : String(notify || 'BOSS').split(/[\s,]+/).filter(Boolean);
|
|
55
59
|
lines.push(`notify: [${notifyList.map(yamlScalar).join(', ')}]`);
|
|
56
60
|
if (Number(cooldownSec) > 0) lines.push(`cooldownSec: ${Math.round(Number(cooldownSec))}`);
|
|
@@ -77,13 +81,14 @@ export async function listNodeRules(storage, params = {}) {
|
|
|
77
81
|
const m = doc.meta || {};
|
|
78
82
|
triggers.push({
|
|
79
83
|
name: doc.name,
|
|
84
|
+
label: m.label || doc.name,
|
|
80
85
|
on: m.on || 'save',
|
|
81
86
|
class: m.class || '',
|
|
82
87
|
ext: m.ext || '',
|
|
83
88
|
when: m.when || '',
|
|
84
89
|
template: m.template || '',
|
|
85
90
|
approval: Boolean(m.approval === true || m.approval === 'true'),
|
|
86
|
-
as: m.as || '',
|
|
91
|
+
as: m.as || 'BOSS',
|
|
87
92
|
notify: Array.isArray(m.notify) ? m.notify : String(m.notify || '').split(/[\s,]+/).filter(Boolean),
|
|
88
93
|
cooldownSec: Number(m.cooldownSec) || 0,
|
|
89
94
|
maxPerHour: Number(m.maxPerHour) || 20,
|
|
@@ -116,16 +121,18 @@ export async function saveNodeRule(storage, params = {}) {
|
|
|
116
121
|
await fsp.rm(filePath, { force: true });
|
|
117
122
|
resetTriggerCache();
|
|
118
123
|
audit('agent_rule_delete', { name, point: storage.path, params });
|
|
124
|
+
await recordBossSettingTask(storage, params, {
|
|
125
|
+
title: `Удалена реакция «${name}»`,
|
|
126
|
+
summary: `В подразделении ${storage.path || '/'} удалена автоматическая реакция «${name}».`,
|
|
127
|
+
});
|
|
119
128
|
return { ok: true, deleted: name };
|
|
120
129
|
}
|
|
121
130
|
|
|
122
|
-
const
|
|
123
|
-
const asUid = String(post.as || uid).trim();
|
|
124
|
-
if (!asUid)
|
|
125
|
-
throw new Error('Не указан исполнитель (as) для правила');
|
|
131
|
+
const asUid = String(post.as || 'BOSS').trim() || 'BOSS';
|
|
126
132
|
|
|
127
133
|
const md = serializeTriggerMd({
|
|
128
134
|
name,
|
|
135
|
+
label: post.label || name,
|
|
129
136
|
on: post.on || 'db:register',
|
|
130
137
|
class: post.class || '',
|
|
131
138
|
ext: post.ext || '',
|
|
@@ -146,6 +153,10 @@ export async function saveNodeRule(storage, params = {}) {
|
|
|
146
153
|
storage?.reset?.();
|
|
147
154
|
resetTriggerCache();
|
|
148
155
|
audit('agent_rule_save', { name, point: storage.path, params });
|
|
156
|
+
await recordBossSettingTask(storage, params, {
|
|
157
|
+
title: `Настроена реакция «${post.label || name}»`,
|
|
158
|
+
summary: `В подразделении ${storage.path || '/'} сохранена автоматическая реакция «${post.label || name}» (событие: ${post.on || 'db:register'}).`,
|
|
159
|
+
});
|
|
149
160
|
return { ok: true, name };
|
|
150
161
|
}
|
|
151
162
|
|
|
@@ -158,20 +169,63 @@ export async function saveNodeSchedule(storage, params = {}) {
|
|
|
158
169
|
throw new Error('Не определён владелец расписания');
|
|
159
170
|
|
|
160
171
|
if (post.delete === true && post.id) {
|
|
161
|
-
await cancelSchedule({ uid, id: post.id })
|
|
172
|
+
await cancelSchedule({ uid, id: post.id }).catch(async () => {
|
|
173
|
+
// Если расписание создавал прежний BOSS — разрешаем BOSS узла удалить
|
|
174
|
+
const { indexDb } = await import('../../host/index-db.js');
|
|
175
|
+
const d = await indexDb();
|
|
176
|
+
d?.prepare('DELETE FROM agent_schedules WHERE id = ? AND node_path = ?').run(String(post.id), nodePath);
|
|
177
|
+
});
|
|
178
|
+
await recordBossSettingTask(storage, params, {
|
|
179
|
+
title: `Удалено расписание (${post.id})`,
|
|
180
|
+
summary: `В подразделении ${nodePath} удалено расписание ${post.id}.`,
|
|
181
|
+
});
|
|
162
182
|
return { ok: true, deleted: post.id };
|
|
163
183
|
}
|
|
164
184
|
if (post.toggle === true && post.id) {
|
|
165
|
-
|
|
185
|
+
const res = await toggleSchedule({ id: post.id, enabled: post.enabled });
|
|
186
|
+
await recordBossSettingTask(storage, params, {
|
|
187
|
+
title: `${res.enabled ? 'Включено' : 'Приостановлено'} расписание «${res.label || post.id}»`,
|
|
188
|
+
summary: `В подразделении ${nodePath} расписание «${res.label || post.id}» переведено в состояние: ${res.enabled ? 'активно' : 'пауза'}.`,
|
|
189
|
+
});
|
|
190
|
+
return res;
|
|
166
191
|
}
|
|
167
|
-
|
|
192
|
+
const created = await createSchedule({
|
|
168
193
|
uid,
|
|
194
|
+
task: String(post.task || '').trim(),
|
|
169
195
|
nodePath,
|
|
170
196
|
label: post.label || 'Задача по расписанию',
|
|
171
197
|
prompt: post.prompt,
|
|
172
198
|
rule: post.rule,
|
|
173
199
|
tz: post.tz,
|
|
174
200
|
});
|
|
201
|
+
await recordBossSettingTask(storage, params, {
|
|
202
|
+
title: `Добавлено расписание «${created.label}»`,
|
|
203
|
+
summary: `В подразделении ${nodePath} добавлено расписание «${created.label}» (${created.when})${created.task ? ` на основе задачи ${created.task}` : ''}.`,
|
|
204
|
+
});
|
|
205
|
+
return created;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function saveOwnClassFields(storage, params, patch) {
|
|
209
|
+
const own = await storage.meta_file;
|
|
210
|
+
const text = own ? await own.load({ encoding: 'utf-8', session: params?.session }).catch(() => '') : '';
|
|
211
|
+
const data = text ? (await FS.$class.importScript(String(text))) || {} : {};
|
|
212
|
+
const copy = { ...data, ...patch };
|
|
213
|
+
if (storage.meta_folder?.save_file) {
|
|
214
|
+
await storage.meta_folder.save_file({
|
|
215
|
+
...params,
|
|
216
|
+
filename: 'class.js',
|
|
217
|
+
post: 'export default ' + FS.$class.toScript(copy),
|
|
218
|
+
});
|
|
219
|
+
storage.meta_folder?.reset?.();
|
|
220
|
+
storage.reset?.();
|
|
221
|
+
if (typeof storage.import === 'function')
|
|
222
|
+
storage.DATA = await storage.import({ reset: true });
|
|
223
|
+
await storage.init;
|
|
224
|
+
}
|
|
225
|
+
else if (storage?.DATA) {
|
|
226
|
+
Object.assign(storage.DATA, patch);
|
|
227
|
+
}
|
|
228
|
+
return copy;
|
|
175
229
|
}
|
|
176
230
|
|
|
177
231
|
/**
|
|
@@ -186,12 +240,11 @@ export async function saveNodeProactivity(storage, params = {}) {
|
|
|
186
240
|
...(typeof post.autoReply === 'boolean' ? { autoReply: post.autoReply } : {}),
|
|
187
241
|
...(typeof post.quietDigest === 'boolean' ? { quietDigest: post.quietDigest } : {}),
|
|
188
242
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
243
|
+
await saveOwnClassFields(storage, params, { proactivity: next });
|
|
244
|
+
await recordBossSettingTask(storage, params, {
|
|
245
|
+
title: 'Изменено поведение агента узла',
|
|
246
|
+
summary: `В подразделении ${storage.path || '/'} обновлены параметры поведения (autoReply=${next.autoReply !== false}, quietDigest=${next.quietDigest !== false}).`,
|
|
247
|
+
});
|
|
195
248
|
return { ok: true, proactivity: next };
|
|
196
249
|
}
|
|
197
250
|
|
|
@@ -365,3 +418,333 @@ export async function runMailAutoRefresh({ nodes = null } = {}) {
|
|
|
365
418
|
}
|
|
366
419
|
return refreshed;
|
|
367
420
|
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Зафиксировать настройку руководителя как выполненную задачу `.task` в журнале узла (без вызова LLM).
|
|
424
|
+
*/
|
|
425
|
+
export async function recordBossSettingTask(storage, params = {}, { title = 'Настройка узла', summary = '' } = {}) {
|
|
426
|
+
if (!storage || params?.skipAuditTask)
|
|
427
|
+
return null;
|
|
428
|
+
try {
|
|
429
|
+
const actor = storage.constructor?.resolveUid?.(params) || params?.session?.uid || 'BOSS';
|
|
430
|
+
const now = Date.now();
|
|
431
|
+
const taskBody = {
|
|
432
|
+
name: String(title || 'Настройка узла').slice(0, 120),
|
|
433
|
+
title: String(title || 'Настройка узла').slice(0, 120),
|
|
434
|
+
status: 'done',
|
|
435
|
+
source: 'boss-setting',
|
|
436
|
+
actor,
|
|
437
|
+
nodePath: storage.path || '/',
|
|
438
|
+
created: now,
|
|
439
|
+
items: [
|
|
440
|
+
{ id: 'u_' + now, type: 'user', content: `[Настройка в «Системе»] ${title}` },
|
|
441
|
+
{ id: 'a_' + now, type: 'assistant', content: summary || title },
|
|
442
|
+
],
|
|
443
|
+
};
|
|
444
|
+
if (typeof storage.save_file === 'function') {
|
|
445
|
+
const filename = `setting-${new Date(now).toISOString().replace(/[:.]/g, '-')}.task`;
|
|
446
|
+
const safeParams = {
|
|
447
|
+
...params,
|
|
448
|
+
session: { ...(params?.session || { uid: actor, $user: globalThis.WORK }), trigger: 'boss-setting' },
|
|
449
|
+
filename,
|
|
450
|
+
post: JSON.stringify(taskBody, null, 2),
|
|
451
|
+
auto: false,
|
|
452
|
+
};
|
|
453
|
+
await storage.save_file(safeParams).catch(() => {});
|
|
454
|
+
}
|
|
455
|
+
return { ok: true, title };
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Прочитать собственную инструкцию узла (`$structure/ai/system.md`) и унаследованные слои сверху.
|
|
464
|
+
*/
|
|
465
|
+
export async function getNodeAgentSystem(storage, params = {}) {
|
|
466
|
+
await assertBoss(storage, params);
|
|
467
|
+
const metaDir = storage?.meta_folder?.real_dir || storage?.meta_folder?.dir
|
|
468
|
+
|| (storage?.real_dir ? path.join(storage.real_dir, storage.type || '$class') : '');
|
|
469
|
+
const ownFile = metaDir ? path.join(metaDir, 'ai', 'system.md') : '';
|
|
470
|
+
let ownText = '';
|
|
471
|
+
let replace = false;
|
|
472
|
+
if (ownFile && fs.existsSync(ownFile)) {
|
|
473
|
+
try {
|
|
474
|
+
const raw = await fsp.readFile(ownFile, 'utf8');
|
|
475
|
+
const parsed = parseFrontmatter(raw);
|
|
476
|
+
ownText = String(parsed.body || '').trim();
|
|
477
|
+
replace = parsed.meta?.replace === true || parsed.meta?.replace === 'true';
|
|
478
|
+
}
|
|
479
|
+
catch { /* ignore */ }
|
|
480
|
+
}
|
|
481
|
+
const inherited = [];
|
|
482
|
+
try {
|
|
483
|
+
const dirs = await aiDirs(storage);
|
|
484
|
+
const ownPath = storage?.path || '/';
|
|
485
|
+
for (const { dir, scope } of dirs) {
|
|
486
|
+
if (scope === ownPath)
|
|
487
|
+
continue;
|
|
488
|
+
const f = await dir.get_item('system.md').catch(() => null);
|
|
489
|
+
const raw = f && typeof f.load === 'function' ? await f.load({ encoding: 'utf-8' }).catch(() => '') : '';
|
|
490
|
+
const text = String(raw || '').trim();
|
|
491
|
+
if (!text)
|
|
492
|
+
continue;
|
|
493
|
+
const parsed = parseFrontmatter(text);
|
|
494
|
+
inherited.push({
|
|
495
|
+
scope: scope === 'engine' ? 'Базовые правила системы WORK' : scope,
|
|
496
|
+
text: String(parsed.body || text).trim(),
|
|
497
|
+
replace: parsed.meta?.replace === true || parsed.meta?.replace === 'true',
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
catch { /* ignore */ }
|
|
502
|
+
return { text: ownText, replace, inherited };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Сохранить собственную инструкцию агента узла (`$structure/ai/system.md`).
|
|
507
|
+
*/
|
|
508
|
+
export async function saveNodeAgentSystem(storage, params = {}) {
|
|
509
|
+
await assertBoss(storage, params);
|
|
510
|
+
const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
|
|
511
|
+
const text = String(post.text ?? '').trim();
|
|
512
|
+
const replace = Boolean(post.replace);
|
|
513
|
+
const metaDir = storage?.meta_folder?.real_dir || storage?.meta_folder?.dir
|
|
514
|
+
|| (storage?.real_dir ? path.join(storage.real_dir, storage.type || '$class') : '');
|
|
515
|
+
if (!metaDir)
|
|
516
|
+
throw new Error('Не найдена метапапка узла');
|
|
517
|
+
const filePath = path.join(metaDir, 'ai', 'system.md');
|
|
518
|
+
if (!text && !replace) {
|
|
519
|
+
if (fs.existsSync(filePath))
|
|
520
|
+
await fsp.rm(filePath, { force: true });
|
|
521
|
+
}
|
|
522
|
+
else {
|
|
523
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true });
|
|
524
|
+
const content = replace ? `---\nreplace: true\n---\n${text}\n` : `${text}\n`;
|
|
525
|
+
await fsp.writeFile(filePath, content, 'utf8');
|
|
526
|
+
}
|
|
527
|
+
storage?.meta_folder?.reset?.();
|
|
528
|
+
storage?.reset?.();
|
|
529
|
+
audit('agent_system_save', { point: storage.path, replace, length: text.length, params });
|
|
530
|
+
await recordBossSettingTask(storage, params, {
|
|
531
|
+
title: 'Обновлена инструкция агента узла',
|
|
532
|
+
summary: text
|
|
533
|
+
? `Для подразделения ${storage.path || '/'} сохранена инструкция поведения агента (${replace ? 'с заменой общих правил' : 'в дополнение к общим правилам'}):\n${text.slice(0, 300)}`
|
|
534
|
+
: `Для подразделения ${storage.path || '/'} собственная инструкция агента очищена (действуют общие правила).`,
|
|
535
|
+
});
|
|
536
|
+
return { ok: true, text, replace };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const DATA_CLASS_TYPES = new Set(['$catalog', '$virtual', '$operation', '$register', '$account', '$struct']);
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Дерево доступных прикладных классов (из всех модулей текущей организации/проекта и общих /MODULES).
|
|
543
|
+
*/
|
|
544
|
+
export async function listNodeAvailableClasses(storage, params = {}) {
|
|
545
|
+
await assertBoss(storage, params);
|
|
546
|
+
const WORK = globalThis.WORK;
|
|
547
|
+
if (!WORK)
|
|
548
|
+
return { roots: [] };
|
|
549
|
+
|
|
550
|
+
const p = String(storage?.path || '/');
|
|
551
|
+
const m = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(p);
|
|
552
|
+
const baseModPath = m ? m[1] + '/MODULES' : '';
|
|
553
|
+
const candidateRoots = [];
|
|
554
|
+
if (baseModPath)
|
|
555
|
+
candidateRoots.push({ path: baseModPath, label: 'Модули организации' });
|
|
556
|
+
candidateRoots.push({ path: '/MODULES', label: 'Общие модули системы' });
|
|
557
|
+
|
|
558
|
+
const walk = async (node, depth = 0, modRootPath = '') => {
|
|
559
|
+
if (!node || depth > 6)
|
|
560
|
+
return null;
|
|
561
|
+
await node.init?.catch?.(() => {});
|
|
562
|
+
if (!node.id || node.id[0] === '$')
|
|
563
|
+
return null;
|
|
564
|
+
const t = node.type;
|
|
565
|
+
const isLeafData = DATA_CLASS_TYPES.has(t);
|
|
566
|
+
const isFolderGroup = t === '$domain' || t === '$module' || t === '$class' || t === '$folder';
|
|
567
|
+
if (!isLeafData && !isFolderGroup)
|
|
568
|
+
return null;
|
|
569
|
+
const items = await Promise.resolve(node.items).catch(() => []) || [];
|
|
570
|
+
const children = [];
|
|
571
|
+
for (const ch of items) {
|
|
572
|
+
if (!ch || ch.id?.[0] === '$')
|
|
573
|
+
continue;
|
|
574
|
+
const childNode = await walk(ch, depth + 1, modRootPath);
|
|
575
|
+
if (childNode)
|
|
576
|
+
children.push(childNode);
|
|
577
|
+
}
|
|
578
|
+
if (!isLeafData && !children.length)
|
|
579
|
+
return null;
|
|
580
|
+
const rawShort = modRootPath && node.path?.startsWith(modRootPath + '/')
|
|
581
|
+
? node.path.slice(modRootPath.length + 1)
|
|
582
|
+
: (node.path || node.id);
|
|
583
|
+
return {
|
|
584
|
+
id: node.id,
|
|
585
|
+
path: node.path,
|
|
586
|
+
label: node.DATA?.label || node.label || node.id,
|
|
587
|
+
type: t,
|
|
588
|
+
icon: node.icon || node.DATA?.icon || (isLeafData ? 'odant:class' : 'odant:folder'),
|
|
589
|
+
selectable: isLeafData || t === '$module',
|
|
590
|
+
shortPath: rawShort,
|
|
591
|
+
children,
|
|
592
|
+
};
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
const roots = [];
|
|
596
|
+
const seenPaths = new Set();
|
|
597
|
+
for (const r of candidateRoots) {
|
|
598
|
+
if (seenPaths.has(r.path))
|
|
599
|
+
continue;
|
|
600
|
+
seenPaths.add(r.path);
|
|
601
|
+
const modRoot = await WORK.get_item(r.path).catch(() => null);
|
|
602
|
+
if (!modRoot)
|
|
603
|
+
continue;
|
|
604
|
+
const items = await Promise.resolve(modRoot.items).catch(() => []) || [];
|
|
605
|
+
const children = [];
|
|
606
|
+
for (const ch of items) {
|
|
607
|
+
if (!ch || ch.id?.[0] === '$')
|
|
608
|
+
continue;
|
|
609
|
+
const built = await walk(ch, 1, r.path);
|
|
610
|
+
if (built)
|
|
611
|
+
children.push(built);
|
|
612
|
+
}
|
|
613
|
+
if (children.length) {
|
|
614
|
+
roots.push({
|
|
615
|
+
id: r.path,
|
|
616
|
+
path: r.path,
|
|
617
|
+
label: r.label,
|
|
618
|
+
type: '$domain',
|
|
619
|
+
icon: 'odant:folder',
|
|
620
|
+
selectable: false,
|
|
621
|
+
children,
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return { roots };
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Список подразделений текущей организации/проекта (для добавления в участники ролей).
|
|
630
|
+
*/
|
|
631
|
+
export async function listNodeStructures(storage, params = {}) {
|
|
632
|
+
await assertBoss(storage, params);
|
|
633
|
+
const WORK = globalThis.WORK;
|
|
634
|
+
if (!WORK)
|
|
635
|
+
return { structures: [] };
|
|
636
|
+
const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
|
|
637
|
+
const m = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
|
|
638
|
+
const rootsToScan = m ? [m[1]] : ['/ORGANIZATIONS', '/PROJECTS'];
|
|
639
|
+
const out = [];
|
|
640
|
+
const seen = new Set();
|
|
641
|
+
const visit = async (node, depth = 0) => {
|
|
642
|
+
if (!node || depth > 5)
|
|
643
|
+
return;
|
|
644
|
+
await node.init?.catch?.(() => {});
|
|
645
|
+
const p = String(node.path || '').replace(/\/+$/, '') || '/';
|
|
646
|
+
if (['$base', '$project', '$structure'].includes(node.type) && p !== selfPath && !seen.has(p)) {
|
|
647
|
+
seen.add(p);
|
|
648
|
+
out.push({
|
|
649
|
+
path: p,
|
|
650
|
+
id: node.id,
|
|
651
|
+
label: node.DATA?.label || node.label || node.id,
|
|
652
|
+
type: node.type,
|
|
653
|
+
icon: node.icon || node.DATA?.icon || 'odant:structure',
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
const items = await Promise.resolve(node.items).catch(() => []) || [];
|
|
657
|
+
for (const ch of items) {
|
|
658
|
+
if (!ch || ch.id?.[0] === '$')
|
|
659
|
+
continue;
|
|
660
|
+
await ch.init?.catch?.(() => {});
|
|
661
|
+
if (['$domain', '$base', '$project', '$structure'].includes(ch.type))
|
|
662
|
+
await visit(ch, depth + 1);
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
for (const rp of rootsToScan) {
|
|
666
|
+
const item = await WORK.get_item(rp).catch(() => null);
|
|
667
|
+
if (item)
|
|
668
|
+
await visit(item, 0);
|
|
669
|
+
}
|
|
670
|
+
return { structures: out };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* Последние выполненные задачи `.task` подразделения (для повторения по расписанию).
|
|
675
|
+
*/
|
|
676
|
+
export async function listNodeTasks(storage, params = {}) {
|
|
677
|
+
await assertBoss(storage, params);
|
|
678
|
+
const out = [];
|
|
679
|
+
const seen = new Set();
|
|
680
|
+
const scanContainer = async (container) => {
|
|
681
|
+
if (!container)
|
|
682
|
+
return;
|
|
683
|
+
const items = await Promise.resolve(container.items).catch(() => []) || [];
|
|
684
|
+
for (const f of items) {
|
|
685
|
+
if (!(f instanceof FS.$file) || !String(f.id || '').endsWith('.task') || seen.has(f.path))
|
|
686
|
+
continue;
|
|
687
|
+
seen.add(f.path);
|
|
688
|
+
try {
|
|
689
|
+
const raw = await f.load({ encoding: 'utf-8' }).catch(() => '');
|
|
690
|
+
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
691
|
+
if (!parsed || parsed.source === 'boss-setting')
|
|
692
|
+
continue;
|
|
693
|
+
const firstUser = Array.isArray(parsed.items) ? parsed.items.find(i => i?.type === 'user' && i.content) : null;
|
|
694
|
+
const prompt = String(firstUser?.content || parsed.prompt || parsed.name || '').trim();
|
|
695
|
+
if (!prompt)
|
|
696
|
+
continue;
|
|
697
|
+
out.push({
|
|
698
|
+
path: f.path,
|
|
699
|
+
title: String(parsed.title || parsed.name || f.id.replace(/\.task$/i, '')).slice(0, 100),
|
|
700
|
+
prompt: prompt.slice(0, 1000),
|
|
701
|
+
time: Number(parsed.updated || parsed.created || f.mtime || 0),
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
catch { /* ignore */ }
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
await scanContainer(storage);
|
|
708
|
+
const uid = storage.constructor?.resolveUid?.(params) || params?.session?.uid || '';
|
|
709
|
+
if (uid && globalThis.WORK) {
|
|
710
|
+
const userItem = await globalThis.WORK.get_item(`/USERS/${uid}`).catch(() => null);
|
|
711
|
+
await scanContainer(userItem);
|
|
712
|
+
}
|
|
713
|
+
out.sort((a, b) => (b.time || 0) - (a.time || 0));
|
|
714
|
+
return { tasks: out.slice(0, 30) };
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Сохранить `#security` подразделения (BOSS — не более одного, ROLES — роли с людьми/подразделениями и классами)
|
|
719
|
+
* с автоматической фиксацией в журнале босса.
|
|
720
|
+
*/
|
|
721
|
+
export async function saveNodeSecurity(storage, params = {}) {
|
|
722
|
+
await assertBoss(storage, params);
|
|
723
|
+
const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
|
|
724
|
+
const rawSec = post.security && typeof post.security === 'object' ? post.security : post;
|
|
725
|
+
const bossArr = Array.isArray(rawSec.BOSS)
|
|
726
|
+
? rawSec.BOSS.filter(v => typeof v === 'string' && v.trim()).slice(0, 1)
|
|
727
|
+
: [];
|
|
728
|
+
const nextSec = {
|
|
729
|
+
...rawSec,
|
|
730
|
+
BOSS: bossArr,
|
|
731
|
+
};
|
|
732
|
+
await saveOwnClassFields(storage, params, { '#security': nextSec });
|
|
733
|
+
try {
|
|
734
|
+
const LINKS = await import('../../server/access/links.js');
|
|
735
|
+
LINKS.reset();
|
|
736
|
+
}
|
|
737
|
+
catch { /* ignore */ }
|
|
738
|
+
const summaryText = String(post.summary || '').trim()
|
|
739
|
+
|| `Обновлена структура прав в ${storage.path || '/'}: BOSS=${bossArr[0] || 'наследуется сверху'}, ролей=${Array.isArray(nextSec.ROLES) ? nextSec.ROLES.length : 0}.`;
|
|
740
|
+
await recordBossSettingTask(storage, params, {
|
|
741
|
+
title: String(post.title || 'Изменены права и роли подразделения'),
|
|
742
|
+
summary: summaryText,
|
|
743
|
+
});
|
|
744
|
+
storage.meta_folder?.reset?.();
|
|
745
|
+
storage.reset?.();
|
|
746
|
+
if (typeof storage.import === 'function')
|
|
747
|
+
storage.DATA = await storage.import({ reset: true });
|
|
748
|
+
await storage.init;
|
|
749
|
+
return { ok: true, security: nextSec };
|
|
750
|
+
}
|