odant-work 1.0.100 → 1.0.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/$server/$folder/$class/$structure/$department/ai/config.js +9 -0
  2. package/$server/$folder/$class/$structure/$department/ai/system.md +11 -0
  3. package/$server/$folder/$class/$structure/$department/class.js +9 -0
  4. package/$server/$folder/$class/$structure/$project/ai/config.js +9 -0
  5. package/$server/$folder/$class/$structure/$project/ai/system.md +12 -0
  6. package/$server/$folder/$class/$structure/$project/class.js +4 -1
  7. package/$server/$folder/$class/$structure/$project/handlers/pages/site/$handler/class.js +1 -1
  8. package/$server/$folder/$class/$structure/$server/ai/config.js +9 -0
  9. package/$server/$folder/$class/$structure/$server/ai/system.md +10 -0
  10. package/$server/$folder/$class/$structure/$server/class.js +2 -0
  11. package/$server/$folder/$class/$structure/$user/ai/config.js +9 -0
  12. package/$server/$folder/$class/$structure/$user/ai/system.md +8 -0
  13. package/$server/$folder/$class/$structure/$user/class.js +3 -0
  14. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/profile/$handler/class.js +5 -2
  15. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/staff/$handler/class.js +3 -0
  16. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/tokens/$handler/class.js +24 -0
  17. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/users/$handler/class.js +213 -0
  18. package/$server/$folder/$class/$structure/ai/system.md +1 -1
  19. package/$server/$folder/$class/$structure/class.js +4 -2
  20. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +67 -20
  21. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +132 -3
  22. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2 -2
  23. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +2 -1
  24. package/$server/$folder/$class/ai/system.md +2 -2
  25. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +7 -0
  26. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +22 -31
  27. package/$server/$folder/handlers/pages/form/$handler/class.js +47 -5
  28. package/$server/$folder/lib/chat-item/chat-item.js +14 -2
  29. package/$server/$folder/lib/consultant/consultant.js +1 -1
  30. package/$server/$folder/lib/explorer/explorer.js +38 -12
  31. package/$server/$folder/lib/icon/icon.js +1 -1
  32. package/$server/$folder/lib/node/node.js +3 -3
  33. package/$server/$folder/lib/site-loc/site-loc.js +8 -3
  34. package/$server/$folder/lib/tree/tree.js +8 -9
  35. package/AGENTS.md +3 -3
  36. package/MODULES/$domain/class.js +1 -0
  37. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/class.js +1 -0
  38. package/{$server/$folder/$class/$users → USERS/$user}/class.js +4 -1
  39. package/oda/oda.js +15 -1
  40. package/package.json +1 -1
  41. package/readme.md +1 -1
  42. package/scripts/import-bis.mjs +5 -5
  43. package/scripts/import-delovaya.mjs +5 -5
  44. package/sources/client/class.js +1 -1
  45. package/sources/client.js +84 -38
  46. package/sources/data/api.js +1 -1
  47. package/sources/data/classes.js +2 -1
  48. package/sources/data/schema.js +2 -0
  49. package/sources/host/auth-methods.js +15 -4
  50. package/sources/modules/agent/index.js +22 -6
  51. package/sources/modules/agent/node-rules.js +353 -9
  52. package/sources/modules/agent/scheduler.js +7 -0
  53. package/sources/modules/agent/scope.js +8 -6
  54. package/sources/modules/agent/tools/work/access.js +1 -1
  55. package/sources/modules/agent/tools/work/classes.js +1 -1
  56. package/sources/modules/agent/triggers.js +1 -1
  57. package/sources/modules/agent/twin-bus.js +2 -1
  58. package/sources/modules/notify/index.js +5 -2
  59. package/sources/modules/rag/extract.js +1 -1
  60. package/sources/modules/trainer/local-engine.js +3 -1
  61. package/sources/modules/user-profile/user-profile.js +120 -115
  62. package/sources/modules/user-profile/user-tokens.js +185 -0
  63. package/sources/server/access/gateway.js +4 -3
  64. package/sources/server/access/links.js +9 -6
  65. package/sources/server/chat-threads.js +1 -1
  66. package/sources/server/class/base-template.js +3 -2
  67. package/sources/server/class/distro.js +9 -5
  68. package/sources/server/class/feed.js +30 -0
  69. package/sources/server/class/scaffold.js +137 -0
  70. package/sources/server/class/search.js +2 -2
  71. package/sources/server/class/security.js +35 -11
  72. package/sources/server/class.js +5 -3
  73. package/sources/server/folder.js +17 -13
  74. package/sources/server/logs.js +14 -0
  75. package/sources/server/node.js +1 -1
  76. package/sources/server/user.js +3 -0
  77. package/sources/work.js +7 -0
  78. package/USERS/$users/class.js +0 -4
@@ -284,7 +284,7 @@ export default {
284
284
  if (!it || ('isPlace' in Object(it) && it.isPlace))
285
285
  return '';
286
286
  const t = it.type;
287
- if (t === '$project' || t === '$structure' || t === '$server' || t === '$domain')
287
+ if ((it.DATA?.isStructure && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server' || t === '$domain')
288
288
  return '';
289
289
  const c = isLinkNode(it) ? it.objectCount : it.DATA?.objectCount;
290
290
  return (typeof c === 'number' && c > 0) ? c.toLocaleString('ru-RU') : '';
@@ -357,7 +357,7 @@ export default {
357
357
  return false;
358
358
  const t = it.type;
359
359
  const isNetServer = t === '$node' && it.id !== 'NODES';
360
- return t === '$project' || t === '$structure' || t === '$server' || isNetServer || it.id === 'PROJECTS';
360
+ return (it.DATA?.isStructure && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server' || isNetServer || it.id === 'PROJECTS';
361
361
  },
362
362
  // пользователи в строке дерева не показываются (шум и запросы на каждую строку); свойство оставлено для совместимости биндов
363
363
  showUsers: false,
@@ -431,7 +431,7 @@ export default {
431
431
  return 24;
432
432
  const t = this.$item?.type;
433
433
  const isNetServer = t === '$node' && this.$item?.id !== 'NODES';
434
- if(this.isUser || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer)
434
+ if(this.isUser || this.$item?.DATA?.isStructure || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer)
435
435
  return 48;
436
436
  if(t === '$module' || t === '$provider' || t === '$mcp')
437
437
  return 32;
@@ -10,8 +10,13 @@ export const STRUCTURE_TYPES = Object.freeze(['$structure', '$project']);
10
10
  * @param {string} type Тип элемента ($project, $structure, …)
11
11
  * @returns {string}
12
12
  */
13
- export function structureKind(type) {
14
- switch (type) {
13
+ export function structureKind(typeOrItem) {
14
+ if (typeOrItem && typeof typeOrItem === 'object') {
15
+ if (typeOrItem.DATA?.isProject) return 'org';
16
+ if (typeOrItem.DATA?.isDepartment) return 'unit';
17
+ typeOrItem = typeOrItem.type;
18
+ }
19
+ switch (typeOrItem) {
15
20
  case '$project': return 'org';
16
21
  case '$structure': return 'unit';
17
22
  default: return '';
@@ -20,7 +25,7 @@ export function structureKind(type) {
20
25
 
21
26
  /** Узел оргструктуры (есть сайт, участвует в навигации). */
22
27
  export function isStructureNode(item) {
23
- return !!item && STRUCTURE_TYPES.includes(item.type);
28
+ return !!item && (STRUCTURE_TYPES.includes(item.type) || item.DATA?.isProject === true || item.DATA?.isDepartment === true);
24
29
  }
25
30
 
26
31
  function _encodeVal(v) {
@@ -6,7 +6,6 @@ function rawItem(it) {
6
6
  return it?.[R]?.target || it;
7
7
  }
8
8
 
9
- const MAIN_TREE_ENV_TYPES = new Set(['$domain', '$structure', '$project', '$module', '$provider', '$mcp', '$users', '$user', '$node', '$ai']);
10
9
  const MAIN_TREE_LEAF_TYPES = new Set(['$module', '$mcp', '$user', '$ai']);
11
10
 
12
11
  function isRootSectionNode(it) {
@@ -51,14 +50,14 @@ function filterMainTreeItems(items, parent) {
51
50
  if (parent.type === '$folder')
52
51
  return items;
53
52
  if (isRootSectionNode(parent))
54
- return items.filter(f => f && MAIN_TREE_ENV_TYPES.has(f.type));
53
+ return items.filter(f => f && !f.DATA?.objects);
55
54
  if (isMainTreeLeaf(parent))
56
55
  return [];
57
- if (parent.type === '$project' || parent.type === '$structure')
58
- return items.filter(f => f && (f.type === '$structure' || f.type === '$project'));
56
+ if (parent.type === '$project' || parent.type === '$structure' || parent.DATA?.isProject || parent.DATA?.isDepartment)
57
+ return items.filter(f => f && (f.type === '$structure' || f.type === '$project' || f.DATA?.isDepartment || f.DATA?.isProject));
59
58
  if (parent.type === '$provider')
60
59
  return items.filter(f => f?.type === '$ai');
61
- return items.filter(f => f && MAIN_TREE_ENV_TYPES.has(f.type));
60
+ return items.filter(f => f && !f.DATA?.objects);
62
61
  }
63
62
 
64
63
  /**
@@ -77,7 +76,7 @@ export function knownHasItems(it, pdp = {}) {
77
76
  return false;
78
77
  if (it.DATA?.mainTree === true && typeof it.DATA?.hasItems === 'boolean')
79
78
  return it.DATA.hasItems;
80
- if (it.type === '$project' || it.type === '$structure')
79
+ if (it.type === '$project' || it.type === '$structure' || it.DATA?.isProject || it.DATA?.isDepartment)
81
80
  return undefined;
82
81
  }
83
82
  // __version — реактивная зависимость: после события changed флаг удаляется и пересчитывается по items
@@ -862,7 +861,7 @@ ODA({is: 'oda-tree-node',
862
861
  return false;
863
862
  const t = it.type;
864
863
  const isNetServer = t === '$node' && it.id !== 'NODES';
865
- return it instanceof CORE.$user || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer;
864
+ return it instanceof CORE.$user || it.DATA?.isStructure === true || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer;
866
865
  },
867
866
  get isMediumIconNode() {
868
867
  return this.isModule;
@@ -885,7 +884,7 @@ ODA({is: 'oda-tree-node',
885
884
  return false;
886
885
  const t = it.type;
887
886
  // $server (корень WORK) и $project — тоже наследники $structure: на них показываем BOSS.
888
- return t === '$project' || t === '$structure' || t === '$server';
887
+ return (it.DATA?.isStructure === true && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server';
889
888
  },
890
889
  get isModule() {
891
890
  const it = this.$item;
@@ -931,7 +930,7 @@ ODA({is: 'oda-tree-node',
931
930
  return false;
932
931
  this.$item.__version;
933
932
  const t = this.$item?.type;
934
- if (t !== '$structure' && t !== '$project' && t !== '$server')
933
+ if ((!this.$item?.DATA?.isStructure && t !== '$structure' && t !== '$project' && t !== '$server') || this.$item?.DATA?.isUser || t === '$user')
935
934
  return false;
936
935
  return !!this.$item?.DATA?.hasSecurity;
937
936
  },
package/AGENTS.md CHANGED
@@ -30,9 +30,9 @@
30
30
  2. **Установка.** Модуль ставится в структуру и работает для неё и всех структур ниже. Копия ниже продолжает копию выше и меняет только своё.
31
31
  3. **Владение.** Агент, роли, навыки и память есть только у структуры. Модуль поставляет классы данных, инструменты, подключения и модели. Класс данных хранит объекты в базе ближайшего проекта.
32
32
 
33
- - **Дерево и типы:** всё — папка или файл единого дерева; адрес узла — его путь. Папка с метапапкой `$тип` — класс: `class.js` (свойства), `readme.md` (контракт), `handlers/`. Ветки типов: `$structure` (кто действует: `$server`, `$project`, `$structure`, `$user`), `$module` (что установлено, в т. ч. `$mcp` и `$provider` с моделями `$ai`), `$data` (где хранятся объекты); `$class` абстрактен. `/X/~/…` отдаёт собранное по слоям: `/X/~/class.js`, `/X/~/readme.md`, `/X/~/handlers/…`.
33
+ - **Дерево и типы:** всё — папка или файл единого дерева; адрес узла — его путь. Папка с метапапкой `$тип` — класс: `class.js` (свойства), `readme.md` (контракт), `handlers/`. Ветки типов: `$structure` (абстрактный базовый тип; кто действует: `$server`, `$project`, `$department`, `$user`), `$module` (что установлено, в т. ч. `$mcp` и `$provider` с моделями `$ai`), `$data` (где хранятся объекты); `$class` абстрактен. `/X/~/…` отдаёт собранное по слоям: `/X/~/class.js`, `/X/~/readme.md`, `/X/~/handlers/…`.
34
34
  - **Ссылки:** только `ancestor` (узел продолжает другой) и `types` (примеси) в `class.js`; из пути ничего не вычисляется.
35
- - **Роли:** встроенная одна — `BOSS` (единственный владелец узла и поддерева на `$server`, `$project` и `$structure`, наследуется вниз). Остальные — записи `#security.ROLES` только подразделений `$structure` (`USERS`, права `LINKS`, маркер `external`), а не дочерние классы.
35
+ - **Роли:** встроенная одна — `BOSS` (единственный владелец узла и поддерева на `$server`, `$project` и `$department`, наследуется вниз). Остальные — записи `#security.ROLES` только подразделений `$department` (`USERS`, права `LINKS`, маркер `external`), а не дочерние классы.
36
36
  - **Учёт:** `$catalog` (листья хранят объекты, группы агрегируют), `$virtual` (`turnover`/`balance` + `OVERLAY`), `$struct` (`table: true` — таблица), `$operation` — двойная запись (Дебет + Кредит в `$account` + `logs`); проведённое исправляется только сторно; поля справочника-аналитики — субаналитики.
37
37
  - **Ядро и дерево:** ядро (`sources/`, `oda/`, `run.mjs`, `#system/`) меняется только по явной задаче доработки движка через `developer`-контур (тесты, отложенный перезапуск). Остальное — дерево, включая системный типизатор `/$server/$folder`; оно меняется штатно, без git. Правки типизатора и модулей уровня WORK — только извне проектов, с подтверждением, проверкой последствий и сбросом кэша.
38
38
  - **Арены инструментов:** дерево — WORK-инструментами (`ls/read/find/write/edit/delete`, `create_class/update_class/move_class/delete_class`), файлы ОС вне WORK — `os_*`; `shell` не служит обходом WORK-ограничений.
@@ -48,7 +48,7 @@
48
48
  ## Дополнительно для сессий разработки (OpenCode / репозиторий)
49
49
 
50
50
  1. Актуальность рабочей копии: ветка **`main`** (`git pull origin main`; при использовании SVN — `svn update`).
51
- 2. Демо-база организации (`PROJECTS/Маслоторг/$project/#system/work.db`): `node scripts/demo-seed.mjs`.
51
+ 2. Демо-база организации (`<Проект>/$project/#system/work.db`): `node scripts/demo-seed.mjs`.
52
52
  3. Документация: канон — **`docs/architecture.md`** (при расхождении он главнее кода и остальных документов; меняет его только владелец проекта). Справочно: **`docs/use-cases.md`**, **`docs/work-mcp.md`**, **`docs/autonomous-install-and-licensing.md`**, **`docs/halogen-provider.md`**, **`docs/chrome-extension.md`**, **`sources/data/progress.md`** (исторические спецификации — в `docs/archive/`).
53
53
  4. Протокол экономии токенов/кэша: основная модель **`Gemini 4 Argon`** (`opencode/gemini-4-argon`), не менять модель внутри длинной сессии, разведку делегировать субагенту `explore`, сжимать (`/compact`) на границах этапов. В начале сессии выдать короткий блок **«Рекомендация на шаг»**.
54
54
  5. Принцип единого UI: единая форма объектов — `form/objects` (и карточка `form/object` с `designMode`), выборщик класса — `item-class-picker`; `form/builder` удалён (модель данных меняется через ИИ-инструменты `create_class`/`update_class` и вкладку «Система → Реквизиты»).
@@ -2,6 +2,7 @@ export default {
2
2
  label: 'Модули',
3
3
  icon: 'odant:folder',
4
4
  form: 'system',
5
+ container: true,
5
6
  mainTreeChildren: ['$folder', '$module', '$provider', '$mcp'],
6
7
  ACCESS: {
7
8
  mcp_catalog: 'read',
@@ -10,6 +10,7 @@ export default {
10
10
  label: 'Local',
11
11
  protocol: 'local',
12
12
  form: 'system',
13
+ allowAllUsers: true,
13
14
  mainTreeChildren: ['$ai'],
14
15
  baseUrl: 'http://127.0.0.1:8731/v1/chat/completions',
15
16
  }
@@ -2,4 +2,7 @@ export default {
2
2
  label: 'Пользователи',
3
3
  icon: 'social:people',
4
4
  allowTypes: '$user',
5
- }
5
+ usersContainer: true,
6
+ allowRoles: false,
7
+ mainTreeChildren: ['$user'],
8
+ };
package/oda/oda.js CHANGED
@@ -356,13 +356,27 @@ localStorage: {
356
356
  }
357
357
  this.save();
358
358
  }
359
- save() {
359
+ save(sync = false) {
360
360
  if (this._value === undefined)
361
361
  return;
362
+ if (sync) {
363
+ this.flush();
364
+ return;
365
+ }
362
366
  this.debounce('saveToLocalStorage',()=>{
363
367
  globalThis.localStorage.setItem(this.path, JSON.stringify(this.value));
364
368
  })
365
369
  }
370
+ flush() {
371
+ if (this._value === undefined)
372
+ return;
373
+ const dbKey = 'saveToLocalStorage.0';
374
+ if (this.__debounces__?.[dbKey]) {
375
+ clearTimeout(this.__debounces__[dbKey]);
376
+ delete this.__debounces__[dbKey];
377
+ }
378
+ globalThis.localStorage.setItem(this.path, JSON.stringify(this.value));
379
+ }
366
380
  get version() {
367
381
  return this.value.$$stamp;
368
382
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.100",
3
+ "version": "1.0.102",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/readme.md CHANGED
@@ -114,7 +114,7 @@ WORK решает проблему управления организацион
114
114
  | `/MODULES/` | Эталонные модули и внешние коннекторы (`Register`, `Geo`, `KLADR`, `Process`, `1C`, `Bitrix24`, `Telegram`, `DaData`, …) — предки для модулей организаций |
115
115
  | `/MODELS/` | Встроенный источник ИИ: локальные (`Local`) и внешние провайдеры/модели (`$provider`, `$ai`), дообучение и профилировщик железа |
116
116
  | `/NODES/` | Карта адресов внешних серверов WORK (федерация серверов) |
117
- | `/USERS/` | Пользователи (класс `$users`, личные кабинеты `$user`) |
117
+ | `/USERS/` | Пользователи (класс `$user`, личные кабинеты `$user`) |
118
118
  | `tests/`, `docs/` | Автотесты, контрольные задания (`tests/eval`) и проектная документация (`docs/architecture.md` — канон) |
119
119
 
120
120
  ## 5. В каком это состоянии
@@ -124,8 +124,8 @@ export function scaffoldBisClasses() {
124
124
  }
125
125
  }`);
126
126
 
127
- // 1.2. Подразделения ($structure) и рабочие места (ROLES + LINKS)
128
- writeClassJs('accounting', '$structure', `{
127
+ // 1.2. Подразделения ($department) и рабочие места (ROLES + LINKS)
128
+ writeClassJs('accounting', '$department', `{
129
129
  icon: "icons:account-balance",
130
130
  label: "Бухгалтерия",
131
131
  "#security": {
@@ -229,7 +229,7 @@ export function scaffoldBisClasses() {
229
229
  }
230
230
  }`);
231
231
 
232
- writeClassJs('orders', '$structure', `{
232
+ writeClassJs('orders', '$department', `{
233
233
  icon: "icons:shopping-cart",
234
234
  label: "Заказы и договоры",
235
235
  "#security": {
@@ -254,7 +254,7 @@ export function scaffoldBisClasses() {
254
254
  }
255
255
  }`);
256
256
 
257
- writeClassJs('hr', '$structure', `{
257
+ writeClassJs('hr', '$department', `{
258
258
  icon: "icons:supervisor-account",
259
259
  label: "Кадры и делопроизводство",
260
260
  "#security": {
@@ -277,7 +277,7 @@ export function scaffoldBisClasses() {
277
277
  }
278
278
  }`);
279
279
 
280
- writeClassJs('development', '$structure', `{
280
+ writeClassJs('development', '$department', `{
281
281
  icon: "carbon:code",
282
282
  label: "Разработка и выставки",
283
283
  "#security": {
@@ -240,8 +240,8 @@ export function scaffoldDelovayaClasses() {
240
240
  }
241
241
  }`);
242
242
 
243
- // 2.2. Подразделения ($structure) и рабочие места (ROLES + LINKS)
244
- writeClassJs('accounting', '$structure', `{
243
+ // 2.2. Подразделения ($department) и рабочие места (ROLES + LINKS)
244
+ writeClassJs('accounting', '$department', `{
245
245
  icon: "icons:account-balance",
246
246
  label: "Бухгалтерия",
247
247
  "#security": {
@@ -322,7 +322,7 @@ export function scaffoldDelovayaClasses() {
322
322
  }
323
323
  }`);
324
324
 
325
- writeClassJs('orders', '$structure', `{
325
+ writeClassJs('orders', '$department', `{
326
326
  icon: "icons:shopping-cart",
327
327
  label: "Отдел заказов",
328
328
  "#security": {
@@ -344,7 +344,7 @@ export function scaffoldDelovayaClasses() {
344
344
  }
345
345
  }`);
346
346
 
347
- writeClassJs('hr', '$structure', `{
347
+ writeClassJs('hr', '$department', `{
348
348
  icon: "icons:supervisor-account",
349
349
  label: "Отдел кадров",
350
350
  "#security": {
@@ -363,7 +363,7 @@ export function scaffoldDelovayaClasses() {
363
363
  }
364
364
  }`);
365
365
 
366
- writeClassJs('research', '$structure', `{
366
+ writeClassJs('research', '$department', `{
367
367
  icon: "carbon:analytics",
368
368
  label: "Маркетинговые исследования",
369
369
  "#security": {
@@ -15,7 +15,7 @@ export class $class extends $folder{
15
15
  return this.DATA?.icon || 'odant:module';
16
16
  if (this.type === '$domain' && this.id === 'MODULES')
17
17
  return 'odant:folder';
18
- if (this.type === '$structure')
18
+ if (this.type === '$structure' || this.DATA?.isDepartment)
19
19
  return this.DATA?.icon || 'odant:structure';
20
20
  return this.DATA?.icon || 'bootstrap:database';
21
21
  },
package/sources/client.js CHANGED
@@ -5,6 +5,7 @@ import { Reactor } from "./reactor.js";
5
5
  import { RTCCaller } from "./modules/call/call.js";
6
6
  import "./modules/user-profile/user-profile.js";
7
7
  import "./modules/user-profile/user-token.js";
8
+ import "./modules/user-profile/user-tokens.js";
8
9
  window.RTCCaller = RTCCaller;
9
10
  class WORK_ServerError extends Error{}
10
11
  window.CORE = CORE;
@@ -437,53 +438,96 @@ WORK.login = async function(force = false){
437
438
  WORK.credentials = window.top.WORK.credentials;
438
439
  WORK.uid = window.top.WORK.uid || '';
439
440
  WORK.USER = window.top.WORK.USER;
441
+ WORK._loginError = null;
440
442
  return res;
441
443
  }
442
444
  }
443
- catch { /* cross-origin fallback */ }
445
+ catch (err) {
446
+ if (!err || err.name === 'SecurityError') { /* cross-origin fallback */ }
447
+ else {
448
+ WORK._loginError = err;
449
+ throw err;
450
+ }
451
+ }
444
452
  }
445
453
  if (!force && WORK._loginPromise && WORK._loginTargetUid === nextUid)
446
454
  return WORK._loginPromise;
447
455
  WORK._loginTargetUid = nextUid;
448
- return WORK._loginPromise = (async () => {
449
- WORK.credentials = nextCreds;
450
- let KEY = secure.getItem('KEY');
451
- let uid = WORK.credentials?.uid;
452
- if(uid && KEY){
453
- if (WORK.uid && WORK.uid !== uid)
456
+ WORK._loginError = null;
457
+ WORK._loginInProgress = true;
458
+ try {
459
+ WORK.authEvents?.dispatchEvent?.(new CustomEvent('login-state', { detail: { pending: true, error: null } }));
460
+ } catch {}
461
+ const run = (async () => {
462
+ try {
463
+ WORK.credentials = nextCreds;
464
+ let KEY = secure.getItem('KEY');
465
+ let uid = WORK.credentials?.uid;
466
+ if(uid && KEY){
467
+ if (WORK.uid && WORK.uid !== uid)
468
+ await WORK.removeCurrentPushSubscription?.();
469
+ let challengeId = crypto.randomUUID();
470
+ const challenge = await WORK.fetch("/", 'user_login_start', { uid, challengeId});
471
+ KEY = Uint8Array.from(atob(KEY), c => c.charCodeAt(0));
472
+ let privateKey = await crypto.subtle.importKey("pkcs8", KEY, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["sign"]);
473
+ let signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, privateKey, new TextEncoder().encode(challenge));
474
+ signature = WORK.arrayBufferToBase64(signature);
475
+ let pendingInviteToken = '';
476
+ try { pendingInviteToken = sessionStorage.getItem('work.pendingInviteToken') || ''; } catch { /* ignore */ }
477
+ const res = await WORK.fetch("/", 'user_login_finish' , { uid, time: WORK.credentials.time, challengeId}, {signature, ...(pendingInviteToken ? { inviteToken: pendingInviteToken } : {})});
478
+ if (pendingInviteToken) {
479
+ try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
480
+ }
481
+ const prevUid = WORK.uid || '';
482
+ const authChanged = !WORK._authNotifiedOnce || prevUid !== uid;
483
+ WORK.uid = uid;
484
+ WORK._loginError = null;
485
+ WORK._anonExitSynced = false;
486
+ if (authChanged || !WORK.USER)
487
+ await WORK.syncAuthUI();
488
+ WORK.refreshChatUnread?.();
489
+ if (authChanged) {
490
+ WORK._authNotifiedOnce = true;
491
+ WORK.notifyAuth?.({ uid, reason: 'login' });
492
+ }
493
+ return res;
494
+ }
495
+ const hadAuth = Boolean(WORK.uid);
496
+ const authChanged = !WORK._authNotifiedOnce || hadAuth;
497
+ if (WORK.uid)
454
498
  await WORK.removeCurrentPushSubscription?.();
455
- let challengeId = crypto.randomUUID();
456
- const challenge = await WORK.fetch("/", 'user_login_start', { uid, challengeId});
457
- KEY = Uint8Array.from(atob(KEY), c => c.charCodeAt(0));
458
- let privateKey = await crypto.subtle.importKey("pkcs8", KEY, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["sign"]);
459
- let signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, privateKey, new TextEncoder().encode(challenge));
460
- signature = WORK.arrayBufferToBase64(signature);
461
- let pendingInviteToken = '';
462
- try { pendingInviteToken = sessionStorage.getItem('work.pendingInviteToken') || ''; } catch { /* ignore */ }
463
- const res = await WORK.fetch("/", 'user_login_finish' , { uid, time: WORK.credentials.time, challengeId}, {signature, ...(pendingInviteToken ? { inviteToken: pendingInviteToken } : {})});
464
- if (pendingInviteToken) {
465
- try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
499
+ WORK.uid = '';
500
+ WORK._pushSyncedUid = '';
501
+ WORK._loginError = null;
502
+ WORK.USER = undefined;
503
+ WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
504
+ if (hadAuth || !WORK._anonExitSynced) {
505
+ WORK._anonExitSynced = true;
506
+ await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
466
507
  }
467
- WORK.uid = uid;
468
- WORK._anonExitSynced = false;
469
- await WORK.syncAuthUI();
470
- WORK.refreshChatUnread?.();
471
- WORK.notifyAuth?.({ uid, reason: 'login' });
472
- return res;
508
+ if (authChanged) {
509
+ await WORK.syncAuthUI();
510
+ WORK._authNotifiedOnce = true;
511
+ WORK.notifyAuth?.({ uid: '', reason: 'logout' });
512
+ }
513
+ }
514
+ catch (err) {
515
+ WORK._loginError = err;
516
+ if (WORK._loginPromise === run)
517
+ WORK._loginPromise = null;
518
+ throw err;
473
519
  }
474
- const hadAuth = Boolean(WORK.uid);
475
- if (WORK.uid)
476
- await WORK.removeCurrentPushSubscription?.();
477
- WORK.uid = '';
478
- WORK.USER = undefined;
479
- WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
480
- if (hadAuth || !WORK._anonExitSynced) {
481
- WORK._anonExitSynced = true;
482
- await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
520
+ finally {
521
+ WORK._loginInProgress = false;
522
+ try {
523
+ WORK.authEvents?.dispatchEvent?.(new CustomEvent('login-state', {
524
+ detail: { pending: false, error: WORK._loginError || null, uid: WORK.uid || '' }
525
+ }));
526
+ } catch {}
483
527
  }
484
- await WORK.syncAuthUI();
485
- WORK.notifyAuth?.({ uid: '', reason: 'logout' });
486
528
  })();
529
+ WORK._loginPromise = run;
530
+ return run;
487
531
  }
488
532
  WORK.applyChatReadLocal = function ({ threadId = '', kind = '', nodePath = '', peerId = '' } = {}) {
489
533
  const u = WORK.chatUnread;
@@ -608,7 +652,7 @@ class WebSocketEvents {
608
652
  onopen(e) {
609
653
  this.send(JSON.stringify(Object.keys(CORE.$item.ITEMS)));
610
654
  WORK.connected = true;
611
- WORK.login();
655
+ WORK.login().catch(() => {});
612
656
  }
613
657
  onclose(e) {
614
658
  WORK.connected = false;
@@ -791,16 +835,18 @@ if (WORK.top === window) {
791
835
  }
792
836
  // Даже действующую подписку привязываем к текущему uid после входа/рестарта.
793
837
  await WORK.storePushSubscription(subscription);
838
+ WORK._pushSyncedUid = WORK.uid;
794
839
  return true;
795
840
  }
796
841
  catch (err) { console.warn('[push] subscription', err); return false; }
797
842
  };
798
843
  setTimeout(() => {
799
- WORK.enableTaskNotifications(false);
844
+ if (WORK.uid && WORK._pushSyncedUid !== WORK.uid)
845
+ WORK.enableTaskNotifications(false);
800
846
  RTCCaller.init();
801
847
  }, 3000);
802
848
  WORK.authEvents?.addEventListener('auth', e => {
803
- if (e.detail?.uid)
849
+ if (e.detail?.uid && WORK._pushSyncedUid !== e.detail.uid)
804
850
  WORK.enableTaskNotifications(false);
805
851
  });
806
852
  }
@@ -144,7 +144,7 @@ function getDbSummary(db) {
144
144
  countFor(clsPath, clsType = '') {
145
145
  const cls = getClass(db, clsPath);
146
146
  const type = cls?.type || clsType;
147
- if (!type || type === '$project' || type === '$project' || type === '$structure' || type === '$domain')
147
+ if (!type || cls?.own?.isStructure || type === '$project' || type === '$structure' || type === '$domain')
148
148
  return 0;
149
149
  const key = `${type}:${cls?.cid || clsPath}`;
150
150
  if (subtreeCounts.has(key))
@@ -14,12 +14,13 @@ import fsp from 'node:fs/promises';
14
14
  import path from 'node:path';
15
15
  import { pathToFileURL } from 'node:url';
16
16
  import { tx } from './db.js';
17
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
17
18
 
18
19
  /** Типы прикладных классов данных. */
19
20
  export const DATA_TYPES = Object.freeze(['$catalog', '$virtual', '$struct', '$operation', '$account', '$register']);
20
21
 
21
22
  /** Типы классов орг-структуры (подразделения), проектов, доменов и модулей. */
22
- export const STRUCTURE_TYPES = Object.freeze(['$structure', '$project']);
23
+ export const STRUCTURE_TYPES = Object.freeze([...new Set(['$structure', '$project', ...structureSubtypesSync()])]);
23
24
  export const MODULE_TYPES = Object.freeze(['$module', '$provider', '$mcp']);
24
25
  export const DOMAIN_TYPES = Object.freeze(['$domain']);
25
26
 
@@ -20,6 +20,7 @@
20
20
  import { getClass, ancestors, descendants, isLeaf, classesGeneration } from './classes.js';
21
21
  import { compile, BUILTIN_FUNCTIONS } from './expr.js';
22
22
  import { formatFio } from './fio.js';
23
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
23
24
 
24
25
  /** Семейство типа класса: схема наследуется внутри семейства. */
25
26
  export const FAMILY = Object.freeze({
@@ -27,6 +28,7 @@ export const FAMILY = Object.freeze({
27
28
  $struct: 'struct',
28
29
  $operation: 'operation',
29
30
  $account: 'account', $register: 'account',
31
+ ...Object.fromEntries(structureSubtypesSync().map(t => [t, 'structure'])),
30
32
  $structure: 'structure', $project: 'structure',
31
33
  $module: 'module',
32
34
  });
@@ -306,7 +306,7 @@ export const authMethods = {
306
306
 
307
307
  let post = CORE.$class.toScript(credentials);
308
308
 
309
- let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK } });
309
+ let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK }, ignore_save_logs: true });
310
310
  let u = await this.$users;
311
311
  (await u.children)?.forEach?.(ch => ch.children = undefined);
312
312
  u.children = undefined;
@@ -378,12 +378,20 @@ export const authMethods = {
378
378
  const uid = String(rawUid || '').trim().toUpperCase();
379
379
  if (!UID_RE.test(uid))
380
380
  throw new Error("uid required");
381
- if (session.uid !== uid) {
381
+ const challengeKey = challengeId != null ? String(challengeId) : '';
382
+ if (session.uid === uid) {
383
+ if (challengeKey) {
384
+ const entry = pendingLogins.get(challengeKey);
385
+ if (entry?.uid === uid)
386
+ pendingLogins.delete(challengeKey);
387
+ }
388
+ }
389
+ else {
382
390
  let signature = params.post?.signature;
383
391
  if (!signature) throw new Error("login session break. Need signature.");
384
- const challengeEntry = pendingLogins.get(String(challengeId));
392
+ const challengeEntry = pendingLogins.get(challengeKey);
385
393
  if (!challengeEntry) throw new Error("login session break. Challenge expired or missing.");
386
- pendingLogins.delete(String(challengeId));
394
+ pendingLogins.delete(challengeKey);
387
395
  const challengeValue = challengeEntry.value ?? challengeEntry;
388
396
  if (!challengeEntry.expiresAt || Date.now() > challengeEntry.expiresAt)
389
397
  throw new Error("login session break. Challenge expired.");
@@ -477,6 +485,9 @@ export const authMethods = {
477
485
  }
478
486
  const affected = Object.values($server.sessions).filter(s => s.uid === uid);
479
487
  this.constructor.clearAllSessionsForUid(uid);
488
+ for (const [id, c] of pendingLogins)
489
+ if (c?.uid === uid)
490
+ pendingLogins.delete(id);
480
491
  const { time } = params.post || {};
481
492
  if (time)
482
493
  delete session[time];
@@ -276,23 +276,39 @@ export async function llmWithFallback(primaryPath, fallbackPaths = []) {
276
276
  };
277
277
  return adapter;
278
278
  }
279
- /** Первая доступная чат-модель в /MODULES/Модели (активная приоритетно), когда дефолтная модель отсутствует. */
280
- async function findFirstAvailableChatModel() {
279
+ const CLASSIFIER_MODEL_RE = /(классификатор|classifier|rerank|0\.6b)/i;
280
+
281
+ /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
282
+ export async function findFirstAvailableChatModel() {
281
283
  const root = await WORK.get_item('/MODULES/Модели').catch(() => null);
282
284
  let firstAny = '';
285
+ let firstActive = '';
286
+ let firstPrimary = '';
283
287
  for (const provider of (await root?.items) || []) {
288
+ await provider?.init?.catch?.(() => {});
289
+ if (provider?.DATA?.enabled === false)
290
+ continue;
284
291
  for (const m of (await provider.items) || []) {
285
- await m.init;
292
+ await m.init?.catch?.(() => {});
293
+ if (m?.DATA?.enabled === false)
294
+ continue;
286
295
  const caps = Array.isArray(m.capabilities) ? m.capabilities : String(m.capabilities || '').split(/[\s,]+/);
287
296
  if (!caps.includes('chat') || typeof m.streamChat !== 'function')
288
297
  continue;
298
+ const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
299
+ const name = String(m.id || m.DATA?.label || m.label || m.path || '');
300
+ const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
289
301
  if (!firstAny)
290
302
  firstAny = m.path;
291
- if ((m.aiActive ?? m.DATA?.aiActive) !== false)
303
+ if (active && !firstActive)
304
+ firstActive = m.path;
305
+ if (active && m.DATA?.default === true)
292
306
  return m.path;
307
+ if (isPrimary && !firstPrimary)
308
+ firstPrimary = m.path;
293
309
  }
294
310
  }
295
- return firstAny;
311
+ return firstPrimary || firstActive || firstAny;
296
312
  }
297
313
  /** Найти активную локальную модель в /MODULES/Модели/Local по capabilities (или id). */
298
314
  async function findActiveLocalModel({ caps = [], ids = [], method = '' } = {}) {
@@ -661,7 +677,7 @@ async function placeBlock(place, session, location, contextPath) {
661
677
  const label = place.DATA?.label || place.label || place.id || place.path || 'WORK';
662
678
  const cone = contextConeOf(contextPath || place.path);
663
679
  const pt = place.type;
664
- if (pt === '$structure') {
680
+ if (place.DATA?.isDepartment || pt === '$structure') {
665
681
  const orgName = cone?.[1] || '';
666
682
  lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник подразделения «${label}»${orgName ? ` (организация «${orgName}»)` : ''}, путь ${place.path}. Отвечай и действуй от первого лица этого подразделения.`);
667
683
  }