odant-work 1.0.65 → 1.0.67

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 (66) hide show
  1. package/#system/package-manifest.json +56 -59
  2. package/{PROJECTS → $server/$folder/$class}/$domain/handlers/methods/restore/$handler/class.js +40 -24
  3. package/$server/$folder/$class/$structure/$server/handlers/methods/distro/$handler/class.js +0 -2
  4. package/$server/$folder/$class/$structure/handlers/methods/archive/$handler/class.js +27 -0
  5. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js +9 -0
  6. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/data.js +310 -0
  7. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/class.js +1 -0
  8. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +160 -1
  9. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +2 -0
  10. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +1 -0
  11. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/class.js +10 -0
  12. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +233 -0
  13. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +289 -0
  14. package/$server/$folder/$class/$structure/handlers/pages/form/{search/$handler → system/$handler/tabs}/search.js +4 -1
  15. package/$server/$folder/$class/$structure/handlers/pages/form/{staff/$handler → system/$handler/tabs}/staff.js +122 -14
  16. package/$server/$folder/$class/handlers/pages/form/editor/$handler/class.js +3 -0
  17. package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +10 -6
  18. package/$server/$folder/handlers/pages/form/$handler/form.js +27 -2
  19. package/$server/$folder/lib/dot/dot-math.js +1 -1
  20. package/$server/$folder/lib/dot/dot.js +19 -5
  21. package/$server/$folder/lib/explorer/explorer.js +29 -15
  22. package/$server/$folder/lib/node/node.js +49 -4
  23. package/$server/$folder/lib/security/users/users.js +68 -3
  24. package/$server/$folder/lib/tools/tools.js +3 -3
  25. package/$server/$folder/lib/tree/tree.js +29 -13
  26. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/gantt/$handler/gantt.js" +293 -1
  27. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/scheduler/$handler/scheduler.js" +234 -1
  28. package/ORGANIZATIONS/$domain/class.js +1 -0
  29. package/PROJECTS/$domain/class.js +1 -0
  30. package/package.json +1 -1
  31. package/sources/client/handler.js +27 -11
  32. package/sources/client.js +36 -0
  33. package/sources/data/api.js +25 -5
  34. package/sources/data/db.js +39 -0
  35. package/sources/data/scope.js +2 -1
  36. package/sources/host/websocket.js +22 -0
  37. package/sources/modules/agent/index.js +11 -1
  38. package/sources/modules/agent/node-rules.js +171 -0
  39. package/sources/modules/agent/resources.js +1 -0
  40. package/sources/modules/agent/scheduler.js +75 -17
  41. package/sources/modules/agent/triggers.js +486 -198
  42. package/sources/modules/agent/twin-bus.js +163 -0
  43. package/sources/server/access/gateway.js +3 -0
  44. package/sources/server/access/links.js +8 -4
  45. package/sources/server/access/policy.js +7 -2
  46. package/sources/server/access/workplaces.js +14 -5
  47. package/sources/server/chat-threads.js +640 -0
  48. package/sources/server/class/archive.js +4 -3
  49. package/sources/server/class/feed.js +59 -0
  50. package/sources/server/class/security.js +18 -3
  51. package/sources/server/handler.js +1 -2
  52. package/$server/$folder/$class/$structure/$base/handlers/methods/archive/$handler/class.js +0 -23
  53. package/$server/$folder/$class/$structure/$project/handlers/methods/archive/$handler/class.js +0 -23
  54. package/$server/$folder/$class/$structure/$server/handlers/pages/form/license/$handler/class.js +0 -9
  55. package/$server/$folder/$class/$structure/handlers/pages/form/database/$handler/class.js +0 -9
  56. package/$server/$folder/$class/$structure/handlers/pages/form/gantt/$handler/class.js +0 -27
  57. package/$server/$folder/$class/$structure/handlers/pages/form/gantt/$handler/gantt.js +0 -293
  58. package/$server/$folder/$class/$structure/handlers/pages/form/messengers/$handler/class.js +0 -5
  59. package/$server/$folder/$class/$structure/handlers/pages/form/scheduler/$handler/class.js +0 -27
  60. package/$server/$folder/$class/$structure/handlers/pages/form/scheduler/$handler/scheduler.js +0 -234
  61. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +0 -5
  62. package/$server/$folder/$class/$structure/handlers/pages/form/staff/$handler/class.js +0 -5
  63. package/ORGANIZATIONS/$domain/handlers/methods/restore/$handler/class.js +0 -173
  64. /package/$server/$folder/$class/$structure/handlers/pages/form/{database/$handler → system/$handler/tabs}/database.js +0 -0
  65. /package/$server/$folder/$class/$structure/{$server/handlers/pages/form/license/$handler → handlers/pages/form/system/$handler/tabs}/license.js +0 -0
  66. /package/$server/$folder/$class/$structure/handlers/pages/form/{messengers/$handler → system/$handler/tabs}/messengers.js +0 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Внутренний межагентный канал WORK (`twin_ask`):
3
+ * позволяет Агенту одного структурного узла ($structure/$base/$project/$server)
4
+ * задать структурированный вопрос или запросить действие у Агента другого узла
5
+ * с жёстким лимитом глубины (maxDepth = 3), защитой от циклов (visited),
6
+ * сквозной авторизацией инициатора и изоляцией от Control Plane.
7
+ */
8
+ import { DEV_MODE } from '../../host/config.js';
9
+ import { audit } from '../../server/access/audit.js';
10
+ import { FS } from '../../server/index.js';
11
+
12
+ export const MAX_TWIN_DEPTH = 3;
13
+
14
+ const STRUCT_TYPES = new Set(['$server', '$base', '$project', '$structure']);
15
+
16
+ function normPath(p) {
17
+ const s = String(p || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
18
+ if (!s || s === '/')
19
+ return '/';
20
+ return s.startsWith('/') ? s : '/' + s;
21
+ }
22
+
23
+ function baseContainerOf(p) {
24
+ const m = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(normPath(p));
25
+ return m ? m[1] : '';
26
+ }
27
+
28
+ function sameBoundary(fromPath, targetPath) {
29
+ const a = normPath(fromPath);
30
+ const b = normPath(targetPath);
31
+ if (b === '/')
32
+ return true;
33
+ const baseA = baseContainerOf(a);
34
+ const baseB = baseContainerOf(b);
35
+ if (baseA && baseB)
36
+ return baseA === baseB;
37
+ if (!baseA && !baseB)
38
+ return true;
39
+ // Из корня WORK ($) вниз в организацию/проект — разрешено, из организации в чужую — нет
40
+ return a === '/';
41
+ }
42
+
43
+ let customRunner = null;
44
+ export function setTwinRunner(fn) {
45
+ customRunner = typeof fn === 'function' ? fn : null;
46
+ }
47
+
48
+ /**
49
+ * Вызвать Агента целевого узла в Service Plane.
50
+ * @param {object} opts
51
+ * @param {string} opts.fromPath Путь вызывающего узла
52
+ * @param {string} opts.targetPath Путь целевого узла ($structure/$base/$project/$server)
53
+ * @param {string} opts.question Суть запроса
54
+ * @param {object} opts.session Сессия инициатора
55
+ * @param {number} [opts.depth=0]
56
+ * @param {string[]} [opts.visited=[]]
57
+ * @param {Function} [opts.runner]
58
+ */
59
+ export async function askTwin({ fromPath = '/', targetPath, question, session, depth = 0, visited = [], runner } = {}) {
60
+ const WORK = globalThis.WORK;
61
+ if (!WORK)
62
+ throw new Error('WORK не инициализирован');
63
+ const from = normPath(fromPath);
64
+ const target = normPath(targetPath);
65
+ const q = String(question || '').trim();
66
+ if (!q)
67
+ throw new Error('twin_ask: пустой вопрос');
68
+
69
+ const prevVisited = Array.isArray(visited) ? visited.map(normPath) : [];
70
+ if (!prevVisited.includes(from))
71
+ prevVisited.push(from);
72
+
73
+ if (depth >= MAX_TWIN_DEPTH)
74
+ throw new Error(`twin_ask: превышена максимальная глубина вызовов (${MAX_TWIN_DEPTH})`);
75
+ if (prevVisited.includes(target))
76
+ throw new Error(`twin_ask: обнаружен цикл вызова на узле ${target}`);
77
+
78
+ const isWorkBoss = DEV_MODE || !session || session.$user === WORK
79
+ || await WORK._isWorkBoss?.({ session }).catch(() => false);
80
+ if (!isWorkBoss && !sameBoundary(from, target))
81
+ throw new Error(`twin_ask: переход за границы организации/проекта запрещён (${from} → ${target})`);
82
+
83
+ let targetItem = await WORK.get_item(target).catch(() => null);
84
+ if (Array.isArray(targetItem))
85
+ targetItem = targetItem.at(-1);
86
+ if (!targetItem || !(targetItem instanceof FS.$class))
87
+ throw new Error(`twin_ask: узел не найден (${target})`);
88
+ await targetItem.init;
89
+ if (!STRUCT_TYPES.has(targetItem.type))
90
+ throw new Error(`twin_ask: адресат ${target} не является структурным Агентом (${targetItem.type})`);
91
+
92
+ if (!DEV_MODE && session && session.$user !== WORK) {
93
+ const canSee = await targetItem.canSee?.({ session }, { session }).catch(() => false);
94
+ const roles = await targetItem.roles?.({ session }).catch(() => []);
95
+ if (!canSee && !roles.length)
96
+ throw new Error(`twin_ask: нет прав доступа к узлу ${target}`);
97
+ }
98
+
99
+ const nextVisited = [...prevVisited, target];
100
+ const nextDepth = depth + 1;
101
+ const childSession = {
102
+ ...session,
103
+ twinCall: Object.freeze({ fromPath: from, targetPath: target, depth: nextDepth, visited: nextVisited }),
104
+ };
105
+
106
+ const prompt = `[Межагентный запрос от узла ${from} (глубина ${nextDepth}/${MAX_TWIN_DEPTH})]\n`
107
+ + `Ответь кратко и по делу исключительно в рамках полномочий и данных узла ${target}. `
108
+ + `Не выполняй модификаций кода, схем или прав доступа (Service Plane).\n\n`
109
+ + `Запрос: ${q}`;
110
+
111
+ audit('twin_ask', { from, target, depth: nextDepth, params: { session } });
112
+
113
+ const exec = runner || customRunner || (async o => (await import('./index.js')).runOnce(o));
114
+ const res = await exec({
115
+ place: targetItem,
116
+ session: childSession,
117
+ prompt,
118
+ mode: 'ask',
119
+ signal: AbortSignal.timeout(5 * 60_000),
120
+ });
121
+
122
+ return {
123
+ ok: res?.status !== 'error',
124
+ fromPath: from,
125
+ targetPath: target,
126
+ depth: nextDepth,
127
+ visited: nextVisited,
128
+ status: res?.status || 'done',
129
+ answer: String(res?.content || '').trim(),
130
+ };
131
+ }
132
+
133
+ export const twinAskTool = {
134
+ name: 'twin_ask',
135
+ description: 'Обратиться к цифровому двойнику (Агенту) другого подразделения, организации, проекта или WORK (Service Plane, глубина <= 3, без циклов).',
136
+ parameters: {
137
+ type: 'object',
138
+ properties: {
139
+ target: { type: 'string', description: 'WORK-путь целевого узла ($structure, $base, $project, /)' },
140
+ question: { type: 'string', description: 'Чёткий запрос или поручение для Агента целевого узла' },
141
+ },
142
+ required: ['target', 'question'],
143
+ },
144
+ async run({ target, question }, ctx) {
145
+ if (!ctx?.session)
146
+ throw new Error('twin_ask: нет сессии');
147
+ const fromPath = ctx?.place?.path || '/';
148
+ const prev = ctx.session.twinCall || {};
149
+ const depth = Number(prev.depth) || 0;
150
+ const visited = Array.isArray(prev.visited) ? prev.visited : [fromPath];
151
+ // В Control Plane или из обычного диалога межагентный запрос всегда идёт с Service Plane (mode: ask)
152
+ return askTwin({
153
+ fromPath,
154
+ targetPath: target,
155
+ question,
156
+ session: ctx.session,
157
+ depth,
158
+ visited,
159
+ });
160
+ },
161
+ };
162
+
163
+ export const twinTools = [twinAskTool];
@@ -40,6 +40,9 @@ export const MEMBERS = Object.freeze({
40
40
  semantic_search: L.READ, search: L.READ, query_objects: L.READ, rag_status: L.READ,
41
41
  logs: L.READ, logs_dates: L.READ, log_files: L.READ, read_log_bodies: L.READ,
42
42
  read_log_entry: L.READ, log_index: L.READ, chatSource: L.READ,
43
+ chat_thread_open: L.CALL, chat_threads_list: L.READ, chat_messages_list: L.READ,
44
+ chat_send: L.WRITE, chat_mark_read: L.WRITE, chat_action: L.WRITE, chat_unread_summary: L.USER, visible_contacts: L.USER,
45
+ agent_rules_list: L.READ, agent_rule_save: L.ADMIN, agent_schedule_save: L.ADMIN,
43
46
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
44
47
  work_zone: L.READ, places: L.READ,
45
48
  data_access: L.READ, link_tree: L.READ, search_tree: L.USER,
@@ -77,7 +77,7 @@ async function collect() {
77
77
  for (const { node, trail } of WORKPLACES.walkPlaces(places)) {
78
78
  const place = WORKPLACES.trailKey(trail);
79
79
  for (const l of node.LINKS)
80
- out.push({ structure: clsPath, place, id: l.id, access: l.access, ...(l.scope ? { scope: l.scope } : {}) });
80
+ out.push({ structure: clsPath, place, id: l.id, access: l.access, ...(l.scope ? { scope: l.scope } : {}), ...(node.external ? { external: true } : {}) });
81
81
  }
82
82
  }
83
83
  catch { /* нет доступа */ }
@@ -144,7 +144,7 @@ export async function linkLevel(cls, params = {}) {
144
144
  else if (roles.includes('BOSS'))
145
145
  best = takeRank(best, 'read');
146
146
  }
147
- else {
147
+ else if (roles.includes('BOSS') || roles.includes('USER')) {
148
148
  best = takeRank(best, roles.includes('BOSS') && access === 'write' ? 'admin' : access);
149
149
  }
150
150
  }
@@ -231,8 +231,12 @@ export async function scopeLinks(cls, params = {}) {
231
231
  const s = await seen.get(e.structure);
232
232
  if (!s)
233
233
  continue;
234
- const base = { structure: e.structure, place: e.place, id: e.id, scope: e.scope ?? null, places: s.places, labels: s.labels };
235
- if (!e.place || s.places.includes(e.place))
234
+ const base = { structure: e.structure, place: e.place, id: e.id, scope: e.scope ?? null, ...(e.external ? { external: true } : {}), places: s.places, labels: s.labels };
235
+ if (!e.place) {
236
+ if (s.roles.includes('BOSS') || s.roles.includes('USER'))
237
+ out.push({ ...base, access: e.access, relation: 'member' });
238
+ }
239
+ else if (s.places.includes(e.place))
236
240
  out.push({ ...base, access: e.access, relation: 'member' });
237
241
  else if (WORKPLACES.isAncestorPlaceMember(s.sec, uid, e.place))
238
242
  out.push({ ...base, access: 'read', relation: 'ancestor' });
@@ -59,6 +59,7 @@ export const SYSTEM_META_NAMES = Object.freeze([
59
59
  export const BASE_ROLES = Object.freeze({
60
60
  BOSS: Object.freeze({ id: 'BOSS', label: 'Руководитель', icon: '', color: '', principals: Object.freeze(['user']) }),
61
61
  USER: Object.freeze({ id: 'USER', label: 'Исполнитель', icon: '', color: '', principals: Object.freeze(['user', 'node']) }),
62
+ CLIENT: Object.freeze({ id: 'CLIENT', label: 'Клиент', icon: '', color: '', principals: Object.freeze(['user']) }),
62
63
  });
63
64
 
64
65
  /** Системная ли роль (поведение из кода, а не из данных). */
@@ -75,8 +76,8 @@ export function seesFullFeed(role) {
75
76
  /** Виды субъектов: пользователь этого сервера | узел сети WORK (другой сервер и его представители). */
76
77
  export const PRINCIPALS = Object.freeze(['user', 'node']);
77
78
 
78
- /** Порядок ролей «по силе»: BOSS, затем USER и остальные в порядке объявления. */
79
- export const BASE_ORDER = Object.freeze(['BOSS', 'USER']);
79
+ /** Порядок ролей «по силе»: BOSS, затем USER, CLIENT и остальные в порядке объявления. */
80
+ export const BASE_ORDER = Object.freeze(['BOSS', 'USER', 'CLIENT']);
80
81
 
81
82
  /** Имя роли — заглавные латиница/цифры/подчёркивание (совпадает с именем папки зоны). */
82
83
  export function isRoleId(id) {
@@ -205,6 +206,8 @@ export function canRead(role, area, opts = {}) {
205
206
  return true;
206
207
  if (area.kind === AREA.SECRET)
207
208
  return false;
209
+ if (role.id === 'CLIENT')
210
+ return area.kind === AREA.SYSTEM;
208
211
  switch (area.kind) {
209
212
  case AREA.SYSTEM:
210
213
  case AREA.FILES:
@@ -234,6 +237,8 @@ export function canWrite(role, area, opts = {}) {
234
237
  return false;
235
238
  if (role.id === 'BOSS')
236
239
  return true;
240
+ if (role.id === 'CLIENT')
241
+ return false;
237
242
  if (!opts.local || opts.executable)
238
243
  return false;
239
244
  if (area.kind === AREA.FILES)
@@ -96,6 +96,7 @@ export function normalizePlaces(raw, seen = new Set(), depth = 0) {
96
96
  id,
97
97
  label: typeof r.label === 'string' && r.label ? r.label : id,
98
98
  icon: typeof r.icon === 'string' ? r.icon : '',
99
+ ...(r.external ? { external: true } : {}),
99
100
  USERS: Array.isArray(r.USERS) ? r.USERS.filter(u => typeof u === 'string') : [],
100
101
  LINKS: links,
101
102
  ROLES: normalizePlaces(r.ROLES, seen, depth + 1),
@@ -134,16 +135,24 @@ export function trailKey(trail) {
134
135
  }
135
136
 
136
137
  /** Пути (trail) мест, на которые назначен uid (с учётом псевдо-субъектов USERS и GUESTS). */
137
- export function memberTrailKeys(security, uid) {
138
+ export function memberTrailKeys(security, uid, { includeExternal = true } = {}) {
138
139
  const { places } = normalizeSecurity(security);
139
140
  return walkPlaces(places)
140
- .filter(({ node }) => matchesUserList(node.USERS, uid))
141
+ .filter(({ node }) => (includeExternal || !node.external) && matchesUserList(node.USERS, uid))
141
142
  .map(({ trail }) => trailKey(trail));
142
143
  }
143
144
 
144
- /** Назначен ли uid хоть на одно место. */
145
+ /** Назначен ли uid хоть на одно внутреннее (не-external) рабочее место. */
145
146
  export function isPlaceMember(security, uid) {
146
- return memberTrailKeys(security, uid).length > 0;
147
+ return memberTrailKeys(security, uid, { includeExternal: false }).length > 0;
148
+ }
149
+
150
+ /** Назначен ли uid как внешний клиент (роль CLIENT в #security или место с external: true). */
151
+ export function isClientMember(security, uid) {
152
+ if (matchesUserList(security?.CLIENT, uid))
153
+ return true;
154
+ const { places } = normalizeSecurity(security);
155
+ return walkPlaces(places).some(({ node }) => Boolean(node.external) && matchesUserList(node.USERS, uid));
147
156
  }
148
157
 
149
158
  /** Назначен ли uid на место placeKey или на любое место выше него. */
@@ -151,7 +160,7 @@ export function isAncestorPlaceMember(security, uid, placeKey) {
151
160
  const key = String(placeKey || '');
152
161
  if (!key)
153
162
  return false;
154
- return memberTrailKeys(security, uid).some(m => key === m || key.startsWith(m + '/'));
163
+ return memberTrailKeys(security, uid, { includeExternal: false }).some(m => key === m || key.startsWith(m + '/'));
155
164
  }
156
165
 
157
166
  /** Все uid, назначенные на места подразделения (без дубликатов). */