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.
@@ -72,11 +72,79 @@ function utcOf(y, m, d, hh, mm, tz) {
72
72
  /** Дней в месяце года (григорианский, по UTC — пояс не важен). */
73
73
  const daysInMonth = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate();
74
74
 
75
+ /** Разбор ODANT-маски времени вида YYYY-MM-05T10:15:00 (YYYY/MM/DD/HH/mm — любое значение). */
76
+ export function parseTimeMask(rawMask) {
77
+ const src = String(rawMask ?? '').trim();
78
+ const m = src.match(/^(\d{4}|[Yy]{4})-(\d{2}|[Mm]{2})-(\d{2}|[Dd]{2})[T ](\d{2}|[Hh]{2}):(\d{2}|[Mm]{2})(?::(\d{2}|[Ss]{2}))?$/);
79
+ if (!m)
80
+ throw new Error('mask: формат YYYY-MM-DDTHH:MM:00 (например YYYY-MM-05T10:15:00)');
81
+ const [, yStr, moStr, dStr, hStr, minStr] = m;
82
+ const y = /^[Yy]{4}$/.test(yStr) ? null : Number(yStr);
83
+ const mo = /^[Mm]{2}$/.test(moStr) ? null : Number(moStr);
84
+ const d = /^[Dd]{2}$/.test(dStr) ? null : Number(dStr);
85
+ const hh = /^[Hh]{2}$/.test(hStr) ? null : Number(hStr);
86
+ const mm = /^[Mm]{2}$/.test(minStr) ? null : Number(minStr);
87
+ if (y !== null && (y < 1970 || y > 2199))
88
+ throw new Error('mask: год должен быть 1970–2199 или YYYY');
89
+ if (mo !== null && (mo < 1 || mo > 12))
90
+ throw new Error('mask: месяц должен быть 01–12 или MM');
91
+ if (d !== null && (d < 1 || d > 31))
92
+ throw new Error('mask: день должен быть 01–31 или DD');
93
+ if (hh !== null && (hh < 0 || hh > 23))
94
+ throw new Error('mask: час должен быть 00–23 или HH');
95
+ if (mm !== null && (mm < 0 || mm > 59))
96
+ throw new Error('mask: минуты должны быть 00–59 или MM');
97
+ if (hh === null && mm === null)
98
+ throw new Error('mask: укажите хотя бы час или минуты (для более редкого интервала используйте каждые N минут)');
99
+ const norm = `${y === null ? 'YYYY' : String(y).padStart(4, '0')}-${mo === null ? 'MM' : String(mo).padStart(2, '0')}-${d === null ? 'DD' : String(d).padStart(2, '0')}T${hh === null ? 'HH' : String(hh).padStart(2, '0')}:${mm === null ? 'MM' : String(mm).padStart(2, '0')}:00`;
100
+ return { norm, y, mo, d, hh, mm };
101
+ }
102
+
103
+ function nextRunMask(maskStr, tz, from) {
104
+ const { y, mo, d, hh, mm } = parseTimeMask(maskStr);
105
+ const now = local(from, tz);
106
+ const years = y !== null
107
+ ? (y < now.y ? [] : [y])
108
+ : [now.y, now.y + 1, now.y + 2, now.y + 3, now.y + 4];
109
+ const months = mo !== null ? [mo] : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
110
+ const hours = hh !== null ? [hh] : Array.from({ length: 24 }, (_, i) => i);
111
+ const mins = mm !== null ? [mm] : Array.from({ length: 60 }, (_, i) => i);
112
+ for (const yy of years) {
113
+ for (const m2 of months) {
114
+ if (yy === now.y && m2 < now.m)
115
+ continue;
116
+ const maxD = daysInMonth(yy, m2);
117
+ const days = d !== null ? (d <= maxD ? [d] : []) : Array.from({ length: maxD }, (_, i) => i + 1);
118
+ for (const dd of days) {
119
+ if (yy === now.y && m2 === now.m && dd < now.d)
120
+ continue;
121
+ for (const h of hours) {
122
+ if (yy === now.y && m2 === now.m && dd === now.d && h < now.hh)
123
+ continue;
124
+ for (const min of mins) {
125
+ const t = utcOf(yy, m2, dd, h, min, tz);
126
+ if (t > from)
127
+ return t;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+
75
136
  /** Нормализовать правило (бросает при ошибке). */
76
137
  export function normalizeRule(rule = {}) {
77
138
  if (rule.scope != null && rule.scope !== '' && !['personal', 'department'].includes(String(rule.scope)))
78
139
  throw new Error('scope: personal (лично) | department (общее по подразделению)');
79
140
  const extra = rule.scope === 'department' ? { scope: 'department' } : {};
141
+ if (rule.mask != null && String(rule.mask).trim() !== '') {
142
+ const parsed = parseTimeMask(rule.mask);
143
+ const days = Array.isArray(rule.days) && rule.days.length
144
+ ? [...new Set(rule.days.map(Number))].filter(d => Number.isInteger(d) && d >= 1 && d <= 7).sort()
145
+ : null;
146
+ return { mask: parsed.norm, ...(days?.length ? { days } : {}), ...extra };
147
+ }
80
148
  if (rule.once) {
81
149
  const t = Date.parse(rule.once);
82
150
  if (!Number.isFinite(t))
@@ -145,6 +213,21 @@ export function normalizeRule(rule = {}) {
145
213
  /** Следующий запуск после from (мс) или null (разовое уже прошло). */
146
214
  export function nextRun(rule, tz, from = Date.now()) {
147
215
  tz = validTz(tz);
216
+ if (rule.mask) {
217
+ if (Array.isArray(rule.days) && rule.days.length) {
218
+ let cur = from;
219
+ for (let i = 0; i < 64; i++) {
220
+ const candidate = nextRunMask(rule.mask, tz, cur);
221
+ if (!candidate)
222
+ return null;
223
+ if (rule.days.includes(local(candidate, tz).dow))
224
+ return candidate;
225
+ cur = candidate;
226
+ }
227
+ return null;
228
+ }
229
+ return nextRunMask(rule.mask, tz, from);
230
+ }
148
231
  if (rule.once) {
149
232
  const t = Date.parse(rule.once);
150
233
  return t > from ? t : null;
@@ -238,6 +321,36 @@ export function nextRun(rule, tz, from = Date.now()) {
238
321
 
239
322
  export function describeRule(rule) {
240
323
  const suffix = rule.scope === 'department' ? ' [по подразделению]' : '';
324
+ if (rule.mask) {
325
+ let p;
326
+ try { p = parseTimeMask(rule.mask); } catch { return rule.mask + suffix; }
327
+ const timeStr = `${p.hh === null ? 'каждый час' : String(p.hh).padStart(2, '0')}:${p.mm === null ? '00' : String(p.mm).padStart(2, '0')}`;
328
+ let dateDesc = '';
329
+ if (p.y === null && p.mo === null && p.d === null) {
330
+ if (Array.isArray(rule.days) && rule.days.length && rule.days.length < 7) {
331
+ const isWorkdays = rule.days.join(',') === '1,2,3,4,5';
332
+ const names = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];
333
+ dateDesc = isWorkdays ? 'по будням' : rule.days.map(d => names[d - 1]).join(', ');
334
+ }
335
+ else {
336
+ dateDesc = 'ежедневно';
337
+ }
338
+ }
339
+ else if (p.y === null && p.mo === null && p.d !== null) {
340
+ dateDesc = `каждое ${p.d}-е число месяца`;
341
+ }
342
+ else if (p.y === null && p.mo !== null && p.d !== null) {
343
+ dateDesc = `ежегодно ${String(p.d).padStart(2, '0')}.${String(p.mo).padStart(2, '0')}`;
344
+ }
345
+ else if (p.y !== null && p.mo !== null && p.d !== null) {
346
+ dateDesc = `${String(p.d).padStart(2, '0')}.${String(p.mo).padStart(2, '0')}.${p.y}`;
347
+ }
348
+ else {
349
+ dateDesc = rule.mask.split('T')[0];
350
+ }
351
+ const atText = p.hh === null ? `в :${String(p.mm).padStart(2, '0')} каждого часа` : `в ${timeStr}`;
352
+ return `${dateDesc} ${atText}${suffix}`;
353
+ }
241
354
  if (rule.once)
242
355
  return 'однократно ' + rule.once + suffix;
243
356
  if (rule.every) {
@@ -404,8 +517,8 @@ async function defaultRunner(r) {
404
517
  };
405
518
  const session = { uid: r.uid, $user: user, principal: Object.freeze({ kind: 'user', id: r.uid }), scheduled: true, sockets: {}, send: sendToUser };
406
519
 
407
- // Расписание уровня узла $structure (без привязки к файлу .task)
408
- if (r.node_path && !r.task) {
520
+ // Расписание уровня узла $structure (свежий запуск по поручению или на основе готовой задачи .task)
521
+ if (r.node_path) {
409
522
  let nodeItem = await WORK.get_item(r.node_path).catch(() => null);
410
523
  if (Array.isArray(nodeItem))
411
524
  nodeItem = nodeItem.at(-1);
@@ -414,12 +527,29 @@ async function defaultRunner(r) {
414
527
  const roles = await nodeItem.roles?.({ session }).catch(() => []);
415
528
  if (!roles.length)
416
529
  throw new Error('Доступ запрещён');
530
+ let effectivePrompt = String(r.prompt || '').trim();
531
+ if (r.task) {
532
+ try {
533
+ let tplFile = await WORK.get_item(r.task).catch(() => null);
534
+ if (Array.isArray(tplFile)) tplFile = tplFile.at(-1);
535
+ const raw = tplFile && typeof tplFile.load === 'function' ? await tplFile.load().catch(() => null) : null;
536
+ const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
537
+ const firstUser = Array.isArray(parsed?.items) ? parsed.items.find(i => i?.type === 'user' && i.content) : null;
538
+ const basePrompt = String(firstUser?.content || '').trim();
539
+ if (basePrompt) {
540
+ effectivePrompt = effectivePrompt && effectivePrompt !== basePrompt
541
+ ? `Выполни повторно по образцу задачи «${parsed?.title || r.label}»:\n${basePrompt}\n\nДополнительное уточнение: ${effectivePrompt}`
542
+ : basePrompt;
543
+ }
544
+ }
545
+ catch { /* если исходная .task недоступна — используем сохранённый prompt */ }
546
+ }
417
547
  const stamp = new Date().toLocaleString('ru-RU', { timeZone: r.tz || undefined });
418
548
  const { runOnce } = await import('./index.js');
419
549
  const res = await runOnce({
420
550
  place: nodeItem,
421
551
  session,
422
- prompt: '[по расписанию «' + r.label + '», ' + stamp + ']\n' + r.prompt,
552
+ prompt: '[по расписанию «' + r.label + '», ' + stamp + ']\n' + effectivePrompt,
423
553
  mode: 'ask',
424
554
  signal: AbortSignal.timeout(10 * 60_000),
425
555
  });
@@ -429,7 +559,8 @@ async function defaultRunner(r) {
429
559
  uid: r.uid,
430
560
  asTwin: true,
431
561
  kind: 'text',
432
- message: `[по расписанию «${r.label}»] ${answer}`,
562
+ message: `🤖 Агент · по расписанию «${r.label}»:\n${answer}`,
563
+ meta: { source: 'agent-schedule', scheduleId: r.id, scheduleLabel: r.label, actedAsBoss: true },
433
564
  }).catch(() => {});
434
565
  return;
435
566
  }
@@ -148,13 +148,27 @@ export async function matchTriggers(file) {
148
148
  if (area.kind !== 'files' && (area.kind !== 'zone' || area.role !== String(m.zone)))
149
149
  continue;
150
150
  }
151
- if (!m.as)
152
- continue;
153
151
  out.push({ ...doc, point });
154
152
  }
155
153
  return out;
156
154
  }
157
155
 
156
+ async function resolveRuleActorUid(point, rawAs, params) {
157
+ const val = String(rawAs || '').trim();
158
+ if (val && val !== 'BOSS')
159
+ return val;
160
+ const bosses = await Promise.resolve(point?.bosses).catch(() => []);
161
+ if (Array.isArray(bosses) && bosses[0]?.id)
162
+ return bosses[0].id;
163
+ const allBosses = await Promise.resolve(point?.allBosses).catch(() => []);
164
+ if (Array.isArray(allBosses) && allBosses.length) {
165
+ const last = allBosses.at(-1);
166
+ if (last?.id)
167
+ return last.id;
168
+ }
169
+ return String(params?.session?.uid || '').trim();
170
+ }
171
+
158
172
  async function sessionFor(uid, trigger) {
159
173
  let user = await (await WORK.$users)?.get_item('//' + uid);
160
174
  if (Array.isArray(user))
@@ -181,6 +195,16 @@ async function resolveNotifyUids(point, rawNotify, fallbackUid) {
181
195
  if (top?.id) out.add(top.id);
182
196
  }
183
197
  }
198
+ else if (entry === 'CHAT' || entry === 'ALL') {
199
+ const members = await Promise.resolve(point?.assignedUsers).catch(() => []);
200
+ for (const u of Array.isArray(members) ? members : []) {
201
+ if (u?.id) out.add(u.id);
202
+ }
203
+ const bosses = await Promise.resolve(point?.bosses).catch(() => []);
204
+ for (const b of Array.isArray(bosses) ? bosses : []) {
205
+ if (b?.id) out.add(b.id);
206
+ }
207
+ }
184
208
  else {
185
209
  out.add(entry);
186
210
  }
@@ -195,15 +219,20 @@ async function deliverTwinNotification(point, t, { uid, text, attachments = [],
195
219
  const CHAT = await import('../../server/chat-threads.js');
196
220
  const isApproval = t.meta?.approval === true || t.meta?.approval === 'true';
197
221
  const msgKind = isApproval ? 'approval' : 'text';
222
+ const ruleTitle = String(t.meta?.label || t.name || 'правило').trim();
223
+ const decorated = `🤖 Агент · реакция «${ruleTitle}» (с правами руководителя):\n${text}`;
198
224
  for (const targetUid of notifyUids) {
199
225
  await CHAT.sendMessage(point, {
200
226
  uid: targetUid,
201
227
  asTwin: true,
202
228
  kind: msgKind,
203
- message: text,
229
+ message: decorated,
204
230
  attachments,
205
231
  meta: {
232
+ source: 'agent-rule',
206
233
  trigger: t.name,
234
+ ruleTitle,
235
+ actedAsBoss: true,
207
236
  event: eventName,
208
237
  entityId,
209
238
  ...(isApproval ? { status: 'pending', action: t.meta?.action || t.name } : {}),
@@ -215,7 +244,9 @@ async function deliverTwinNotification(point, t, { uid, text, attachments = [],
215
244
  async function runTrigger(t, ctxData, params) {
216
245
  const { audit } = await import('../../server/access/audit.js');
217
246
  const m = t.meta || {};
218
- const uid = String(m.as || '');
247
+ const uid = await resolveRuleActorUid(t.point, m.as, params);
248
+ if (!uid)
249
+ throw new Error('не найден руководитель (BOSS) для выполнения правила ' + t.name);
219
250
  const session = await sessionFor(uid, t.name);
220
251
  const roles = await t.point.roles({ session });
221
252
  if (!roles.length)
@@ -271,7 +302,7 @@ async function runTrigger(t, ctxData, params) {
271
302
  }
272
303
  await deliverTwinNotification(t.point, t, {
273
304
  uid,
274
- text: `[${t.name}] ${text}`,
305
+ text,
275
306
  eventName,
276
307
  entityId,
277
308
  });
@@ -380,7 +411,7 @@ export async function onDbEvent(eventName, { basePath = '', cls = null, obj = nu
380
411
  continue;
381
412
  for (const doc of docs.values()) {
382
413
  const m = doc.meta || {};
383
- if (m.enabled === false || !m.as)
414
+ if (m.enabled === false)
384
415
  continue;
385
416
  if (!onList(m).includes(eventName))
386
417
  continue;
@@ -449,7 +480,7 @@ export async function onChatEvent({ storage, thread, message, params = {} } = {}
449
480
  let n = 0;
450
481
  for (const doc of docs.values()) {
451
482
  const m = doc.meta || {};
452
- if (m.enabled === false || !m.as)
483
+ if (m.enabled === false)
453
484
  continue;
454
485
  if (!onList(m).includes('chat:message'))
455
486
  continue;
@@ -89,18 +89,32 @@ export async function askTwin({ fromPath = '/', targetPath, question, session, d
89
89
  if (!STRUCT_TYPES.has(targetItem.type))
90
90
  throw new Error(`twin_ask: адресат ${target} не является структурным Агентом (${targetItem.type})`);
91
91
 
92
+ let hasHumanAccess = true;
93
+ let hasHumanRoles = true;
94
+ let hasNodeRole = false;
92
95
  if (!DEV_MODE && session && session.$user !== WORK) {
93
- const canSee = await targetItem.canSee?.({ session }, { session }).catch(() => false);
96
+ const canSee = await targetItem.canSee?.(targetItem, { session }).catch(() => false);
94
97
  const roles = await targetItem.roles?.({ session }).catch(() => []);
95
- if (!canSee && !roles.length)
98
+ hasHumanRoles = Array.isArray(roles) && roles.length > 0;
99
+ hasHumanAccess = Boolean(canSee || hasHumanRoles);
100
+ hasNodeRole = Boolean(await targetItem.hasNodeRole?.(from).catch(() => false));
101
+ if (!hasHumanAccess && !hasNodeRole)
96
102
  throw new Error(`twin_ask: нет прав доступа к узлу ${target}`);
97
103
  }
104
+ else {
105
+ const roles = await targetItem.roles?.({ session }).catch(() => []);
106
+ hasHumanRoles = Array.isArray(roles) && roles.length > 0;
107
+ hasNodeRole = Boolean(await targetItem.hasNodeRole?.(from).catch(() => false));
108
+ hasHumanAccess = hasHumanRoles;
109
+ }
98
110
 
99
111
  const nextVisited = [...prevVisited, target];
100
112
  const nextDepth = depth + 1;
113
+ const useRoleOnly = Boolean(hasNodeRole && !hasHumanRoles);
101
114
  const childSession = {
102
115
  ...session,
103
116
  twinCall: Object.freeze({ fromPath: from, targetPath: target, depth: nextDepth, visited: nextVisited }),
117
+ ...(useRoleOnly ? { twinRoleOnly: true } : {}),
104
118
  };
105
119
 
106
120
  const prompt = `[Межагентный запрос от узла ${from} (глубина ${nextDepth}/${MAX_TWIN_DEPTH})]\n`
@@ -209,7 +223,7 @@ export const twinRuleSaveTool = {
209
223
 
210
224
  export const twinScheduleSaveTool = {
211
225
  name: 'twin_schedule_save',
212
- description: 'Создать, переключить или удалить регулярное расписание задач текущего структурного узла (только BOSS).',
226
+ description: 'Создать, переключить или удалить регулярное расписание задач текущего структурного узла (только BOSS). Поддерживает ODANT-маску времени (например YYYY-MM-05T10:15:00) и повтор готовой .task.',
213
227
  risk: 'write',
214
228
  parameters: {
215
229
  type: 'object',
@@ -217,9 +231,10 @@ export const twinScheduleSaveTool = {
217
231
  id: { type: 'string', description: 'ID расписания (для toggle или delete)' },
218
232
  label: { type: 'string', description: 'Название регулярной обязанности' },
219
233
  prompt: { type: 'string', description: 'Что именно должен проверять/делать двойник по расписанию' },
234
+ task: { type: 'string', description: 'WORK-путь готовой .task для повторного выполнения (необязательно)' },
220
235
  rule: {
221
236
  type: 'object',
222
- description: 'Правило времени: { kind: "daily"|"weekly"|"every"|"once", at?: "09:00", days?: [1,2,3,4,5], minutes?: 60 }',
237
+ description: 'Правило времени: { mask: "YYYY-MM-05T10:15:00" } | { every: 60 } | { at: "09:00", days?: [1..5] } | { once: ISO }',
223
238
  },
224
239
  tz: { type: 'string', description: 'Часовой пояс, например Europe/Moscow' },
225
240
  toggle: { type: 'boolean', description: 'Переключить enabled для id' },
@@ -236,4 +251,50 @@ export const twinScheduleSaveTool = {
236
251
  },
237
252
  };
238
253
 
239
- export const twinTools = [twinAskTool, twinRuleListTool, twinRuleSaveTool, twinScheduleSaveTool];
254
+ export const twinSystemSaveTool = {
255
+ name: 'twin_system_save',
256
+ description: 'Обновить системную инструкцию (правила поведения) цифрового двойника текущего узла (ai/system.md, только BOSS).',
257
+ risk: 'write',
258
+ parameters: {
259
+ type: 'object',
260
+ properties: {
261
+ text: { type: 'string', description: 'Текст инструкции для агента этого подразделения' },
262
+ replace: { type: 'boolean', description: 'true — заменить правила сверху; false (по умолчанию) — дополнить их' },
263
+ },
264
+ required: ['text'],
265
+ },
266
+ async run(args, ctx) {
267
+ if (!ctx?.session || ctx.session.twinCall)
268
+ throw new Error('twin_system_save: недоступно в Service Plane');
269
+ const place = ctx.place || globalThis.WORK;
270
+ const { saveNodeAgentSystem } = await import('./node-rules.js');
271
+ return saveNodeAgentSystem(place, { session: ctx.session, post: args });
272
+ },
273
+ };
274
+
275
+ export const twinSecuritySaveTool = {
276
+ name: 'twin_security_save',
277
+ description: 'Настроить права доступа подразделения: назначить руководителя (одного BOSS), роли (ROLES), участников (людей и подразделения) и привязку классов (LINKS) — только BOSS.',
278
+ risk: 'write',
279
+ parameters: {
280
+ type: 'object',
281
+ properties: {
282
+ security: {
283
+ type: 'object',
284
+ description: 'Секция #security: { BOSS: [uid?], ROLES: [{ id, label, external?, USERS: [uid|nodePath], LINKS: [{ id, access: "read"|"write", scope? }] }] }',
285
+ },
286
+ title: { type: 'string', description: 'Краткий заголовок изменения для журнала босса' },
287
+ summary: { type: 'string', description: 'Описание изменения' },
288
+ },
289
+ required: ['security'],
290
+ },
291
+ async run(args, ctx) {
292
+ if (!ctx?.session || ctx.session.twinCall)
293
+ throw new Error('twin_security_save: недоступно в Service Plane');
294
+ const place = ctx.place || globalThis.WORK;
295
+ const { saveNodeSecurity } = await import('./node-rules.js');
296
+ return saveNodeSecurity(place, { session: ctx.session, post: args });
297
+ },
298
+ };
299
+
300
+ export const twinTools = [twinAskTool, twinRuleListTool, twinRuleSaveTool, twinScheduleSaveTool, twinSystemSaveTool, twinSecuritySaveTool];
@@ -46,6 +46,8 @@ 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_tasks_list: L.READ,
50
+ security_update: L.ADMIN,
49
51
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
50
52
  work_zone: L.READ, places: L.READ,
51
53
  data_access: L.READ, link_tree: L.READ, search_tree: L.USER,
@@ -117,9 +117,17 @@ function takeRank(best, level) {
117
117
  * Место даёт свой access участникам; вышестоящее место и BOSS видят
118
118
  * ссылки вложенных мест на чтение; общая ссылка — всем назначенным.
119
119
  */
120
+ function linkSubject(cls, params = {}) {
121
+ const uid = cls.constructor.resolveUid(params);
122
+ const nodePath = params?.session?.twinCall?.fromPath || '';
123
+ const nodeOnly = Boolean(params?.session?.twinRoleOnly);
124
+ return nodePath ? { uid, nodePath, nodeOnly } : uid;
125
+ }
126
+
120
127
  export async function linkLevel(cls, params = {}) {
121
128
  if (NO_LINK_TYPES.has(cls.type))
122
129
  return null;
130
+ const subject = linkSubject(cls, params);
123
131
  const uid = cls.constructor.resolveUid(params);
124
132
  let best = null;
125
133
  for (const { structure, place, access } of await covering(cls.path)) {
@@ -137,14 +145,14 @@ export async function linkLevel(cls, params = {}) {
137
145
  continue;
138
146
  const sec = g.DATA?.['#security'];
139
147
  if (place) {
140
- if (WORKPLACES.memberTrailKeys(sec, uid).includes(place))
148
+ if (WORKPLACES.memberTrailKeys(sec, subject).includes(place))
141
149
  best = takeRank(best, access);
142
- else if (WORKPLACES.isAncestorPlaceMember(sec, uid, place))
150
+ else if (!params?.session?.twinRoleOnly && WORKPLACES.isAncestorPlaceMember(sec, uid, place))
143
151
  best = takeRank(best, 'read');
144
- else if (roles.includes('BOSS'))
152
+ else if (!params?.session?.twinRoleOnly && roles.includes('BOSS'))
145
153
  best = takeRank(best, 'read');
146
154
  }
147
- else if (roles.includes('BOSS') || roles.includes('USER')) {
155
+ else if (!params?.session?.twinRoleOnly && (roles.includes('BOSS') || roles.includes('USER'))) {
148
156
  best = takeRank(best, roles.includes('BOSS') && access === 'write' ? 'admin' : access);
149
157
  }
150
158
  }
@@ -156,8 +164,10 @@ export async function linkLevel(cls, params = {}) {
156
164
  * прямые назначения плюс ссылки рабочих мест (кроме структурных типов).
157
165
  */
158
166
  export async function dataAccess(cls, params = {}) {
159
- if (DEV_MODE)
167
+ if (DEV_MODE && !params?.session?.twinRoleOnly)
160
168
  return 'admin';
169
+ if (params?.session?.twinRoleOnly)
170
+ return await linkLevel(cls, params);
161
171
  return takeRank(await directAccess(cls, params), await linkLevel(cls, params));
162
172
  }
163
173
 
@@ -225,7 +235,7 @@ export async function scopeLinks(cls, params = {}) {
225
235
  const labels = {};
226
236
  for (const { node, trail } of WORKPLACES.walkPlaces(WORKPLACES.normalizeSecurity(sec).places))
227
237
  labels[WORKPLACES.trailKey(trail)] = node.label;
228
- return { roles, sec, labels, places: WORKPLACES.memberTrailKeys(sec, uid) };
238
+ return { roles, sec, labels, places: WORKPLACES.memberTrailKeys(sec, linkSubject(cls, params)) };
229
239
  })());
230
240
  }
231
241
  const s = await seen.get(e.structure);
@@ -32,10 +32,32 @@ export function isPseudoUser(id) {
32
32
  return id === 'USERS' || id === 'GUESTS' || id === 'GUEST';
33
33
  }
34
34
 
35
- /** Сопоставление субъекта uid (или null для гостя) со списком назначенных USERS. */
36
- export function matchesUserList(list, uid) {
35
+ /** Проверка, является ли идентификатор путём структурного подразделения (/ORGANIZATIONS/...). */
36
+ export function isNodeSubject(id) {
37
+ return typeof id === 'string' && id.startsWith('/');
38
+ }
39
+
40
+ function normNodePath(p) {
41
+ const s = String(p || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
42
+ return s || '/';
43
+ }
44
+
45
+ /** Сопоставление субъекта uid (строка/null или { uid, nodePath, nodeOnly }) со списком назначенных USERS. */
46
+ export function matchesUserList(list, subject) {
37
47
  if (!Array.isArray(list) || !list.length)
38
48
  return false;
49
+ if (subject && typeof subject === 'object' && !Array.isArray(subject)) {
50
+ const { uid = null, nodePath = '', nodeOnly = false } = subject;
51
+ if (nodePath) {
52
+ const target = normNodePath(nodePath);
53
+ if (list.some(item => isNodeSubject(item) && normNodePath(item) === target))
54
+ return true;
55
+ }
56
+ if (nodeOnly)
57
+ return false;
58
+ return matchesUserList(list, uid);
59
+ }
60
+ const uid = subject;
39
61
  if (list.includes('GUESTS') || list.includes('GUEST'))
40
62
  return true;
41
63
  if (!uid)
@@ -45,6 +67,17 @@ export function matchesUserList(list, uid) {
45
67
  return list.includes(uid);
46
68
  }
47
69
 
70
+ /** Пути (trail) не-external ролей, в которые добавлено подразделение nodePath. */
71
+ export function nodePlaceTrails(security, nodePath) {
72
+ if (!nodePath)
73
+ return [];
74
+ const { places } = normalizeSecurity(security);
75
+ const subject = { nodePath, nodeOnly: true };
76
+ return walkPlaces(places)
77
+ .filter(({ node }) => !node.external && matchesUserList(node.USERS, subject))
78
+ .map(({ trail }) => trailKey(trail));
79
+ }
80
+
48
81
  /** Открыта ли точка для неавторизованных гостей (через USER или любое рабочее место ROLES). */
49
82
  export function isOpenToGuests(security) {
50
83
  if (!security || typeof security !== 'object')
@@ -224,6 +224,42 @@ export const classFeedMethods = {
224
224
  return saveNodeProactivity(this, params);
225
225
  },
226
226
 
227
+ /** Получить собственную инструкцию агента узла (ai/system.md) и унаследованные слои (только BOSS). */
228
+ async agent_system_get(params = {}) {
229
+ const { getNodeAgentSystem } = await import('../../modules/agent/node-rules.js');
230
+ return getNodeAgentSystem(this, params);
231
+ },
232
+
233
+ /** Сохранить системную инструкцию агента узла (ai/system.md, только BOSS). */
234
+ async agent_system_save(params = {}) {
235
+ const { saveNodeAgentSystem } = await import('../../modules/agent/node-rules.js');
236
+ return saveNodeAgentSystem(this, params);
237
+ },
238
+
239
+ /** Дерево доступных прикладных классов (модули организации + общие /MODULES, только BOSS). */
240
+ async agent_available_classes(params = {}) {
241
+ const { listNodeAvailableClasses } = await import('../../modules/agent/node-rules.js');
242
+ return listNodeAvailableClasses(this, params);
243
+ },
244
+
245
+ /** Список подразделений организации/проекта (для добавления в роли, только BOSS). */
246
+ async agent_structures_list(params = {}) {
247
+ const { listNodeStructures } = await import('../../modules/agent/node-rules.js');
248
+ return listNodeStructures(this, params);
249
+ },
250
+
251
+ /** Список последних выполненных задач (.task) узла для повторения по расписанию (только BOSS). */
252
+ async agent_tasks_list(params = {}) {
253
+ const { listNodeTasks } = await import('../../modules/agent/node-rules.js');
254
+ return listNodeTasks(this, params);
255
+ },
256
+
257
+ /** Сохранить права/роли подразделения (#security) с фиксацией таски босса (только BOSS). */
258
+ async security_update(params = {}) {
259
+ const { saveNodeSecurity } = await import('../../modules/agent/node-rules.js');
260
+ return saveNodeSecurity(this, params);
261
+ },
262
+
227
263
  /** Публичный список настроенных почтовых ящиков узла (без паролей и секретов). */
228
264
  async mail_accounts(params = {}) {
229
265
  return MAILCAL.mailAccounts(this, params);
@@ -143,10 +143,22 @@ export const classSecurityMethods = {
143
143
  return WORKPLACES.isClientMember(this.DATA?.['#security'], uid);
144
144
  },
145
145
 
146
+ /** Назначено ли подразделение nodePath в какую-либо роль (#security.ROLES) этого узла. */
147
+ async hasNodeRole(nodePath) {
148
+ if (!nodePath || !(await this._isStructure()))
149
+ return false;
150
+ await this.init;
151
+ return WORKPLACES.nodePlaceTrails(this.DATA?.['#security'], nodePath).length > 0;
152
+ },
153
+
146
154
  /** Получить список ролей текущего пользователя в классе. */
147
155
  async roles(params = {}) {
148
- const uid = this.constructor.resolveUid(params);
149
156
  await this.init;
157
+ const twinFrom = params?.session?.twinCall?.fromPath || '';
158
+ if (params?.session?.twinRoleOnly && twinFrom) {
159
+ return (await this.hasNodeRole(twinFrom)) ? ['USER'] : [];
160
+ }
161
+ const uid = this.constructor.resolveUid(params);
150
162
  const declared = this._declaredRolesSync();
151
163
  if (!uid) {
152
164
  if (WORKPLACES.matchesUserList(this._roleIds('USER', declared), null) || await this._isPlaceMember(null))
@@ -174,7 +186,7 @@ export const classSecurityMethods = {
174
186
  }
175
187
  }
176
188
  }
177
- if (!roles.includes('USER') && await this._isPlaceMember(uid))
189
+ if (!roles.includes('USER') && (await this._isPlaceMember(uid) || (twinFrom && await this.hasNodeRole(twinFrom))))
178
190
  roles.push('USER');
179
191
  if (!roles.includes('CLIENT') && await this._isClientMember(uid))
180
192
  roles.push('CLIENT');
@@ -515,7 +527,16 @@ export const classSecurityMethods = {
515
527
 
516
528
  /** Видимость элемента (чтение). */
517
529
  async canSee(item, params = {}) {
518
- if (DEV_MODE) return true;
530
+ const twinRoleOnly = Boolean(params?.session?.twinRoleOnly);
531
+ if (DEV_MODE && !twinRoleOnly) return true;
532
+ if (twinRoleOnly) {
533
+ if (!item || typeof item !== 'object') return false;
534
+ if (this._isSystemItem(item)) return true;
535
+ if (await LINKS.grants(this, item, params)) return true;
536
+ const roles = await this.roles(params);
537
+ if (!roles.length) return false;
538
+ return this._readableByRoles(item, roles, null);
539
+ }
519
540
  const users = this.DATA?.['#security']?.USER;
520
541
  if (Array.isArray(users) && (users.includes('GUEST') || users.includes('GUESTS'))) return true;
521
542
  if (!item || typeof item !== 'object') return true;
@@ -569,8 +590,20 @@ export const classSecurityMethods = {
569
590
 
570
591
  /** Право записи (при отсутствии params.role использует сильнейшую роль пользователя в точке). */
571
592
  async canWrite(item, params = {}) {
572
- if (DEV_MODE) return true;
593
+ const twinRoleOnly = Boolean(params?.session?.twinRoleOnly);
594
+ if (DEV_MODE && !twinRoleOnly) return true;
573
595
  if (!item || typeof item !== 'object') return false;
596
+ if (twinRoleOnly) {
597
+ const roles = await this.roles(params);
598
+ if (!roles.length) return false;
599
+ const rel = [params.folder, params.filename].filter(Boolean).join('/');
600
+ const target = rel && item.path ? item.path.replace(/\/+$/, '') + '/' + rel : item.path;
601
+ const protectedTarget = POLICY.isSystemMetaPath(target, this.path)
602
+ || POLICY.isExecutablePath(target, this.path)
603
+ || POLICY.isAgentControlPath(target, this.path);
604
+ if (protectedTarget) return false;
605
+ return LINKS.grantsWrite(this, params);
606
+ }
574
607
  const uid = this.constructor.resolveUid(params);
575
608
  if (!uid) return false;
576
609
  const rel = [params.folder, params.filename].filter(Boolean).join('/');
@@ -611,9 +644,9 @@ export const classSecurityMethods = {
611
644
 
612
645
  /** Единая проверка доступа (бросает при отказе): read → canSee, write → canWrite, BOSS → BOSS точки или корня. */
613
646
  async assertAccess(params = {}, level = this.constructor.ACCESS_LEVEL.READ, folder) {
614
- if (DEV_MODE) return;
647
+ if (DEV_MODE && !params?.session?.twinRoleOnly) return;
615
648
  if (!params?.session) return;
616
- if (params.session?.$user === globalThis.WORK) return;
649
+ if (params.session?.$user === globalThis.WORK && !params?.session?.twinRoleOnly) return;
617
650
  const uid = this.constructor.resolveUid(params);
618
651
  const L = this.constructor.ACCESS_LEVEL;
619
652
  const ROLES = this.constructor.ROLES;
@@ -711,6 +744,7 @@ export const classSecurityMethods = {
711
744
  * напрямую и не вызывает canWrite/assertAccess/_isWorkBoss.
712
745
  */
713
746
  async _isWorkBoss(params = {}) {
747
+ if (params?.session?.twinRoleOnly) return false;
714
748
  if (!globalThis.WORK) return false;
715
749
  return globalThis.WORK.roles?.(params).then(r => r.includes(this.constructor.ROLES.BOSS));
716
750
  },