odant-work 1.0.70 → 1.0.72
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 +24 -22
- package/$server/$folder/$class/$structure/ai/system.md +15 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +181 -59
- package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +10 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/{system/$handler/tabs → search/$handler}/search.js +14 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +53 -30
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +33 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-ui.js +5 -5
- package/$server/$folder/lib/chat-item/chat-item.js +44 -1
- package/$server/$folder/lib/tree/tree.js +1 -1
- package/oda/oda.js +8 -4
- package/package.json +1 -1
- package/sources/client.js +42 -6
- package/sources/modules/agent/index.js +24 -5
- package/sources/modules/agent/node-rules.js +146 -1
- package/sources/modules/agent/scheduler.js +8 -0
- package/sources/modules/agent/triggers.js +64 -0
- package/sources/modules/agent/twin-bus.js +77 -1
- package/sources/server/access/gateway.js +1 -1
- package/sources/server/chat-threads.js +90 -26
- package/sources/server/class/feed.js +19 -13
- package/sources/server/logs.js +15 -11
|
@@ -94,7 +94,11 @@ export async function listNodeRules(storage, params = {}) {
|
|
|
94
94
|
}
|
|
95
95
|
const nodePath = storage?.path || '/';
|
|
96
96
|
const schedules = await listSchedules({ nodePath }).catch(() => []);
|
|
97
|
-
|
|
97
|
+
const proactivity = {
|
|
98
|
+
autoReply: storage?.DATA?.proactivity?.autoReply !== false,
|
|
99
|
+
quietDigest: storage?.DATA?.proactivity?.quietDigest !== false,
|
|
100
|
+
};
|
|
101
|
+
return { triggers, schedules, proactivity };
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
export async function saveNodeRule(storage, params = {}) {
|
|
@@ -169,3 +173,144 @@ export async function saveNodeSchedule(storage, params = {}) {
|
|
|
169
173
|
tz: post.tz,
|
|
170
174
|
});
|
|
171
175
|
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Сохранить базовые настройки проактивности узла (`autoReply`, `quietDigest`) в class.js.
|
|
179
|
+
*/
|
|
180
|
+
export async function saveNodeProactivity(storage, params = {}) {
|
|
181
|
+
await assertBoss(storage, params);
|
|
182
|
+
const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
|
|
183
|
+
const prev = storage?.DATA?.proactivity && typeof storage.DATA.proactivity === 'object' ? storage.DATA.proactivity : {};
|
|
184
|
+
const next = {
|
|
185
|
+
...prev,
|
|
186
|
+
...(typeof post.autoReply === 'boolean' ? { autoReply: post.autoReply } : {}),
|
|
187
|
+
...(typeof post.quietDigest === 'boolean' ? { quietDigest: post.quietDigest } : {}),
|
|
188
|
+
};
|
|
189
|
+
if (typeof storage?.save === 'function') {
|
|
190
|
+
await storage.save({ proactivity: next }, params);
|
|
191
|
+
}
|
|
192
|
+
else if (storage?.DATA) {
|
|
193
|
+
storage.DATA.proactivity = next;
|
|
194
|
+
}
|
|
195
|
+
return { ok: true, proactivity: next };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Собрать реальные заметные события узла для тихой сводки руководителю (0 событий => пустой список).
|
|
200
|
+
*/
|
|
201
|
+
export async function collectQuietDigest(storage) {
|
|
202
|
+
if (!storage)
|
|
203
|
+
return { events: [], nodePath: '/' };
|
|
204
|
+
const nodePath = String(storage.path || '/').replace(/\/+$/, '') || '/';
|
|
205
|
+
const events = [];
|
|
206
|
+
try {
|
|
207
|
+
const { dbForThreadStorage } = await import('../../server/chat-threads.js');
|
|
208
|
+
const db = await dbForThreadStorage(storage, 'twin');
|
|
209
|
+
const now = Date.now();
|
|
210
|
+
const hourAgo = now - 3600_000;
|
|
211
|
+
const min15Ago = now - 15 * 60_000;
|
|
212
|
+
|
|
213
|
+
// 1. Ожидающие утверждения карточки (старше 1 часа)
|
|
214
|
+
const pendingApprovals = db.prepare(`
|
|
215
|
+
SELECT m.id, m.content, m.created
|
|
216
|
+
FROM chat_messages m
|
|
217
|
+
JOIN chat_threads t ON t.id = m.thread_id
|
|
218
|
+
WHERE t.kind = 'twin' AND t.node_path = ? AND m.kind = 'approval' AND m.created <= ?
|
|
219
|
+
AND (m.meta LIKE '%"status":"pending"%' OR m.meta LIKE '%"status": "pending"%')
|
|
220
|
+
ORDER BY m.created DESC LIMIT 5
|
|
221
|
+
`).all(nodePath, hourAgo);
|
|
222
|
+
for (const a of pendingApprovals) {
|
|
223
|
+
events.push(`Ожидает решения: «${String(a.content || '').slice(0, 90)}»`);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 2. Неотвеченные текстовые обращения пользователей/клиентов в twin-диалогах этого узла (без .task-карточек, за последние 3 дня)
|
|
227
|
+
const threeDaysAgo = now - 3 * 86400_000;
|
|
228
|
+
const threads = db.prepare(`
|
|
229
|
+
SELECT id FROM chat_threads WHERE kind = 'twin' AND node_path = ?
|
|
230
|
+
`).all(nodePath);
|
|
231
|
+
let unansweredCount = 0;
|
|
232
|
+
for (const t of threads) {
|
|
233
|
+
const lastMsg = db.prepare('SELECT sender, kind, task_path, created FROM chat_messages WHERE thread_id = ? ORDER BY id DESC LIMIT 1').get(t.id);
|
|
234
|
+
if (lastMsg
|
|
235
|
+
&& lastMsg.sender !== '$twin'
|
|
236
|
+
&& lastMsg.kind === 'text'
|
|
237
|
+
&& !lastMsg.task_path
|
|
238
|
+
&& Number(lastMsg.created) <= min15Ago
|
|
239
|
+
&& Number(lastMsg.created) >= threeDaysAgo)
|
|
240
|
+
unansweredCount++;
|
|
241
|
+
}
|
|
242
|
+
if (unansweredCount > 0)
|
|
243
|
+
events.push(`Неотвеченных обращений в диалогах узла: ${unansweredCount}`);
|
|
244
|
+
}
|
|
245
|
+
catch { /* ignore */ }
|
|
246
|
+
|
|
247
|
+
try {
|
|
248
|
+
const schedules = await listSchedules({ nodePath }).catch(() => []);
|
|
249
|
+
const failed = schedules.filter(s => s.lastError);
|
|
250
|
+
if (failed.length)
|
|
251
|
+
events.push(`Ошибки расписания (${failed.length}): ${failed[0].label} — ${String(failed[0].lastError).slice(0, 80)}`);
|
|
252
|
+
}
|
|
253
|
+
catch { /* ignore */ }
|
|
254
|
+
|
|
255
|
+
return { nodePath, events };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const lastDigestDayByNode = new Map();
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Проверить узлы $base/$project/$structure и отправить тихую сводку BOSS только при наличии реальных событий.
|
|
262
|
+
*/
|
|
263
|
+
export async function runQuietDigests({ now = Date.now(), nodes = null } = {}) {
|
|
264
|
+
const WORK = globalThis.WORK;
|
|
265
|
+
if (!WORK && !Array.isArray(nodes))
|
|
266
|
+
return [];
|
|
267
|
+
const dayKey = new Date(now).toISOString().slice(0, 10);
|
|
268
|
+
const list = Array.isArray(nodes) ? nodes : [];
|
|
269
|
+
if (!list.length && WORK) {
|
|
270
|
+
const collectTargets = async (containerPath) => {
|
|
271
|
+
const c = await WORK.get_item(containerPath).catch(() => null);
|
|
272
|
+
const items = (await c?.items) || [];
|
|
273
|
+
for (const base of items) {
|
|
274
|
+
if (!base || base.id?.[0] === '$') continue;
|
|
275
|
+
list.push(base);
|
|
276
|
+
const sub = (await base.items) || [];
|
|
277
|
+
for (const child of sub) {
|
|
278
|
+
if (child && child.type === '$structure' && child.id?.[0] !== '$')
|
|
279
|
+
list.push(child);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
await collectTargets('/ORGANIZATIONS');
|
|
284
|
+
await collectTargets('/PROJECTS');
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const sent = [];
|
|
288
|
+
for (const nodeItem of list) {
|
|
289
|
+
if (!nodeItem || nodeItem.DATA?.proactivity?.quietDigest === false)
|
|
290
|
+
continue;
|
|
291
|
+
const nodePath = String(nodeItem.path || '/').replace(/\/+$/, '') || '/';
|
|
292
|
+
if (lastDigestDayByNode.get(nodePath) === dayKey)
|
|
293
|
+
continue;
|
|
294
|
+
const { events } = await collectQuietDigest(nodeItem);
|
|
295
|
+
if (!events.length)
|
|
296
|
+
continue;
|
|
297
|
+
const bosses = await Promise.resolve(nodeItem.bosses).catch(() => []);
|
|
298
|
+
const topBosses = bosses?.length ? bosses : (await Promise.resolve(nodeItem.allBosses).catch(() => []));
|
|
299
|
+
const bossUid = topBosses?.[0]?.id || topBosses?.at?.(-1)?.id;
|
|
300
|
+
if (!bossUid)
|
|
301
|
+
continue;
|
|
302
|
+
const label = nodeItem.DATA?.label || nodeItem.label || nodeItem.id || nodePath;
|
|
303
|
+
const msg = `Сводка узла «${label}» (${dayKey}):\n` + events.map(e => `• ${e}`).join('\n');
|
|
304
|
+
const CHAT = await import('../../server/chat-threads.js');
|
|
305
|
+
await CHAT.sendMessage(nodeItem, {
|
|
306
|
+
uid: bossUid,
|
|
307
|
+
asTwin: true,
|
|
308
|
+
kind: 'text',
|
|
309
|
+
message: msg,
|
|
310
|
+
meta: { digestDay: dayKey },
|
|
311
|
+
}).catch(() => {});
|
|
312
|
+
lastDigestDayByNode.set(nodePath, dayKey);
|
|
313
|
+
sent.push({ nodePath, bossUid, eventsCount: events.length });
|
|
314
|
+
}
|
|
315
|
+
return sent;
|
|
316
|
+
}
|
|
@@ -346,6 +346,8 @@ export async function cancelSchedule({ uid, id }) {
|
|
|
346
346
|
return true;
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
+
let lastQuietDigestAt = 0;
|
|
350
|
+
|
|
349
351
|
/** Выполнить наступившие запуски (вызывается таймером; тесты — напрямую). */
|
|
350
352
|
export async function runDue(now = Date.now(), runner = defaultRunner) {
|
|
351
353
|
const d = await indexDb();
|
|
@@ -369,6 +371,12 @@ export async function runDue(now = Date.now(), runner = defaultRunner) {
|
|
|
369
371
|
.run(now, error, next, next && !fatal ? 1 : 0, r.id);
|
|
370
372
|
done.push({ id: r.id, error });
|
|
371
373
|
}
|
|
374
|
+
if (runner === defaultRunner && now - lastQuietDigestAt >= 15 * 60_000) {
|
|
375
|
+
lastQuietDigestAt = now;
|
|
376
|
+
import('./node-rules.js')
|
|
377
|
+
.then(m => m.runQuietDigests?.({ now }))
|
|
378
|
+
.catch(() => {});
|
|
379
|
+
}
|
|
372
380
|
return done;
|
|
373
381
|
}
|
|
374
382
|
|
|
@@ -471,6 +471,70 @@ export async function onChatEvent({ storage, thread, message, params = {} } = {}
|
|
|
471
471
|
});
|
|
472
472
|
n++;
|
|
473
473
|
}
|
|
474
|
+
|
|
475
|
+
// Базовая субъектная реакция узла $structure на прямое сообщение (без .task),
|
|
476
|
+
// если нет явного правила chat:message и включён autoReply (в т.ч. обращения сотрудников/клиентов).
|
|
477
|
+
const STRUCT_TYPES = new Set(['$server', '$base', '$project', '$structure']);
|
|
478
|
+
const text = String(message.content || '').trim();
|
|
479
|
+
const allowDefaultReply = n === 0
|
|
480
|
+
&& !message.taskPath
|
|
481
|
+
&& text.length > 0
|
|
482
|
+
&& STRUCT_TYPES.has(storage.type)
|
|
483
|
+
&& storage.DATA?.proactivity?.autoReply !== false
|
|
484
|
+
&& !globalThis.__workDisableDefaultTwinReply
|
|
485
|
+
&& (Boolean(runner || globalThis.__workDefaultTwinRunner) || (!process.env.NODE_TEST_CONTEXT && process.env.NODE_ENV !== 'test'));
|
|
486
|
+
|
|
487
|
+
if (allowDefaultReply) {
|
|
488
|
+
const defKey = `default-chat:${thread.id}`;
|
|
489
|
+
if (allowedCooldown(defKey, 2000) && allowedRun(defKey, 30)) {
|
|
490
|
+
const execDefault = runner || globalThis.__workDefaultTwinRunner || (async o => (await import('./index.js')).runOnce(o));
|
|
491
|
+
const senderUid = message.sender || '';
|
|
492
|
+
const replyPromise = (async () => {
|
|
493
|
+
try {
|
|
494
|
+
let callerSession = params?.session;
|
|
495
|
+
if (!callerSession && senderUid && senderUid !== '$twin') {
|
|
496
|
+
callerSession = await sessionFor(senderUid, 'twin-chat').catch(() => null);
|
|
497
|
+
}
|
|
498
|
+
if (!callerSession)
|
|
499
|
+
return;
|
|
500
|
+
if (!runner && !globalThis.__workDefaultTwinRunner) {
|
|
501
|
+
const { createEnv } = await import('./index.js');
|
|
502
|
+
const env = await createEnv({ place: storage, session: callerSession });
|
|
503
|
+
const modelPath = await env.defaultModel().catch(() => '');
|
|
504
|
+
const modelItem = modelPath ? await WORK.get_item(modelPath).catch(() => null) : null;
|
|
505
|
+
if (!modelItem || modelItem.DATA?.aiActive === false)
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const res = await execDefault({
|
|
509
|
+
place: storage,
|
|
510
|
+
session: callerSession,
|
|
511
|
+
prompt: text,
|
|
512
|
+
mode: 'ask',
|
|
513
|
+
signal: AbortSignal.timeout(4 * 60_000),
|
|
514
|
+
});
|
|
515
|
+
const answer = String(res?.content || '').trim();
|
|
516
|
+
if (!answer)
|
|
517
|
+
return;
|
|
518
|
+
const CHAT = await import('../../server/chat-threads.js');
|
|
519
|
+
await CHAT.sendMessage(storage, {
|
|
520
|
+
uid: senderUid || storage.constructor?.resolveUid?.(params) || '',
|
|
521
|
+
threadId: thread.id,
|
|
522
|
+
asTwin: true,
|
|
523
|
+
kind: 'text',
|
|
524
|
+
message: answer,
|
|
525
|
+
meta: { autoReply: true },
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
catch (e) { console.warn('[trigger:autoReply]', e?.message || e); }
|
|
529
|
+
})();
|
|
530
|
+
globalThis.__workPendingTriggers = (globalThis.__workPendingTriggers || 0) + 1;
|
|
531
|
+
replyPromise.finally(() => {
|
|
532
|
+
globalThis.__workPendingTriggers = Math.max(0, (globalThis.__workPendingTriggers || 1) - 1);
|
|
533
|
+
});
|
|
534
|
+
n++;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
474
538
|
pump();
|
|
475
539
|
return n;
|
|
476
540
|
}
|
|
@@ -160,4 +160,80 @@ export const twinAskTool = {
|
|
|
160
160
|
},
|
|
161
161
|
};
|
|
162
162
|
|
|
163
|
-
export const
|
|
163
|
+
export const twinRuleListTool = {
|
|
164
|
+
name: 'twin_rule_list',
|
|
165
|
+
description: 'Показать активные правила проактивности, настройки автоответа/сводки и расписания текущего структурного узла (только BOSS).',
|
|
166
|
+
readonly: true,
|
|
167
|
+
parameters: {
|
|
168
|
+
type: 'object',
|
|
169
|
+
properties: {},
|
|
170
|
+
},
|
|
171
|
+
async run(_args, ctx) {
|
|
172
|
+
if (!ctx?.session || ctx.session.twinCall)
|
|
173
|
+
throw new Error('twin_rule_list: недоступно в Service Plane');
|
|
174
|
+
const place = ctx.place || globalThis.WORK;
|
|
175
|
+
const { listNodeRules } = await import('./node-rules.js');
|
|
176
|
+
return listNodeRules(place, { session: ctx.session });
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export const twinRuleSaveTool = {
|
|
181
|
+
name: 'twin_rule_save',
|
|
182
|
+
description: 'Создать, обновить или удалить правило проактивности текущего узла ($structure/ai/triggers/*.md). Требует полномочий BOSS; перед сохранением в диалоге согласуй правило с руководителем.',
|
|
183
|
+
risk: 'write',
|
|
184
|
+
parameters: {
|
|
185
|
+
type: 'object',
|
|
186
|
+
properties: {
|
|
187
|
+
name: { type: 'string', description: 'Имя правила (латиница/цифры/_/-)' },
|
|
188
|
+
on: { type: 'string', description: 'Событие: db:register | db:create | db:update | chat:message | save' },
|
|
189
|
+
class: { type: 'string', description: 'WORK-путь отслеживаемого класса (необязательно)' },
|
|
190
|
+
ext: { type: 'string', description: 'Расширения файлов для save (например: pdf, eml)' },
|
|
191
|
+
when: { type: 'string', description: 'Предикат условия (например: sum > 100000)' },
|
|
192
|
+
template: { type: 'string', description: 'Быстрый шаблон уведомления без вызова LLM (необязательно)' },
|
|
193
|
+
approval: { type: 'boolean', description: 'Показывать карточку с кнопками Утвердить / Отклонить' },
|
|
194
|
+
cooldownSec: { type: 'number', description: 'Пауза между срабатываниями на один объект (сек)' },
|
|
195
|
+
enabled: { type: 'boolean', description: 'Включено ли правило' },
|
|
196
|
+
body: { type: 'string', description: 'Инструкция для двойника при срабатывании (если не задан template)' },
|
|
197
|
+
delete: { type: 'boolean', description: 'true — удалить правило с этим именем' },
|
|
198
|
+
},
|
|
199
|
+
required: ['name'],
|
|
200
|
+
},
|
|
201
|
+
async run(args, ctx) {
|
|
202
|
+
if (!ctx?.session || ctx.session.twinCall)
|
|
203
|
+
throw new Error('twin_rule_save: недоступно в Service Plane');
|
|
204
|
+
const place = ctx.place || globalThis.WORK;
|
|
205
|
+
const { saveNodeRule } = await import('./node-rules.js');
|
|
206
|
+
return saveNodeRule(place, { session: ctx.session, post: args });
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
export const twinScheduleSaveTool = {
|
|
211
|
+
name: 'twin_schedule_save',
|
|
212
|
+
description: 'Создать, переключить или удалить регулярное расписание задач текущего структурного узла (только BOSS).',
|
|
213
|
+
risk: 'write',
|
|
214
|
+
parameters: {
|
|
215
|
+
type: 'object',
|
|
216
|
+
properties: {
|
|
217
|
+
id: { type: 'string', description: 'ID расписания (для toggle или delete)' },
|
|
218
|
+
label: { type: 'string', description: 'Название регулярной обязанности' },
|
|
219
|
+
prompt: { type: 'string', description: 'Что именно должен проверять/делать двойник по расписанию' },
|
|
220
|
+
rule: {
|
|
221
|
+
type: 'object',
|
|
222
|
+
description: 'Правило времени: { kind: "daily"|"weekly"|"every"|"once", at?: "09:00", days?: [1,2,3,4,5], minutes?: 60 }',
|
|
223
|
+
},
|
|
224
|
+
tz: { type: 'string', description: 'Часовой пояс, например Europe/Moscow' },
|
|
225
|
+
toggle: { type: 'boolean', description: 'Переключить enabled для id' },
|
|
226
|
+
enabled: { type: 'boolean' },
|
|
227
|
+
delete: { type: 'boolean', description: 'Удалить расписание по id' },
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
async run(args, ctx) {
|
|
231
|
+
if (!ctx?.session || ctx.session.twinCall)
|
|
232
|
+
throw new Error('twin_schedule_save: недоступно в Service Plane');
|
|
233
|
+
const place = ctx.place || globalThis.WORK;
|
|
234
|
+
const { saveNodeSchedule } = await import('./node-rules.js');
|
|
235
|
+
return saveNodeSchedule(place, { session: ctx.session, post: args });
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export const twinTools = [twinAskTool, twinRuleListTool, twinRuleSaveTool, twinScheduleSaveTool];
|
|
@@ -42,7 +42,7 @@ export const MEMBERS = Object.freeze({
|
|
|
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
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
|
+
agent_rules_list: L.READ, agent_rule_save: L.ADMIN, agent_schedule_save: L.ADMIN, agent_proactivity_save: L.ADMIN,
|
|
46
46
|
roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
|
|
47
47
|
work_zone: L.READ, places: L.READ,
|
|
48
48
|
data_access: L.READ, link_tree: L.READ, search_tree: L.USER,
|
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
* - kind = 'group' : тематическая группа людей; хранится в БД контекста создания.
|
|
9
9
|
*/
|
|
10
10
|
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
11
13
|
import * as LOGS from './logs.js';
|
|
12
14
|
import * as REFS from './access/refs.js';
|
|
13
15
|
import * as WORKPLACES from './access/workplaces.js';
|
|
14
|
-
import { dataDb, tx } from '../data/db.js';
|
|
16
|
+
import { baseDbFile, dataDb, tx } from '../data/db.js';
|
|
15
17
|
import { DEV_MODE } from '../host/config.js';
|
|
16
18
|
|
|
17
19
|
function notifyChatEvent(uids, payload) {
|
|
@@ -276,9 +278,19 @@ export async function listMessages(storage, params = {}) {
|
|
|
276
278
|
if (!uid)
|
|
277
279
|
throw new Error(ACCESS_DENIED);
|
|
278
280
|
|
|
279
|
-
|
|
280
|
-
if (!threadId)
|
|
281
|
-
|
|
281
|
+
let threadId = String(params.threadId || '').trim();
|
|
282
|
+
if (!threadId) {
|
|
283
|
+
const isDm = storage?.type === '$user' || params.kind === 'dm';
|
|
284
|
+
if (isDm) {
|
|
285
|
+
const peerId = String(params.peerId || (storage?.type === '$user' ? storage.id : '')).trim();
|
|
286
|
+
if (!peerId)
|
|
287
|
+
throw new Error('Не указан threadId или peerId');
|
|
288
|
+
threadId = dmThreadId(uid, peerId);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
threadId = twinThreadId(LOGS.feedPathOf(storage), uid);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
282
294
|
|
|
283
295
|
const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
|
|
284
296
|
const db = await dbForThreadStorage(storage, kindHint);
|
|
@@ -420,6 +432,15 @@ export async function markRead(storage, params = {}) {
|
|
|
420
432
|
if (!part)
|
|
421
433
|
return { ok: false, lastReadId: 0 };
|
|
422
434
|
|
|
435
|
+
const threadRow = db.prepare('SELECT kind, node_path FROM chat_threads WHERE id = ?').get(threadId);
|
|
436
|
+
const kind = threadRow?.kind || kindHint;
|
|
437
|
+
const nodePath = threadRow?.node_path || '';
|
|
438
|
+
let peerId = '';
|
|
439
|
+
if (kind === 'dm' && threadId.startsWith('dm:')) {
|
|
440
|
+
const parts = threadId.slice(3).split('|');
|
|
441
|
+
peerId = parts[0] === uid && parts[1] === uid ? uid : (parts[0] === uid ? parts[1] : parts[0]);
|
|
442
|
+
}
|
|
443
|
+
|
|
423
444
|
const maxRow = db.prepare('SELECT COALESCE(MAX(id), 0) AS max_id FROM chat_messages WHERE thread_id = ?').get(threadId);
|
|
424
445
|
const targetId = params.lastMessageId != null ? Math.min(Number(params.lastMessageId) || 0, Number(maxRow?.max_id) || 0) : (Number(maxRow?.max_id) || 0);
|
|
425
446
|
const nextRead = Math.max(Number(part.last_read_id) || 0, targetId);
|
|
@@ -427,42 +448,85 @@ export async function markRead(storage, params = {}) {
|
|
|
427
448
|
notifyChatEvent([uid], {
|
|
428
449
|
type: 'chat:read',
|
|
429
450
|
threadId,
|
|
451
|
+
kind,
|
|
452
|
+
nodePath,
|
|
453
|
+
peerId,
|
|
430
454
|
uid,
|
|
431
455
|
lastReadId: nextRead,
|
|
432
456
|
});
|
|
433
|
-
return { ok: true, lastReadId: nextRead };
|
|
457
|
+
return { ok: true, lastReadId: nextRead, threadId, kind, nodePath, peerId };
|
|
434
458
|
}
|
|
435
459
|
|
|
436
|
-
/** Сводка непрочитанного для текущего пользователя в БД данного
|
|
460
|
+
/** Сводка непрочитанного для текущего пользователя в БД данного узла/сервера (на $server — включая БД организаций и проектов). */
|
|
437
461
|
export async function unreadSummary(storage, params = {}) {
|
|
438
462
|
const uid = resolveActorUid(storage, params);
|
|
439
463
|
if (!uid)
|
|
440
464
|
return { total: 0, byThread: {}, byNode: {}, byPeer: {} };
|
|
441
|
-
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
465
|
+
|
|
466
|
+
const dbs = [];
|
|
467
|
+
const primaryDb = await dbForThreadStorage(storage, params.kind || '');
|
|
468
|
+
if (primaryDb)
|
|
469
|
+
dbs.push(primaryDb);
|
|
470
|
+
|
|
471
|
+
if (storage?.type === '$server' && !params.kind) {
|
|
472
|
+
const rootDir = rootDirOf();
|
|
473
|
+
for (const container of ['ORGANIZATIONS', 'PROJECTS']) {
|
|
474
|
+
const dir = path.join(rootDir, container);
|
|
475
|
+
if (!fs.existsSync(dir))
|
|
476
|
+
continue;
|
|
477
|
+
try {
|
|
478
|
+
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
479
|
+
if (!ent.isDirectory() || ent.name.startsWith('$'))
|
|
480
|
+
continue;
|
|
481
|
+
const basePath = `/${container}/${ent.name}`;
|
|
482
|
+
const dbFile = baseDbFile(rootDir, basePath);
|
|
483
|
+
if (!fs.existsSync(dbFile))
|
|
484
|
+
continue;
|
|
485
|
+
const baseDb = await dataDb(basePath, rootDir).catch(() => null);
|
|
486
|
+
if (baseDb && !dbs.includes(baseDb))
|
|
487
|
+
dbs.push(baseDb);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
catch { /* ignore unreadable directory */ }
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
449
494
|
const byThread = {};
|
|
450
495
|
const byNode = {};
|
|
451
496
|
const byPeer = {};
|
|
452
497
|
let total = 0;
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
498
|
+
const seenThreads = new Set();
|
|
499
|
+
for (const db of dbs) {
|
|
500
|
+
let rows = [];
|
|
501
|
+
try {
|
|
502
|
+
rows = db.prepare(`
|
|
503
|
+
SELECT t.id, t.kind, t.node_path,
|
|
504
|
+
(SELECT COUNT(*) FROM chat_messages m WHERE m.thread_id = t.id AND m.id > p.last_read_id AND m.sender != ?) AS unread
|
|
505
|
+
FROM chat_threads t
|
|
506
|
+
JOIN chat_participants p ON p.thread_id = t.id
|
|
507
|
+
WHERE p.uid = ?
|
|
508
|
+
`).all(uid, uid);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
rows = [];
|
|
460
512
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
513
|
+
for (const r of rows) {
|
|
514
|
+
if (seenThreads.has(r.id))
|
|
515
|
+
continue;
|
|
516
|
+
seenThreads.add(r.id);
|
|
517
|
+
const cnt = Number(r.unread) || 0;
|
|
518
|
+
if (!cnt) continue;
|
|
519
|
+
total += cnt;
|
|
520
|
+
byThread[r.id] = cnt;
|
|
521
|
+
if (r.kind === 'twin' && r.node_path) {
|
|
522
|
+
byNode[r.node_path] = (byNode[r.node_path] || 0) + cnt;
|
|
523
|
+
}
|
|
524
|
+
else if (r.kind === 'dm') {
|
|
525
|
+
const parts = String(r.id).slice(3).split('|');
|
|
526
|
+
const peer = parts[0] === uid && parts[1] === uid ? uid : (parts[0] === uid ? parts[1] : parts[0]);
|
|
527
|
+
if (peer)
|
|
528
|
+
byPeer[peer] = (byPeer[peer] || 0) + cnt;
|
|
529
|
+
}
|
|
466
530
|
}
|
|
467
531
|
}
|
|
468
532
|
return { total, byThread, byNode, byPeer };
|
|
@@ -25,20 +25,11 @@ export const classFeedMethods = {
|
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
27
|
* Источник логов чата для пользователя.
|
|
28
|
-
*
|
|
29
|
-
*
|
|
28
|
+
* Каждый узел ($server, $base, $project, $structure, $user) хранит и показывает свою собственную ленту,
|
|
29
|
+
* без подмены на /USERS/<uid>.
|
|
30
30
|
*/
|
|
31
31
|
async chatSource(params = {}) {
|
|
32
|
-
|
|
33
|
-
return this.path;
|
|
34
|
-
const uid = this.constructor.resolveUid(params) || (typeof params.uid === 'string' && params.uid ? params.uid : null);
|
|
35
|
-
const own = params.session?.principal?.kind === 'node'
|
|
36
|
-
? params.session.$user?.path
|
|
37
|
-
: (uid ? '/USERS//' + uid : null);
|
|
38
|
-
const wantLocal = params.local === true || params.local === '1' || params.local === 'true' || params.feedMode === 'local';
|
|
39
|
-
if (wantLocal && await this._canViewLocalFeed(params))
|
|
40
|
-
return this.path;
|
|
41
|
-
return own || this.path;
|
|
32
|
+
return this.path;
|
|
42
33
|
},
|
|
43
34
|
|
|
44
35
|
/** Элемент-источник логов для текущей роли (this или $user). */
|
|
@@ -226,6 +217,12 @@ export const classFeedMethods = {
|
|
|
226
217
|
return saveNodeSchedule(this, params);
|
|
227
218
|
},
|
|
228
219
|
|
|
220
|
+
/** Сохранить настройки проактивности узла (autoReply, quietDigest, только BOSS). */
|
|
221
|
+
async agent_proactivity_save(params = {}) {
|
|
222
|
+
const { saveNodeProactivity } = await import('../../modules/agent/node-rules.js');
|
|
223
|
+
return saveNodeProactivity(this, params);
|
|
224
|
+
},
|
|
225
|
+
|
|
229
226
|
/** @deprecated используй append_log_includes({ entryPath, includePaths }) */
|
|
230
227
|
async appendLogIncludes(entryPath, includePaths = [], params = {}) {
|
|
231
228
|
if (entryPath && typeof entryPath === 'object' && entryPath.entryPath) {
|
|
@@ -278,7 +275,16 @@ export const classFeedMethods = {
|
|
|
278
275
|
/** uid, если вызывающему видна только своя часть ленты точки, иначе null. */
|
|
279
276
|
async _feedOwnOnly(params = {}) {
|
|
280
277
|
const uid = this.constructor.resolveUid(params) || (typeof params?.uid === 'string' && params.uid ? params.uid : null);
|
|
281
|
-
if (
|
|
278
|
+
if (this.type === '$user') {
|
|
279
|
+
// На своём профиле — вся личная лента; на чужом $user — только общие записи с собой (приватность)
|
|
280
|
+
if (!uid || this.id === uid)
|
|
281
|
+
return null;
|
|
282
|
+
return uid;
|
|
283
|
+
}
|
|
284
|
+
const wantDialog = params?.feedMode === 'dialog' || params?.ownOnly === true || params?.ownOnly === 1 || params?.ownOnly === '1';
|
|
285
|
+
if (wantDialog && uid)
|
|
286
|
+
return uid;
|
|
287
|
+
if (!uid || this.id === uid)
|
|
282
288
|
return null;
|
|
283
289
|
if (params?.role) {
|
|
284
290
|
return params.role === 'BOSS' ? null : uid;
|
package/sources/server/logs.js
CHANGED
|
@@ -589,19 +589,23 @@ export async function appendRow(storage, row, params = {}) {
|
|
|
589
589
|
if (primaryRes?.logsFilePath)
|
|
590
590
|
row.logsFilePath = primaryRes.logsFilePath;
|
|
591
591
|
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
if (
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
592
|
+
// Записи подразделений и организаций не сваливаются в личный кабинет /USERS/<uid>;
|
|
593
|
+
// зеркалирование в личный кабинет автора делается только при явном mirrorToAuthor === true.
|
|
594
|
+
if (params.mirrorToAuthor === true) {
|
|
595
|
+
let authorCabinet = params.logAuthor?.$user ?? params.session?.$user;
|
|
596
|
+
const senderUid = row.sender || params.session?.uid || params.uid;
|
|
597
|
+
if ((!authorCabinet || authorCabinet === globalThis.WORK) && senderUid && senderUid !== 'system' && senderUid !== 'WORK' && senderUid !== globalThis.WORK?.id) {
|
|
598
|
+
try {
|
|
599
|
+
const usersList = await globalThis.WORK?.$users;
|
|
600
|
+
if (usersList)
|
|
601
|
+
authorCabinet = await usersList.get_item('//' + senderUid);
|
|
602
|
+
}
|
|
603
|
+
catch { /* ignore */ }
|
|
599
604
|
}
|
|
600
|
-
|
|
605
|
+
if (authorCabinet && authorCabinet !== globalThis.WORK
|
|
606
|
+
&& logClassKey(authorCabinet) !== logClassKey(storage))
|
|
607
|
+
await writeLogTo(authorCabinet, log_param, written, row);
|
|
601
608
|
}
|
|
602
|
-
if (authorCabinet && authorCabinet !== globalThis.WORK
|
|
603
|
-
&& logClassKey(authorCabinet) !== logClassKey(storage))
|
|
604
|
-
await writeLogTo(authorCabinet, log_param, written, row);
|
|
605
609
|
|
|
606
610
|
let receivers = row.receivers;
|
|
607
611
|
if (typeof receivers === 'string')
|