odant-work 1.0.66 → 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.
@@ -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];
@@ -41,7 +41,8 @@ export const MEMBERS = Object.freeze({
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
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_unread_summary: L.USER, visible_contacts: L.USER,
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,
45
46
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
46
47
  work_zone: L.READ, places: L.READ,
47
48
  data_access: L.READ, link_tree: L.READ, search_tree: L.USER,
@@ -393,6 +393,15 @@ export async function sendMessage(storage, params = {}) {
393
393
  nodePath: thread.nodePath,
394
394
  message: saved,
395
395
  });
396
+ if (!isTwinBot && thread.kind === 'twin') {
397
+ globalThis.__workPendingTriggers = (globalThis.__workPendingTriggers || 0) + 1;
398
+ import('../modules/agent/triggers.js')
399
+ .then(m => m.onChatEvent?.({ storage, thread, message: saved, params }))
400
+ .catch(() => {})
401
+ .finally(() => {
402
+ globalThis.__workPendingTriggers = Math.max(0, (globalThis.__workPendingTriggers || 1) - 1);
403
+ });
404
+ }
396
405
  return saved;
397
406
  }
398
407
 
@@ -578,3 +587,54 @@ export async function visibleContacts(storage, params = {}) {
578
587
  }
579
588
  return out;
580
589
  }
590
+
591
+ /**
592
+ * Подтвердить или отклонить карточку действия (kind = 'approval') в беседе.
593
+ */
594
+ export async function resolveApproval(storage, params = {}) {
595
+ const uid = resolveActorUid(storage, params);
596
+ if (!uid)
597
+ throw new Error(ACCESS_DENIED);
598
+ const threadId = String(params.threadId || '').trim();
599
+ const messageId = Number(params.messageId);
600
+ const action = params.action === 'approve' ? 'approve' : (params.action === 'reject' ? 'reject' : '');
601
+ if (!threadId || !Number.isFinite(messageId) || !action)
602
+ throw new Error('Требуются threadId, messageId и action (approve|reject)');
603
+
604
+ const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
605
+ const db = await dbForThreadStorage(storage, kindHint);
606
+ const thread = getThreadWithMeta(db, threadId, uid);
607
+ if (!thread)
608
+ throw new Error('Беседа не найдена');
609
+
610
+ const isParticipant = thread.participants.some(p => p.uid === uid);
611
+ const isBoss = thread.kind === 'twin'
612
+ && thread.nodePath === LOGS.feedPathOf(storage)
613
+ && await storage._canViewLocalFeed?.(params);
614
+ if (!isParticipant && !isBoss)
615
+ throw new Error(ACCESS_DENIED);
616
+
617
+ const row = db.prepare('SELECT * FROM chat_messages WHERE id = ? AND thread_id = ?').get(messageId, threadId);
618
+ if (!row)
619
+ throw new Error('Сообщение не найдено');
620
+ if (row.kind !== 'approval')
621
+ throw new Error('Сообщение не является карточкой подтверждения');
622
+ const meta = parseJsonSafe(row.meta, {});
623
+ if (meta.status && meta.status !== 'pending')
624
+ return { ok: true, alreadyResolved: true, message: formatMessageRow(row) };
625
+
626
+ const nextMeta = {
627
+ ...meta,
628
+ status: action === 'approve' ? 'approved' : 'rejected',
629
+ resolvedBy: uid,
630
+ resolvedAt: Date.now(),
631
+ };
632
+ db.prepare('UPDATE chat_messages SET meta = ? WHERE id = ?').run(JSON.stringify(nextMeta), messageId);
633
+ const updated = formatMessageRow(db.prepare('SELECT * FROM chat_messages WHERE id = ?').get(messageId));
634
+ notifyChatEvent(thread.participants.map(p => p.uid), {
635
+ type: 'chat:action',
636
+ threadId,
637
+ message: updated,
638
+ });
639
+ return { ok: true, message: updated };
640
+ }
@@ -198,11 +198,34 @@ export const classFeedMethods = {
198
198
  return CHAT.unreadSummary(this, params);
199
199
  },
200
200
 
201
+ /** Подтвердить/отклонить карточку действия (kind = 'approval') в беседе. */
202
+ async chat_action(params = {}) {
203
+ return CHAT.resolveApproval(this, params);
204
+ },
205
+
201
206
  /** Вычисляемый список видимых контактов («Люди»). */
202
207
  async visible_contacts(params = {}) {
203
208
  return CHAT.visibleContacts(this, params);
204
209
  },
205
210
 
211
+ /** Список проактивных правил и расписаний узла (только BOSS). */
212
+ async agent_rules_list(params = {}) {
213
+ const { listNodeRules } = await import('../../modules/agent/node-rules.js');
214
+ return listNodeRules(this, params);
215
+ },
216
+
217
+ /** Сохранить/удалить правило проактивности узла (только BOSS). */
218
+ async agent_rule_save(params = {}) {
219
+ const { saveNodeRule } = await import('../../modules/agent/node-rules.js');
220
+ return saveNodeRule(this, params);
221
+ },
222
+
223
+ /** Сохранить/переключить/удалить расписание узла (только BOSS). */
224
+ async agent_schedule_save(params = {}) {
225
+ const { saveNodeSchedule } = await import('../../modules/agent/node-rules.js');
226
+ return saveNodeSchedule(this, params);
227
+ },
228
+
206
229
  /** @deprecated используй append_log_includes({ entryPath, includePaths }) */
207
230
  async appendLogIncludes(entryPath, includePaths = [], params = {}) {
208
231
  if (entryPath && typeof entryPath === 'object' && entryPath.entryPath) {