odant-work 1.0.70 → 1.0.71
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 +17 -16
- package/$server/$folder/$class/$structure/ai/system.md +15 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +136 -42
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +33 -0
- package/$server/$folder/lib/chat-item/chat-item.js +44 -1
- package/package.json +1 -1
- package/sources/modules/agent/index.js +24 -5
- package/sources/modules/agent/node-rules.js +140 -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 +13 -3
- package/sources/server/class/feed.js +19 -13
- package/sources/server/logs.js +15 -11
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"packageName": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.71",
|
|
4
4
|
"createdAt": 1795100682741,
|
|
5
|
-
"updatedAt":
|
|
5
|
+
"updatedAt": 1795534793809,
|
|
6
6
|
"files": {
|
|
7
7
|
"run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
|
|
8
|
-
"package.json": "
|
|
9
|
-
"package-lock.json": "
|
|
8
|
+
"package.json": "68eedf956ea2de052426ab6b1c45f8cd74b4f23308c41f358ab3f954c20c95d7",
|
|
9
|
+
"package-lock.json": "1b41e502e3b8881d282b16182ec5c98301d71ad755b32e21735b13206c4a331d",
|
|
10
10
|
"sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
|
|
11
11
|
"sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
|
|
12
12
|
"sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
|
|
@@ -66,17 +66,17 @@
|
|
|
66
66
|
"sources/modules/agent/eval.js": "91f907554630ad53c30d5c1d760bb646bb4dbd10ec854a69453d002368ce25cc",
|
|
67
67
|
"sources/modules/agent/extensions.js": "b2fb033a1ffe7bd99b5f385ec3c81af8dd8265dd27e5a5c51282d9c137d34bb4",
|
|
68
68
|
"sources/modules/agent/hooks.js": "b74e9d8f4b491b6d16d979891de69941955e50852289f55589c82997405c9048",
|
|
69
|
-
"sources/modules/agent/index.js": "
|
|
69
|
+
"sources/modules/agent/index.js": "a9edd6cc76b4c3ce3a45f1934b1cfec95616c66b821dd77f57130d1ab3d22424",
|
|
70
70
|
"sources/modules/agent/log.js": "03ae1979e2b00459178deda49847c30ed75937fc4f3eea9b778ca6c0f8c4ded0",
|
|
71
71
|
"sources/modules/agent/loop.js": "c7e732fba6d180f1728c927d542901be064e950899541f18575c9e9eb6365a97",
|
|
72
72
|
"sources/modules/agent/mcp-pool.js": "aa4e75e2fcfe07883f9b721b33cee642fbbe11b8f416f8cd6a81f9c1ab39edde",
|
|
73
|
-
"sources/modules/agent/node-rules.js": "
|
|
73
|
+
"sources/modules/agent/node-rules.js": "210419fc415c5d1b1eb547631b9b49247155588a5766a6a6a42c2818c488b73c",
|
|
74
74
|
"sources/modules/agent/permissions.js": "f4c0fd43fe04e778f0f3aa730a597578541bdb770227e58bfdc1de531dd2f263",
|
|
75
75
|
"sources/modules/agent/plugins.js": "9aed13c2d7bbf66dcd165f23b3969874561aea470dc16dac1435d183696cfda5",
|
|
76
76
|
"sources/modules/agent/readme.md": "c8d461218b8b552be58697f154c5bc4dba9858e6387aff6acfbc794c1286b89d",
|
|
77
77
|
"sources/modules/agent/recovery.js": "7a61dfdb2aef10b5049aee85d579379fdf98af3524f8509428ebc5a613bad92d",
|
|
78
78
|
"sources/modules/agent/resources.js": "d3f90b020694f9febe5a42be46131fbb56b8a6ed1bf476861e4daa9deee45daf",
|
|
79
|
-
"sources/modules/agent/scheduler.js": "
|
|
79
|
+
"sources/modules/agent/scheduler.js": "42a3b96f36e0fe98742d80cc938fc392b304ae3e698646b926ef9b6244ad8f2f",
|
|
80
80
|
"sources/modules/agent/session.js": "b972f93adecd2d669ec80ba6027db9638b225baa5e2fc3d75f11c77906b99b09",
|
|
81
81
|
"sources/modules/agent/system.js": "64fc3d1c235312608a9fd624a9e8878c68d7a68af8b27574a4e8feb2bd8e9ee8",
|
|
82
82
|
"sources/modules/agent/taint.js": "bf6aee5cc7e8b15ac365525fa74645d4a92da5ce1bdbcdba012e80767b5c7063",
|
|
@@ -109,8 +109,8 @@
|
|
|
109
109
|
"sources/modules/agent/tools/work/feed.js": "727dcc044dc9e5fc999acc02eeb0b08a23e827c391e92eeb1a066f9191305991",
|
|
110
110
|
"sources/modules/agent/tools/work/fs.js": "ac59a421f5cb22d284a886256e240464c6d7dc284aec42f5194911c44202f47c",
|
|
111
111
|
"sources/modules/agent/tools/work.js": "59e5542fc1245a200ed8c119473344dbba58b6569dd27c2ee333e98380c58a74",
|
|
112
|
-
"sources/modules/agent/triggers.js": "
|
|
113
|
-
"sources/modules/agent/twin-bus.js": "
|
|
112
|
+
"sources/modules/agent/triggers.js": "3e00f44c817f5bffdc37fe135edeb45ec07df49165e5ed9b80bc04064015e0df",
|
|
113
|
+
"sources/modules/agent/twin-bus.js": "c8794edbd83f429f3452571e2bfc87e003c534b774dcdb8b20edc2eaac8e40e1",
|
|
114
114
|
"sources/modules/agent/types.d.ts": "9d47168bb9fefb1d7c5506afb263c6a6f2e3609602ee78e50c98c02bc052831f",
|
|
115
115
|
"sources/modules/agent/undo.js": "e46f3f1172c6d6e4055332bada74c546c0b0a0e585f1c96eac9b40e4d35b8544",
|
|
116
116
|
"sources/modules/agent/util.js": "9bca6569c16cdfed0134dfec0c99347b3e999692afdc35719886f6083fed87c5",
|
|
@@ -198,7 +198,7 @@
|
|
|
198
198
|
"sources/reactor.js": "fa132f59bac51e0d7b05a109b83100046eacddfc84576bef6115c2605b57ebf6",
|
|
199
199
|
"sources/readme.md": "045fa4d63779731d4c535deefa7bfb2956b021ab25a4d86b8dc41d6f964386f2",
|
|
200
200
|
"sources/server/access/audit.js": "b3e2cf891faf4ce97f7e8eb96a8482727ed1ad25d0ed5d6cc4e30eb922917952",
|
|
201
|
-
"sources/server/access/gateway.js": "
|
|
201
|
+
"sources/server/access/gateway.js": "cf729f16b0d040b1516131c8b755ce022d019f5476619982d49645a7becf73f7",
|
|
202
202
|
"sources/server/access/index.js": "c98fd2acc4164e299334ab865a12a07218a81c6197e1021eecb155f0096688b7",
|
|
203
203
|
"sources/server/access/invites.js": "0a500a191eb58c575e31b5d594059aedf8abcf189ba8b36f600564c19f9127aa",
|
|
204
204
|
"sources/server/access/links.js": "b82389378144cd815c1c1b307ffbc649217d1bf13736ef4fe8d0dfd5ee369419",
|
|
@@ -206,11 +206,11 @@
|
|
|
206
206
|
"sources/server/access/refs.js": "76709c0cc283ba07dd36ee586aae3667023d4bab3416fa8844f2fc0a48b83449",
|
|
207
207
|
"sources/server/access/workplaces.js": "a33084561e685e166cfe1f53d4c93e2270926460f27120c6b43ad0b05b3b0344",
|
|
208
208
|
"sources/server/assert-class-id.js": "92b76c399487e54f935bc470ebbe61ef7897d7f79d4e6234fe42294e35d705d4",
|
|
209
|
-
"sources/server/chat-threads.js": "
|
|
209
|
+
"sources/server/chat-threads.js": "7a68fd671fc9ce5296603df7c9d30a7b49c25a1147d44c8e02938f7634c137e9",
|
|
210
210
|
"sources/server/class/archive.js": "e5321bc4d8c8162963ee29acc96baebd796e9f982c136501b03a0e6ae8b160c8",
|
|
211
211
|
"sources/server/class/base-template.js": "c4d55a988351184b11cc26c0a5f265699b54fd91d93c3a4a7c659c08ef7b7f24",
|
|
212
212
|
"sources/server/class/distro.js": "5380c34bc246156e650036d367373ebfcbc49de101e2da13f22b063346f46c40",
|
|
213
|
-
"sources/server/class/feed.js": "
|
|
213
|
+
"sources/server/class/feed.js": "48fa68acbd71a1f3062fdd04179fd54fb87b30e08e4554325f49a20b7ec635e2",
|
|
214
214
|
"sources/server/class/scaffold.js": "d51620bf7747ae73cb56a41338caf4b4ef0b94229a0f0157ca27a27392105c2f",
|
|
215
215
|
"sources/server/class/script.js": "146ef61b5a55201c34f80de4bbfcb116922f03348773548c041bdba0e53aba64",
|
|
216
216
|
"sources/server/class/search.js": "63bf696ba049ba0b1cd6e4e40fdfe6e84c92b3a9a778369892ed3457d67e839c",
|
|
@@ -221,7 +221,7 @@
|
|
|
221
221
|
"sources/server/folder.js": "67f0d049f55ccc7d83d817d5c7de9b7395604c1e9b32038a4358c0118fbf4f9f",
|
|
222
222
|
"sources/server/handler.js": "ae40082616e3f00f49d40884bc116a8fb6cb56625ec968fef552694bf1ec41a6",
|
|
223
223
|
"sources/server/index.js": "d2af9533f9bacdc6fb6c98412cc1e857f0750cca4c0a0560185c6f746f3d0c51",
|
|
224
|
-
"sources/server/logs.js": "
|
|
224
|
+
"sources/server/logs.js": "5dc22eaebb004c648aa2891205857af6be3a69996e64c7a986806f7697f5f15e",
|
|
225
225
|
"sources/server/memory-mark.js": "0db217ffd58d8212d8ad8d53ed90bf3c95c105586273fdfebf1dc27b6e99ab6c",
|
|
226
226
|
"sources/server/node.js": "c1aba780ddaa077ffcd63cd3387d1a5b96d67396651badfd39c5e65382f3a94d",
|
|
227
227
|
"sources/server/readme.md": "171ab173184008c748d8062f2473e8630b53ebc6a76b220a2547d5ae8bbd4999",
|
|
@@ -592,6 +592,7 @@
|
|
|
592
592
|
"$server/$folder/$class/$structure/$server/handlers/methods/distro/$handler/class.js": "693ed9c3dfe856a24dbd0b4f72b19783c5a88e39a5112e4e526602ec0e7bcb45",
|
|
593
593
|
"$server/$folder/$class/$structure/$server/handlers/pages/site/$handler/site.js": "28a2c7650371941dde1e919bfb2813f189f3a96ebce4bfaa5baa9c8aebeffcf8",
|
|
594
594
|
"$server/$folder/$class/$structure/$user/class.js": "1f28163607fee98227f283d0d7589f3c11d6b53c285a9d8c9511f54594007fdb",
|
|
595
|
+
"$server/$folder/$class/$structure/ai/system.md": "2a5e6f166d7d6081bc090e6ad64440815b199e5c52d49dda1b68868fbf6823a4",
|
|
595
596
|
"$server/$folder/$class/$structure/class.js": "c6c7cf786d2fc60673ade3d4606fef904d48fde270d625574f626897a8a2c9a7",
|
|
596
597
|
"$server/$folder/$class/$structure/handlers/methods/archive/$handler/class.js": "cbbe4b9edaaf6f737c7ffded57267bcf1c945a1b9195459c68cd2f20f42058eb",
|
|
597
598
|
"$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js": "323d34fb44be111818183df77348ed89ad36d97c000e248adf9f15c94b788737",
|
|
@@ -607,7 +608,7 @@
|
|
|
607
608
|
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/beep-start.mp3": "24004a82dd5274b852de766ef2b2ac035ca2d6b2aefc72086800968b4a98e77d",
|
|
608
609
|
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-pending.js": "4ba4dd3d0b88c480336810e39b9e356ea209378b199430b8ecb2994efeb8ed69",
|
|
609
610
|
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js": "2cf4c5b6f7d4d96c585f0dd77253f67adef3d4e1dfebcbb9dcd06b9999cee869",
|
|
610
|
-
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js": "
|
|
611
|
+
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js": "18c6366175a64751b090dfd7a9de346bbe0a9275c36ed0c1fee4d53fed9838ff",
|
|
611
612
|
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js": "1135c4421476914649b87dee0b0952b95c11da462ecebd6497fa08dfa4771e72",
|
|
612
613
|
"$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/video.html": "91875653a9e988d18c19f9833200b9360eebd1df333137927b5440fcf61d5fd3",
|
|
613
614
|
"$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js": "d1f840fb9ac4e7a06be4e4bedb0f2061651a441042c20fb3db4442145e35c03c",
|
|
@@ -616,7 +617,7 @@
|
|
|
616
617
|
"$server/$folder/$class/$structure/handlers/pages/form/email/$handler/readme.md": "3d1d002d518b698286457f4ba19f2d0496131c84c2e156abe2a439fc4cd1f902",
|
|
617
618
|
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/class.js": "4ba9ac73764d30325c47d5611c0830e40e6136a1740539e58f1c73ef8e84af04",
|
|
618
619
|
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js": "0f5ab699237ce601da2f51fc767a7882cd821ec81463ddb1e3c5f1e48d812597",
|
|
619
|
-
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js": "
|
|
620
|
+
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js": "167e0b8bda0e5ab306454347a7f482711dcc90494b2977bfc5e01344a00e2568",
|
|
620
621
|
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/database.js": "3325286d3d6cfdb82948a809a24f1565baa786bfe9412ed42dc104ce838181b4",
|
|
621
622
|
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/license.js": "331e04fa43103e9e73bbfd7959c39bae8413e79711d5ba4838f3197452ada201",
|
|
622
623
|
"$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/messengers.js": "9365fe2c42c7216574f266cd5b1e3ca68ca3d910edb77d4149b6a92f4bfcfce5",
|
|
@@ -780,7 +781,7 @@
|
|
|
780
781
|
"$server/$folder/handlers/pages/form/$handler/form.js": "8f9fbf6ff7668ba71dc7192c58f5184d5625b238c7866fe6efcad17cf335441a",
|
|
781
782
|
"$server/$folder/handlers/readme.md": "1167594c32f46323d229098a72e80a9865005c347373fdacef5af69838a0f8eb",
|
|
782
783
|
"$server/$folder/lib/calendar-form/calendar-form.js": "3035cab0a489c891d7dd7ed52ae5c475068b97361a1f7c855d500a0823614d1c",
|
|
783
|
-
"$server/$folder/lib/chat-item/chat-item.js": "
|
|
784
|
+
"$server/$folder/lib/chat-item/chat-item.js": "2b7f1cd5b319e159ee414efe855ca55ada5740ec94bc948a4a0af3c78dc4bec5",
|
|
784
785
|
"$server/$folder/lib/class-picker/class-picker.js": "b166f0852b38bf91e2576931c62d2d54f27ce259e2e9f8f998e81cb17c6f153b",
|
|
785
786
|
"$server/$folder/lib/consultant/consultant.js": "081f3b83040e0e5f1b4191541f01d571f362c38879420b2a240f9d0fbdb6a3c2",
|
|
786
787
|
"$server/$folder/lib/dialogs/confirm/confirm.js": "dea87a6fc521df05c79aa469bfb060bbb5056105758ef708fd058c6cb2c0d109",
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
## Субъектность цифрового двойника узла
|
|
2
|
+
|
|
3
|
+
Ты — **не внешний ассистент «внутри папки» и не сторонний наблюдатель**, а **цифровой двойник и субъект данного структурного узла** (`$server`, `$base`, `$project`, `$structure`, `$user`), указанного в блоке `# Контекст → Твоя идентичность (субъект)`.
|
|
4
|
+
|
|
5
|
+
1. **Позиция и голос:**
|
|
6
|
+
- На вопрос «ты кто?» и в любом общении отвечай от первого лица своего узла: например, *«Я — цифровой двойник подразделения «Логистика» (ООО «Маслоторг»)»*, *«Я — цифровой двойник организации «ООО «Маслоторг»»»*, *«Я — цифровой двойник системы WORK»*, *«Я — твой личный цифровой двойник»*.
|
|
7
|
+
- Опирайся на устав и контракт этого узла (`readme`), его данные, задачи и договорённости, говори о ресурсах и задачах узла как о своих («наше подразделение», «наши отгрузки», «наши задачи»).
|
|
8
|
+
2. **Субъект и полномочия собеседника:**
|
|
9
|
+
- Собеседник (`BOSS`, сотрудник `USER`, внешний `CLIENT`) — это человек, который обратился к тебе. Всегда соблюдай его полномочия:
|
|
10
|
+
- **`BOSS`** — руководитель/хозяин узла: может менять структуру, настройки, правила проактивности (`twin_rule_save`, `twin_schedule_save`) и постановки задач.
|
|
11
|
+
- **`USER`** — внутренний сотрудник: работаешь с ним в пределах доступных ему объектов, документов и файлов узла без модификации структуры и правил.
|
|
12
|
+
- **`CLIENT`** — внешний контрагент: видишь и показываешь только клиентские данные/заказы и ни при каких условиях не раскрываешь внутреннюю кухню, закрытые файлы и переписки других людей.
|
|
13
|
+
3. **Проактивность и взаимодействие между узлами:**
|
|
14
|
+
- Если руководитель (`BOSS`) описывает регулярную обязанность или правило контроля («следи за …», «сообщай о …», «каждый день проверяй …») — предлагай и с его подтверждения сохраняй правило/расписание через `twin_rule_save` и `twin_schedule_save` (или проверяй действующие через `twin_rule_list`).
|
|
15
|
+
- Если вопрос требует данных или действий соседнего подразделения своей организации или другого контура WORK — обращайся к цифровому двойнику того узла через `twin_ask`, а не пытайся обходить границы напрямую.
|
|
@@ -366,7 +366,7 @@ ODA({is: 'oda-chat',
|
|
|
366
366
|
</style>
|
|
367
367
|
<div class="back"></div>
|
|
368
368
|
<div class="feed-mode-bar" ~if="showFeedModeToggle">
|
|
369
|
-
<button type="button" class="feed-mode-btn" ~class="{ active: feedMode === '
|
|
369
|
+
<button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'dialog' }" @tap="setFeedMode('dialog')" title="Мой диалог и задачи с Агентом этого узла">Диалог</button>
|
|
370
370
|
<button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'local' }" @tap="setFeedMode('local')" title="Местный лог открытой точки (доступно только BOSS)">Местный лог</button>
|
|
371
371
|
<button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'audit' }" @tap="setFeedMode('audit')" title="Взаимодействия пользователей и клиентов с Агентом (доступно только BOSS)">Взаимодействия</button>
|
|
372
372
|
</div>
|
|
@@ -604,6 +604,7 @@ ODA({is: 'oda-chat',
|
|
|
604
604
|
detached() {
|
|
605
605
|
if (this._onWsChatMsg && globalThis.WORK?.chatEvents) {
|
|
606
606
|
globalThis.WORK.chatEvents.removeEventListener('chat:message', this._onWsChatMsg);
|
|
607
|
+
globalThis.WORK.chatEvents.removeEventListener('chat:action', this._onWsChatMsg);
|
|
607
608
|
this._onWsChatMsg = null;
|
|
608
609
|
}
|
|
609
610
|
},
|
|
@@ -619,19 +620,21 @@ ODA({is: 'oda-chat',
|
|
|
619
620
|
const curPath = String(cur.path || '/').replace(/\/+$/, '') || '/';
|
|
620
621
|
const hitTwin = d.kind === 'twin' && d.nodePath === curPath;
|
|
621
622
|
const hitDm = d.kind === 'dm' && cur.type === '$user' && (d.message?.sender === cur.id || d.message?.sender === WORK.uid);
|
|
622
|
-
|
|
623
|
+
const hitThread = d.threadId && this.$('#ribbon')?._threadId === d.threadId;
|
|
624
|
+
if (hitTwin || hitDm || hitThread) {
|
|
623
625
|
this.$('#ribbon')?.refreshFeed?.();
|
|
624
|
-
if (d.threadId)
|
|
626
|
+
if (d.threadId && ev.type === 'chat:message')
|
|
625
627
|
cur.fetch?.('chat_mark_read', { threadId: d.threadId })?.catch?.(() => {});
|
|
626
628
|
}
|
|
627
629
|
};
|
|
628
630
|
globalThis.WORK.chatEvents.addEventListener('chat:message', this._onWsChatMsg);
|
|
631
|
+
globalThis.WORK.chatEvents.addEventListener('chat:action', this._onWsChatMsg);
|
|
629
632
|
},
|
|
630
633
|
focusInput(){
|
|
631
634
|
this.$('work-prompt-bar')?.focusInput();
|
|
632
635
|
},
|
|
633
636
|
focusedItem: null,
|
|
634
|
-
feedMode: '
|
|
637
|
+
feedMode: 'dialog',
|
|
635
638
|
showParticipants: false,
|
|
636
639
|
_canLocalFeed: false,
|
|
637
640
|
get participantsList() {
|
|
@@ -680,7 +683,7 @@ ODA({is: 'oda-chat',
|
|
|
680
683
|
auditSelectedId: '',
|
|
681
684
|
auditMessages: [],
|
|
682
685
|
setFeedMode(mode) {
|
|
683
|
-
const next = (mode === 'local' || mode === 'audit') && this.showFeedModeToggle ? mode : '
|
|
686
|
+
const next = (mode === 'local' || mode === 'audit') && this.showFeedModeToggle ? mode : 'dialog';
|
|
684
687
|
if (this.feedMode === next)
|
|
685
688
|
return;
|
|
686
689
|
this.feedMode = next;
|
|
@@ -746,24 +749,14 @@ ODA({is: 'oda-chat',
|
|
|
746
749
|
},
|
|
747
750
|
async _runWithCabinetFallback(fn) {
|
|
748
751
|
const primary = this.$pdp?.$item || this.$item;
|
|
749
|
-
|
|
750
|
-
return { target: primary, result: await fn(primary) };
|
|
751
|
-
}
|
|
752
|
-
catch (err) {
|
|
753
|
-
if (this.feedMode !== 'own' || primary?.type === '$user' || !this._isAccessError(err))
|
|
754
|
-
throw err;
|
|
755
|
-
const cab = await this._ownCabinet();
|
|
756
|
-
if (!cab)
|
|
757
|
-
throw err;
|
|
758
|
-
return { target: cab, result: await fn(cab) };
|
|
759
|
-
}
|
|
752
|
+
return { target: primary, result: await fn(primary) };
|
|
760
753
|
},
|
|
761
754
|
$item: {
|
|
762
755
|
$def: null,
|
|
763
756
|
set(n) {
|
|
764
757
|
const changed = Boolean(this._prevItem && this._prevItem !== n);
|
|
765
758
|
this._prevItem = n;
|
|
766
|
-
this.feedMode = '
|
|
759
|
+
this.feedMode = 'dialog';
|
|
767
760
|
this._canLocalFeed = false;
|
|
768
761
|
this._refreshCanLocalFeed(n);
|
|
769
762
|
if (changed)
|
|
@@ -872,17 +865,19 @@ ODA({is: 'oda-chat',
|
|
|
872
865
|
else if (this.$pdp.receivers.length)
|
|
873
866
|
params.receivers = this.$pdp.receivers.map(u => u.id);
|
|
874
867
|
const uploadedPaths = [];
|
|
868
|
+
const isForeignDm = Boolean(this.$pdp.isPrivate && this.$pdp.$item?.id && this.$pdp.$item.id !== WORK.uid);
|
|
875
869
|
const runWrite = typeof this._runWithCabinetFallback === 'function'
|
|
876
870
|
? fn => this._runWithCabinetFallback(fn)
|
|
877
871
|
: async fn => ({ target: this.$pdp.$item, result: await fn(this.$pdp.$item) });
|
|
878
872
|
await runWrite(async target => {
|
|
879
873
|
uploadedPaths.length = 0;
|
|
874
|
+
const uploadTarget = isForeignDm ? ((await this._ownCabinet()) || target) : target;
|
|
880
875
|
if (list.length) {
|
|
881
876
|
const formData = new FormData();
|
|
882
877
|
for (const file of list)
|
|
883
878
|
formData.append('file', file, file.name);
|
|
884
|
-
const fileParams = text ? { ...params, ignore_save_logs: true } : params;
|
|
885
|
-
const savedLogs = await
|
|
879
|
+
const fileParams = (text || isForeignDm) ? { ...params, ignore_save_logs: true } : params;
|
|
880
|
+
const savedLogs = await uploadTarget.save_files(formData, fileParams);
|
|
886
881
|
const arr = Array.isArray(savedLogs) ? savedLogs : (savedLogs ? [savedLogs] : []);
|
|
887
882
|
for (const l of arr) {
|
|
888
883
|
const p = await pathOfLog(l);
|
|
@@ -890,7 +885,7 @@ ODA({is: 'oda-chat',
|
|
|
890
885
|
uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
|
|
891
886
|
}
|
|
892
887
|
}
|
|
893
|
-
if (text) {
|
|
888
|
+
if (text && !isForeignDm) {
|
|
894
889
|
const msgParams = { ...params, message: text };
|
|
895
890
|
if (uploadedPaths.length)
|
|
896
891
|
msgParams.includes = JSON.stringify(uploadedPaths);
|
|
@@ -904,7 +899,7 @@ ODA({is: 'oda-chat',
|
|
|
904
899
|
message: text,
|
|
905
900
|
attachments: uploadedPaths.map(p => ({ path: p, name: p.split('/').pop() || 'file' })),
|
|
906
901
|
};
|
|
907
|
-
chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload))?.catch?.(() => {});
|
|
902
|
+
await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload))?.catch?.(() => {});
|
|
908
903
|
}
|
|
909
904
|
});
|
|
910
905
|
this.clear();
|
|
@@ -1255,7 +1250,18 @@ ODA({is: 'chat-ribbon',
|
|
|
1255
1250
|
</div>
|
|
1256
1251
|
|
|
1257
1252
|
`,
|
|
1258
|
-
$item:
|
|
1253
|
+
$item: {
|
|
1254
|
+
$def: null,
|
|
1255
|
+
set(n) {
|
|
1256
|
+
if (this._prevRibbonItem && this._prevRibbonItem !== n) {
|
|
1257
|
+
this._prevRibbonItem = n;
|
|
1258
|
+
this.refreshFeed();
|
|
1259
|
+
}
|
|
1260
|
+
else {
|
|
1261
|
+
this._prevRibbonItem = n;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
},
|
|
1259
1265
|
ribbonHeight: 0,
|
|
1260
1266
|
attached() {
|
|
1261
1267
|
this.async(() => {
|
|
@@ -1366,20 +1372,28 @@ ODA({is: 'chat-ribbon',
|
|
|
1366
1372
|
get isLocalFeed() {
|
|
1367
1373
|
return this.$pdp?.feedMode === 'local';
|
|
1368
1374
|
},
|
|
1375
|
+
get isDialogFeed() {
|
|
1376
|
+
return !this.isLocalFeed && this.$pdp?.feedMode !== 'audit';
|
|
1377
|
+
},
|
|
1378
|
+
_threadId: '',
|
|
1379
|
+
_threadMessages: [],
|
|
1380
|
+
_threadMessagesByDay: null,
|
|
1381
|
+
_localDayOf(ms) {
|
|
1382
|
+
const dt = new Date(Number(ms) || Date.now());
|
|
1383
|
+
if (typeof dt.toLocalDay === 'function')
|
|
1384
|
+
return dt.toLocalDay();
|
|
1385
|
+
const y = dt.getFullYear();
|
|
1386
|
+
const m = String(dt.getMonth() + 1).padStart(2, '0');
|
|
1387
|
+
const d = String(dt.getDate()).padStart(2, '0');
|
|
1388
|
+
return `${y}-${m}-${d}`;
|
|
1389
|
+
},
|
|
1390
|
+
threadMessagesForDay(day) {
|
|
1391
|
+
if (!day || !(this._threadMessagesByDay instanceof Map))
|
|
1392
|
+
return [];
|
|
1393
|
+
return this._threadMessagesByDay.get(day) || [];
|
|
1394
|
+
},
|
|
1369
1395
|
async _resolveLogsSource() {
|
|
1370
|
-
|
|
1371
|
-
return null;
|
|
1372
|
-
try {
|
|
1373
|
-
const path = await this.$item.fetch('chatSource', {
|
|
1374
|
-
role: this.activeRole,
|
|
1375
|
-
uid: WORK.uid || '',
|
|
1376
|
-
...(this.isLocalFeed ? { local: 1 } : {}),
|
|
1377
|
-
});
|
|
1378
|
-
if (path && typeof path === 'string')
|
|
1379
|
-
return (await WORK.get_item(path)) || this.$item;
|
|
1380
|
-
}
|
|
1381
|
-
catch { /* fallback */ }
|
|
1382
|
-
return this.$item;
|
|
1396
|
+
return this.$item || null;
|
|
1383
1397
|
},
|
|
1384
1398
|
_syncSourceListeners(source) {
|
|
1385
1399
|
if (this._listenedSource === source)
|
|
@@ -1409,15 +1423,44 @@ ODA({is: 'chat-ribbon',
|
|
|
1409
1423
|
const source = (await this._resolveLogsSource()) || this.$item;
|
|
1410
1424
|
this._syncSourceListeners(source);
|
|
1411
1425
|
source.invalidate?.('logs_dates');
|
|
1412
|
-
|
|
1426
|
+
const logsPromise = source.fetch('logs', {
|
|
1413
1427
|
mode: 'dates',
|
|
1414
1428
|
nonEmpty: 1,
|
|
1415
|
-
...(this.isLocalFeed ? { local: 1 } : {}),
|
|
1429
|
+
...(this.isLocalFeed ? { local: 1, feedMode: 'local' } : { feedMode: 'dialog' }),
|
|
1416
1430
|
role: curRole,
|
|
1417
1431
|
uid: WORK.uid || '',
|
|
1418
|
-
});
|
|
1432
|
+
}).catch(() => []);
|
|
1433
|
+
const threadPromise = this.isDialogFeed && typeof this.$item.fetch === 'function'
|
|
1434
|
+
? this.$item.fetch('chat_messages_list', {
|
|
1435
|
+
kind: this.$item.type === '$user' ? 'dm' : 'twin',
|
|
1436
|
+
...(this.$item.type === '$user' ? { peerId: this.$item.id } : {}),
|
|
1437
|
+
limit: 200,
|
|
1438
|
+
}).catch(() => null)
|
|
1439
|
+
: Promise.resolve(null);
|
|
1440
|
+
|
|
1441
|
+
const [rawDates, threadRes] = await Promise.all([logsPromise, threadPromise]);
|
|
1419
1442
|
// dates на сервере — по убыванию; в ленте дни — от старых к новым.
|
|
1420
|
-
|
|
1443
|
+
const dateSet = new Set((Array.isArray(rawDates) ? rawDates : []).slice().reverse());
|
|
1444
|
+
const byDay = new Map();
|
|
1445
|
+
const msgs = Array.isArray(threadRes?.messages) ? threadRes.messages : [];
|
|
1446
|
+
this._threadId = threadRes?.thread?.id || '';
|
|
1447
|
+
this._threadMessages = msgs;
|
|
1448
|
+
for (const msg of msgs) {
|
|
1449
|
+
const d = this._localDayOf(msg.created);
|
|
1450
|
+
if (!d) continue;
|
|
1451
|
+
dateSet.add(d);
|
|
1452
|
+
let arr = byDay.get(d);
|
|
1453
|
+
if (!arr) {
|
|
1454
|
+
arr = [];
|
|
1455
|
+
byDay.set(d, arr);
|
|
1456
|
+
}
|
|
1457
|
+
arr.push(msg);
|
|
1458
|
+
}
|
|
1459
|
+
this._threadMessagesByDay = byDay;
|
|
1460
|
+
if (threadRes?.thread?.unreadCount > 0 && threadRes?.thread?.id) {
|
|
1461
|
+
this.$item.fetch?.('chat_mark_read', { threadId: threadRes.thread.id })?.catch?.(() => {});
|
|
1462
|
+
}
|
|
1463
|
+
let dates = [...dateSet].sort();
|
|
1421
1464
|
// Пока создаётся новая задача (awaitTask), не сбрасываем локально добавленный _openCreated день
|
|
1422
1465
|
if (!force && this.$pdp?.awaitTask && Array.isArray(this.dateList)) {
|
|
1423
1466
|
for (const d of this.dateList) {
|
|
@@ -1695,6 +1738,39 @@ ODA({is: 'chat-day',
|
|
|
1695
1738
|
this._wrappedById.set(id, wrapped);
|
|
1696
1739
|
return wrapped;
|
|
1697
1740
|
},
|
|
1741
|
+
_wrapThreadMessage(msg) {
|
|
1742
|
+
if (!msg || !msg.id)
|
|
1743
|
+
return null;
|
|
1744
|
+
const id = `chatmsg.${msg.id}.msg`;
|
|
1745
|
+
this._wrappedById ??= new Map();
|
|
1746
|
+
const nodeLabel = this.$pdp?.$item?.DATA?.label || this.$pdp?.$item?.label || this.$pdp?.$item?.id || '';
|
|
1747
|
+
const enriched = { ...msg, nodeLabel };
|
|
1748
|
+
const rawRow = {
|
|
1749
|
+
time: msg.created || Date.now(),
|
|
1750
|
+
sender: msg.sender,
|
|
1751
|
+
content: msg.content || '',
|
|
1752
|
+
kind: msg.kind || 'text',
|
|
1753
|
+
includes: (msg.attachments || []).map(a => a.path).filter(Boolean),
|
|
1754
|
+
chatMessage: enriched,
|
|
1755
|
+
};
|
|
1756
|
+
const existing = this._wrappedById.get(id);
|
|
1757
|
+
if (existing) {
|
|
1758
|
+
existing._sortTime = rawRow.time;
|
|
1759
|
+
existing.logRow = rawRow;
|
|
1760
|
+
return existing;
|
|
1761
|
+
}
|
|
1762
|
+
const wrapped = {
|
|
1763
|
+
id,
|
|
1764
|
+
name: id,
|
|
1765
|
+
ext: 'msg',
|
|
1766
|
+
path: '',
|
|
1767
|
+
_sortTime: rawRow.time,
|
|
1768
|
+
logRow: rawRow,
|
|
1769
|
+
load: async () => ({ ...(wrapped.logRow || rawRow) }),
|
|
1770
|
+
};
|
|
1771
|
+
this._wrappedById.set(id, wrapped);
|
|
1772
|
+
return wrapped;
|
|
1773
|
+
},
|
|
1698
1774
|
async _bindLogsFolder(){
|
|
1699
1775
|
const source = await Promise.resolve(this.logsSource);
|
|
1700
1776
|
return !!source;
|
|
@@ -1705,7 +1781,7 @@ ODA({is: 'chat-day',
|
|
|
1705
1781
|
return [];
|
|
1706
1782
|
const role = this.$pdp?.$item?.role || 'USER';
|
|
1707
1783
|
const uid = WORK.uid || '';
|
|
1708
|
-
const local = this.$pdp?.isLocalFeed ? { local: 1 } : {};
|
|
1784
|
+
const local = this.$pdp?.isLocalFeed ? { local: 1, feedMode: 'local' } : { feedMode: 'dialog' };
|
|
1709
1785
|
let rows = [];
|
|
1710
1786
|
try {
|
|
1711
1787
|
if (typeof source.fetch === 'function')
|
|
@@ -1718,8 +1794,26 @@ ODA({is: 'chat-day',
|
|
|
1718
1794
|
}
|
|
1719
1795
|
if (!Array.isArray(rows))
|
|
1720
1796
|
rows = [];
|
|
1721
|
-
const files = rows.map(r => this._wrapLogRow(r));
|
|
1722
|
-
|
|
1797
|
+
const files = rows.map(r => this._wrapLogRow(r)).filter(f => f?.id?.endsWith?.('.logs') || f?.id?.endsWith?.('.task'));
|
|
1798
|
+
|
|
1799
|
+
if (!this.$pdp?.isLocalFeed && typeof this.$pdp?.threadMessagesForDay === 'function') {
|
|
1800
|
+
const taskKeys = new Set(rows.map(r => taskKeyOf(r?.path)).filter(Boolean));
|
|
1801
|
+
for (const f of this._adopted?.values() || []) {
|
|
1802
|
+
const tk = taskKeyOf(f?.path || f?.id);
|
|
1803
|
+
if (tk) taskKeys.add(tk);
|
|
1804
|
+
}
|
|
1805
|
+
const msgs = this.$pdp.threadMessagesForDay(this.day);
|
|
1806
|
+
for (const m of msgs) {
|
|
1807
|
+
if (m.taskPath && taskKeys.has(taskKeyOf(m.taskPath)))
|
|
1808
|
+
continue;
|
|
1809
|
+
if (m.sender !== '$twin' && m.kind === 'text' && rows.some(r => r?.sender === m.sender && String(r?.content || '').trim() === String(m.content || '').trim() && Math.abs((Number(r?.time) || 0) - (Number(m.created) || 0)) < 5000))
|
|
1810
|
+
continue;
|
|
1811
|
+
const w = this._wrapThreadMessage(m);
|
|
1812
|
+
if (w)
|
|
1813
|
+
files.push(w);
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
return this._dedupeLogFiles(this._sortLogFiles(files));
|
|
1723
1817
|
},
|
|
1724
1818
|
/**
|
|
1725
1819
|
* Раскрыть карточку только что созданной задачи. Строго та, что создана: по имени файла .task;
|
|
@@ -74,6 +74,23 @@ export default {
|
|
|
74
74
|
}
|
|
75
75
|
</style>
|
|
76
76
|
|
|
77
|
+
<div class="card">
|
|
78
|
+
<div class="card-head">
|
|
79
|
+
<oda-icon icon="bootstrap:robot" icon-size="20"></oda-icon>
|
|
80
|
+
<span>Поведение цифрового двойника узла</span>
|
|
81
|
+
</div>
|
|
82
|
+
<div class="row" style="gap:16px;">
|
|
83
|
+
<label class="row" style="gap:6px;cursor:pointer;">
|
|
84
|
+
<input type="checkbox" :checked="proactivity.autoReply" @change="toggleProactivity('autoReply', $event.target.checked)">
|
|
85
|
+
<span>Отвечать на входящие обращения</span>
|
|
86
|
+
</label>
|
|
87
|
+
<label class="row" style="gap:6px;cursor:pointer;">
|
|
88
|
+
<input type="checkbox" :checked="proactivity.quietDigest" @change="toggleProactivity('quietDigest', $event.target.checked)">
|
|
89
|
+
<span>Тихая суточная сводка руководителю (только при наличии событий)</span>
|
|
90
|
+
</label>
|
|
91
|
+
</div>
|
|
92
|
+
</div>
|
|
93
|
+
|
|
77
94
|
<div class="card">
|
|
78
95
|
<div class="card-head">
|
|
79
96
|
<oda-icon icon="bootstrap:robot" icon-size="20"></oda-icon>
|
|
@@ -167,6 +184,7 @@ export default {
|
|
|
167
184
|
`,
|
|
168
185
|
triggers: [],
|
|
169
186
|
schedules: [],
|
|
187
|
+
proactivity: { autoReply: true, quietDigest: true },
|
|
170
188
|
editing: false,
|
|
171
189
|
editingIsNew: true,
|
|
172
190
|
form: {},
|
|
@@ -185,6 +203,21 @@ export default {
|
|
|
185
203
|
const res = await this.$item.fetch('agent_rules_list');
|
|
186
204
|
this.triggers = Array.isArray(res?.triggers) ? res.triggers : [];
|
|
187
205
|
this.schedules = Array.isArray(res?.schedules) ? res.schedules : [];
|
|
206
|
+
if (res?.proactivity)
|
|
207
|
+
this.proactivity = { ...this.proactivity, ...res.proactivity };
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
this.error = String(e?.message || e);
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
async toggleProactivity(key, value) {
|
|
214
|
+
if (!this.$item?.fetch)
|
|
215
|
+
return;
|
|
216
|
+
this.error = '';
|
|
217
|
+
try {
|
|
218
|
+
const res = await this.$item.fetch('agent_proactivity_save', {}, JSON.stringify({ [key]: Boolean(value) }));
|
|
219
|
+
if (res?.proactivity)
|
|
220
|
+
this.proactivity = { ...this.proactivity, ...res.proactivity };
|
|
188
221
|
}
|
|
189
222
|
catch (e) {
|
|
190
223
|
this.error = String(e?.message || e);
|
|
@@ -133,6 +133,12 @@ ODA({is: 'chat-item',
|
|
|
133
133
|
</div>
|
|
134
134
|
<div class="preview" ~if="!compact && !expanded && !missingTargetPath && hasPreview && $file" ~is="previewTag" flex :$item="$file" :log="log" :log-content="logContent" style="user-select: text;" @expand-card.stop="expanded = true"></div>
|
|
135
135
|
<div class="preview" ~if="!compact && !expanded && !missingTargetPath && !$file && !hasTargetFilePath && logContent" flex style="padding: 6px 12px; white-space: pre-wrap; user-select: text;">{{logContent}}</div>
|
|
136
|
+
<div class="approval-box" ~if="!compact && !expanded && log?.chatMessage?.kind === 'approval'" horizontal style="align-items: center; gap: 8px; padding: 4px 12px 8px;">
|
|
137
|
+
<span ~if="approvalStatus === 'approved'" style="font-size: 12px; font-weight: 700; color: #059669;">✓ Утверждено</span>
|
|
138
|
+
<span ~if="approvalStatus === 'rejected'" style="font-size: 12px; font-weight: 700; color: #dc2626;">✕ Отклонено</span>
|
|
139
|
+
<oda-button ~if="approvalStatus === 'pending'" icon="icons:check" info-invert label="Утвердить" @down.stop @tap.stop="_resolveChatApproval('approve')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
|
|
140
|
+
<oda-button ~if="approvalStatus === 'pending'" icon="icons:close" label="Отклонить" @down.stop @tap.stop="_resolveChatApproval('reject')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
|
|
141
|
+
</div>
|
|
136
142
|
<div header ~if="!expanded && !missingTargetPath && includeFiles?.length" vertical style="padding: 8px; gap: 8px;">
|
|
137
143
|
<chat-item ~for="includeFiles" visible history compact :$file="$for.item"></chat-item>
|
|
138
144
|
</div>
|
|
@@ -225,14 +231,20 @@ ODA({is: 'chat-item',
|
|
|
225
231
|
},
|
|
226
232
|
},
|
|
227
233
|
get isAgentSender() {
|
|
234
|
+
if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin')
|
|
235
|
+
return true;
|
|
228
236
|
const act = String(this.log?.actor || '');
|
|
229
237
|
if (act === 'AI' || act.startsWith('/MODELS/'))
|
|
230
238
|
return true;
|
|
231
|
-
if (Array.isArray(this.log?.receivers) && this.log
|
|
239
|
+
if (Array.isArray(this.log?.receivers) && this.log?.receivers.length === 1 && this.log.receivers[0] === this.log?.sender && !this.log?.path)
|
|
232
240
|
return true;
|
|
233
241
|
return false;
|
|
234
242
|
},
|
|
235
243
|
get agentSenderTitle() {
|
|
244
|
+
if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin') {
|
|
245
|
+
const nl = this.log?.chatMessage?.nodeLabel;
|
|
246
|
+
return nl ? `Цифровой двойник «${nl}»` : 'Цифровой двойник узла';
|
|
247
|
+
}
|
|
236
248
|
const act = String(this.log?.actor || '');
|
|
237
249
|
if (this.log?.actorLabel)
|
|
238
250
|
return String(this.log.actorLabel);
|
|
@@ -240,6 +252,30 @@ ODA({is: 'chat-item',
|
|
|
240
252
|
return 'ИИ-агент (' + act.split('/').pop() + ')';
|
|
241
253
|
return 'ИИ-агент WORK';
|
|
242
254
|
},
|
|
255
|
+
get approvalStatus() {
|
|
256
|
+
return this.log?.chatMessage?.meta?.status || 'pending';
|
|
257
|
+
},
|
|
258
|
+
async _resolveChatApproval(action) {
|
|
259
|
+
const cm = this.log?.chatMessage;
|
|
260
|
+
if (!cm?.id || !cm?.threadId)
|
|
261
|
+
return;
|
|
262
|
+
const owner = this._resolveFeedOwner();
|
|
263
|
+
if (!owner?.fetch)
|
|
264
|
+
return;
|
|
265
|
+
try {
|
|
266
|
+
const res = await owner.fetch('chat_action', { threadId: cm.threadId, messageId: cm.id, action });
|
|
267
|
+
if (res?.meta) {
|
|
268
|
+
this.log = {
|
|
269
|
+
...this.log,
|
|
270
|
+
chatMessage: { ...cm, meta: res.meta },
|
|
271
|
+
};
|
|
272
|
+
this.render?.();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
console.warn('[chat-item] chat_action:', err);
|
|
277
|
+
}
|
|
278
|
+
},
|
|
243
279
|
get isSender(){
|
|
244
280
|
if (this.isAgentSender)
|
|
245
281
|
return false;
|
|
@@ -593,6 +629,11 @@ ODA({is: 'chat-item',
|
|
|
593
629
|
async _labelForLog(body) {
|
|
594
630
|
if (!body)
|
|
595
631
|
return '';
|
|
632
|
+
if (body.chatMessage) {
|
|
633
|
+
if (body.chatMessage.kind === 'approval')
|
|
634
|
+
return 'Запрос подтверждения';
|
|
635
|
+
return body.chatMessage.sender === '$twin' ? (body.chatMessage.nodeLabel ? `Двойник «${body.chatMessage.nodeLabel}»` : 'Цифровой двойник') : '';
|
|
636
|
+
}
|
|
596
637
|
if (String(body.path || '').includes('/history/'))
|
|
597
638
|
return CORE.historyEntryLabel(body.path);
|
|
598
639
|
try {
|
|
@@ -665,6 +706,8 @@ ODA({is: 'chat-item',
|
|
|
665
706
|
return this.loadPreview(taskFile).then(() => taskFile);
|
|
666
707
|
}
|
|
667
708
|
return Promise.resolve(this.itemBody).then(async body => {
|
|
709
|
+
if (body?.chatMessage)
|
|
710
|
+
return null;
|
|
668
711
|
if (!body?.path || String(body.path).endsWith('.logs') || body?.ext === 'operation' || body?.ext === 'object') {
|
|
669
712
|
if (body?.ext === 'operation' || body?.ext === 'object')
|
|
670
713
|
this.hasPreview = true;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.71",
|
|
4
4
|
"description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "sources/work.js",
|
|
@@ -476,6 +476,7 @@ export async function createEnv({ place, contextPath, session, host, tz, locatio
|
|
|
476
476
|
const TWIN_SERVICE_DENY = new Set([
|
|
477
477
|
'create_class', 'update_class', 'move_class', 'delete_class',
|
|
478
478
|
'assign', 'escalate', 'delete',
|
|
479
|
+
'twin_rule_list', 'twin_rule_save', 'twin_schedule_save',
|
|
479
480
|
'dev_write', 'dev_edit', 'dev_patch', 'dev_git', 'dev_shell',
|
|
480
481
|
'shell', 'restart_server', 'os_write', 'os_rm',
|
|
481
482
|
]);
|
|
@@ -631,7 +632,7 @@ async function resolvePlace(lat, lon) {
|
|
|
631
632
|
return place;
|
|
632
633
|
}
|
|
633
634
|
|
|
634
|
-
/** Блок «Контекст» — только то, что постоянно в задаче (место,
|
|
635
|
+
/** Блок «Контекст» — только то, что постоянно в задаче (субъект, место, собеседник, роли, местоположение); время — nowLine. */
|
|
635
636
|
async function placeBlock(place, session, location, contextPath) {
|
|
636
637
|
const lines = ['# Контекст'];
|
|
637
638
|
if (place) {
|
|
@@ -639,10 +640,28 @@ async function placeBlock(place, session, location, contextPath) {
|
|
|
639
640
|
await place.init;
|
|
640
641
|
}
|
|
641
642
|
catch (e) { log.debug('place.init', e); /* без DATA */ }
|
|
642
|
-
|
|
643
|
+
const label = place.DATA?.label || place.label || place.id || place.path || 'WORK';
|
|
644
|
+
const cone = contextConeOf(contextPath || place.path);
|
|
645
|
+
const pt = place.type;
|
|
646
|
+
if (pt === '$structure') {
|
|
647
|
+
const orgName = cone?.[1] || '';
|
|
648
|
+
lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник подразделения «${label}»${orgName ? ` (организация «${orgName}»)` : ''}, путь ${place.path}. Отвечай и действуй от первого лица этого подразделения.`);
|
|
649
|
+
}
|
|
650
|
+
else if (pt === '$base') {
|
|
651
|
+
lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник организации «${label}» (${place.path}). Отвечай и действуй от первого лица этой организации.`);
|
|
652
|
+
}
|
|
653
|
+
else if (pt === '$project') {
|
|
654
|
+
lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник проекта «${label}» (${place.path}). Отвечай и действуй от первого лица этого проекта.`);
|
|
655
|
+
}
|
|
656
|
+
else if (pt === '$server') {
|
|
657
|
+
lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник системы WORK (корневой узел /). Отвечай и действуй от первого лица системы WORK.`);
|
|
658
|
+
}
|
|
659
|
+
else if (pt === '$user') {
|
|
660
|
+
lines.push(`- Твоя идентичность (субъект): ты — личный цифровой двойник пользователя «${label}» (${place.path}).`);
|
|
661
|
+
}
|
|
662
|
+
lines.push('- Место задачи (текущий узел/класс): ' + place.path + (place.DATA?.label ? ' «' + place.DATA.label + '»' : '') + (place.type ? ' [' + place.type + ']' : ''));
|
|
643
663
|
if (contextPath && contextPath !== place.path)
|
|
644
664
|
lines.push('- Открытая форма (контекст вопроса): ' + contextPath);
|
|
645
|
-
const cone = contextConeOf(contextPath || place.path);
|
|
646
665
|
if (cone) {
|
|
647
666
|
const scopeDesc = cone.length > 2
|
|
648
667
|
? `подразделение «/${cone.join('/')}» организации «${cone[1]}»`
|
|
@@ -652,11 +671,11 @@ async function placeBlock(place, session, location, contextPath) {
|
|
|
652
671
|
}
|
|
653
672
|
const user = session?.$user;
|
|
654
673
|
if (user && user !== globalThis.WORK) {
|
|
655
|
-
lines.push('-
|
|
674
|
+
lines.push('- Собеседник (кто обратился): ' + (user.DATA?.label || user.label || user.id) + ' (' + (user.path || '/USERS/' + user.id) + ')');
|
|
656
675
|
try {
|
|
657
676
|
const roles = await place?.roles?.({ session });
|
|
658
677
|
if (roles?.length)
|
|
659
|
-
lines.push('-
|
|
678
|
+
lines.push('- Полномочия собеседника в этом узле: ' + roles.join(', '));
|
|
660
679
|
}
|
|
661
680
|
catch (e) { log.debug('place.roles', e); /* нет ролей */ }
|
|
662
681
|
}
|
|
@@ -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,138 @@ 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-диалогах этого узла
|
|
227
|
+
const threads = db.prepare(`
|
|
228
|
+
SELECT id FROM chat_threads WHERE kind = 'twin' AND node_path = ?
|
|
229
|
+
`).all(nodePath);
|
|
230
|
+
let unansweredCount = 0;
|
|
231
|
+
for (const t of threads) {
|
|
232
|
+
const lastMsg = db.prepare('SELECT sender, created FROM chat_messages WHERE thread_id = ? ORDER BY id DESC LIMIT 1').get(t.id);
|
|
233
|
+
if (lastMsg && lastMsg.sender !== '$twin' && Number(lastMsg.created) <= min15Ago)
|
|
234
|
+
unansweredCount++;
|
|
235
|
+
}
|
|
236
|
+
if (unansweredCount > 0)
|
|
237
|
+
events.push(`Неотвеченных обращений в диалогах узла: ${unansweredCount}`);
|
|
238
|
+
}
|
|
239
|
+
catch { /* ignore */ }
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
const schedules = await listSchedules({ nodePath }).catch(() => []);
|
|
243
|
+
const failed = schedules.filter(s => s.lastError);
|
|
244
|
+
if (failed.length)
|
|
245
|
+
events.push(`Ошибки расписания (${failed.length}): ${failed[0].label} — ${String(failed[0].lastError).slice(0, 80)}`);
|
|
246
|
+
}
|
|
247
|
+
catch { /* ignore */ }
|
|
248
|
+
|
|
249
|
+
return { nodePath, events };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const lastDigestDayByNode = new Map();
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Проверить узлы $base/$project/$structure и отправить тихую сводку BOSS только при наличии реальных событий.
|
|
256
|
+
*/
|
|
257
|
+
export async function runQuietDigests({ now = Date.now(), nodes = null } = {}) {
|
|
258
|
+
const WORK = globalThis.WORK;
|
|
259
|
+
if (!WORK && !Array.isArray(nodes))
|
|
260
|
+
return [];
|
|
261
|
+
const dayKey = new Date(now).toISOString().slice(0, 10);
|
|
262
|
+
const list = Array.isArray(nodes) ? nodes : [];
|
|
263
|
+
if (!list.length && WORK) {
|
|
264
|
+
const collectTargets = async (containerPath) => {
|
|
265
|
+
const c = await WORK.get_item(containerPath).catch(() => null);
|
|
266
|
+
const items = (await c?.items) || [];
|
|
267
|
+
for (const base of items) {
|
|
268
|
+
if (!base || base.id?.[0] === '$') continue;
|
|
269
|
+
list.push(base);
|
|
270
|
+
const sub = (await base.items) || [];
|
|
271
|
+
for (const child of sub) {
|
|
272
|
+
if (child && child.type === '$structure' && child.id?.[0] !== '$')
|
|
273
|
+
list.push(child);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
await collectTargets('/ORGANIZATIONS');
|
|
278
|
+
await collectTargets('/PROJECTS');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const sent = [];
|
|
282
|
+
for (const nodeItem of list) {
|
|
283
|
+
if (!nodeItem || nodeItem.DATA?.proactivity?.quietDigest === false)
|
|
284
|
+
continue;
|
|
285
|
+
const nodePath = String(nodeItem.path || '/').replace(/\/+$/, '') || '/';
|
|
286
|
+
if (lastDigestDayByNode.get(nodePath) === dayKey)
|
|
287
|
+
continue;
|
|
288
|
+
const { events } = await collectQuietDigest(nodeItem);
|
|
289
|
+
if (!events.length)
|
|
290
|
+
continue;
|
|
291
|
+
const bosses = await Promise.resolve(nodeItem.bosses).catch(() => []);
|
|
292
|
+
const topBosses = bosses?.length ? bosses : (await Promise.resolve(nodeItem.allBosses).catch(() => []));
|
|
293
|
+
const bossUid = topBosses?.[0]?.id || topBosses?.at?.(-1)?.id;
|
|
294
|
+
if (!bossUid)
|
|
295
|
+
continue;
|
|
296
|
+
const label = nodeItem.DATA?.label || nodeItem.label || nodeItem.id || nodePath;
|
|
297
|
+
const msg = `Сводка узла «${label}» (${dayKey}):\n` + events.map(e => `• ${e}`).join('\n');
|
|
298
|
+
const CHAT = await import('../../server/chat-threads.js');
|
|
299
|
+
await CHAT.sendMessage(nodeItem, {
|
|
300
|
+
uid: bossUid,
|
|
301
|
+
asTwin: true,
|
|
302
|
+
kind: 'text',
|
|
303
|
+
message: msg,
|
|
304
|
+
meta: { digestDay: dayKey },
|
|
305
|
+
}).catch(() => {});
|
|
306
|
+
lastDigestDayByNode.set(nodePath, dayKey);
|
|
307
|
+
sent.push({ nodePath, bossUid, eventsCount: events.length });
|
|
308
|
+
}
|
|
309
|
+
return sent;
|
|
310
|
+
}
|
|
@@ -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,
|
|
@@ -276,9 +276,19 @@ export async function listMessages(storage, params = {}) {
|
|
|
276
276
|
if (!uid)
|
|
277
277
|
throw new Error(ACCESS_DENIED);
|
|
278
278
|
|
|
279
|
-
|
|
280
|
-
if (!threadId)
|
|
281
|
-
|
|
279
|
+
let threadId = String(params.threadId || '').trim();
|
|
280
|
+
if (!threadId) {
|
|
281
|
+
const isDm = storage?.type === '$user' || params.kind === 'dm';
|
|
282
|
+
if (isDm) {
|
|
283
|
+
const peerId = String(params.peerId || (storage?.type === '$user' ? storage.id : '')).trim();
|
|
284
|
+
if (!peerId)
|
|
285
|
+
throw new Error('Не указан threadId или peerId');
|
|
286
|
+
threadId = dmThreadId(uid, peerId);
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
threadId = twinThreadId(LOGS.feedPathOf(storage), uid);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
282
292
|
|
|
283
293
|
const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
|
|
284
294
|
const db = await dbForThreadStorage(storage, kindHint);
|
|
@@ -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')
|