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
@@ -56,62 +56,72 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
56
56
  </div>
57
57
  <div vertical style="gap: 16px; align-items: center;">
58
58
  <div class="photo" vertical style="padding: 16px; border-radius: 50%;">
59
- <oda-icon :icon="photoIcon" round @tap="loadPhoto" style="border-radius: 50%; fill: white; color: white;" icon-size="180"></oda-icon>
59
+ <oda-icon :icon="photoIcon" round @tap="!isOtherUser && loadPhoto()" style="border-radius: 50%; fill: white; color: white;" icon-size="180"></oda-icon>
60
60
  </div>
61
- <input id="name" placeholder="Имя" ::value="params.name" name="name">
62
- <input id="surname" placeholder="Фамилия" ::value="params.surname" name="surname">
63
- <input id="patronymic" placeholder="Отчество" ::value="params.patronymic" name="patronymic">
64
- <input id="email" :disabled="isLogin || showCode" placeholder="Email" ::value="params.email" type="email" name="email" :error="!correctEmail" :success="correctEmail">
65
- <oda-otp-input ~if="showCode" center @complete="_onCode"></oda-otp-input>
66
- <button ~if="state.label && !showCode" center horizontal :disabled="!correctEmail" flex raised :class="state.class" @tap.stop.prevent="register_start" style="gap: 8px;align-items: center;">
61
+ <input id="name" :disabled="isOtherUser" placeholder="Имя" ::value="params.name" name="name">
62
+ <input id="surname" :disabled="isOtherUser" placeholder="Фамилия" ::value="params.surname" name="surname">
63
+ <input id="patronymic" :disabled="isOtherUser" placeholder="Отчество" ::value="params.patronymic" name="patronymic">
64
+ <input id="email" :disabled="isOtherUser || isLogin || showCode" placeholder="Email" ::value="params.email" type="email" name="email" :error="!correctEmail" :success="correctEmail">
65
+ <oda-otp-input ~if="!isOtherUser && showCode" center @complete="_onCode"></oda-otp-input>
66
+ <button ~if="!isOtherUser && state.label && !showCode" center horizontal :disabled="!correctEmail" flex raised :class="state.class" @tap.stop.prevent="register_start" style="gap: 8px;align-items: center;">
67
67
  <span>{{state.label}}</span>
68
68
  <oda-icon ~if="state.icon" :icon="state.icon"></oda-icon>
69
69
  </button>
70
- <div ~if="isLogin && state?.name === 'ok' && !showCode" vertical style="gap: 8px; width: 100%; border-top: 1px solid rgba(128,128,128,.3); padding-top: 12px; margin-top: 4px;">
71
- <div style="font-size: medium; font-weight: 600; text-align: center;">Подключения</div>
72
- <button center horizontal flex @tap.stop.prevent="mcp_token" title="Один токен для внешних ИИ-клиентов (MCP) и расширения WORK Chrome Bridge">
73
- <span>Токен для подключения</span>
74
- </button>
75
- <div style="font-size: small; text-align: center; opacity: 0.75; line-height: 1.35;">
76
- Этот же токен вместе с адресом WORK вводится в расширении <b>WORK Chrome Bridge</b> и MCP-клиентах.
77
- </div>
78
- <button center horizontal flex @tap.stop.prevent="mcp_list" title="Список токенов: срок жизни, последнее использование, отзыв по одному">
79
- <span>Список токенов…</span>
80
- </button>
81
- <div ~if="mcpList" vertical style="gap: 8px; width: 100%;">
82
- <div ~if="!mcpList.length" style="font-size: small; text-align: center;">токенов нет</div>
83
- <div ~for="mcpList" horizontal style="gap: 8px; align-items: center; justify-content: space-between; border: 1px solid gray; border-radius: 8px; padding: 4px 8px;">
84
- <span flex>{{$for.item.label}}{{$for.item.role ? ' (' + $for.item.role + ')' : ''}}</span>
85
- <span no-flex style="font-size: small;">{{$for.item.expired ? 'истёк' : 'до ' + fmtDate($for.item.expires)}} · был{{fmtDate($for.item.lastUsed)}}</span>
86
- <button no-flex style="height: 32px; font-size: medium;" @tap.stop.prevent="mcp_revoke_one($for.item.id)">Отозвать</button>
87
- </div>
88
- </div>
89
- <button center horizontal flex @tap.stop.prevent="mcp_revoke">
90
- <span>Отозвать все токены</span>
91
- </button>
92
- </div>
93
70
  </div>
94
71
  <div flex style="text-align: center;" ~html="state.legend"></div>
95
72
  <div flex style="text-align: center;" :error="!!error" @tap="fill_code">{{text}}</div>
96
73
  </div>
97
74
  `,
75
+ $item: {
76
+ $def: null,
77
+ set(n) {
78
+ this._syncFromItem(n);
79
+ }
80
+ },
98
81
  error: null,
99
82
  text: '',
83
+ isLoggingIn: false,
84
+ get isOtherUser() {
85
+ return Boolean(this.$item?.id && WORK?.uid && this.$item.id !== WORK.uid);
86
+ },
87
+ get hasKey() {
88
+ return Boolean(this.credentials?.uid && this.workSecure.getItem('KEY'));
89
+ },
100
90
  get state(){
101
- if(!this.isRegistered || this.error)
91
+ if (this.isOtherUser) {
92
+ const targetUid = this.$item?.id || this.params?.uid || '';
93
+ const enabled = this.$item?.DATA?.enabled !== false;
94
+ return {
95
+ name: 'other',
96
+ label: '',
97
+ legend: (targetUid ? ('uid: ' + targetUid) : '') + (enabled ? '' : ' · <b>Отключён</b>'),
98
+ class: 'info-invert'
99
+ };
100
+ }
101
+ const errMsg = String(this.error?.message || this.error || '');
102
+ const keyRejected = /user not registered|need publickey|login failed|challenge issued for another user/i.test(errMsg);
103
+ if(!this.isRegistered || !this.hasKey || keyRejected)
102
104
  return {
103
105
  name: 'unregistered',
104
106
  label: 'Register KEY',
105
107
  legend: 'Для входа в систему необходимо зарегистрировать ключ безопасности. <p>Ключ будет создан на Вашем устройстве, и привязан к адресу электронной почты.',
106
108
  class: 'success-invert'
107
109
  }
108
- if(!this.isLogin)
110
+ if(!this.isLogin) {
111
+ if (this.isLoggingIn)
112
+ return {
113
+ name: 'logging-in',
114
+ label: '',
115
+ legend: 'Выполняется вход в систему…',
116
+ class: 'info-invert'
117
+ }
109
118
  return {
110
- name: 'need-check',
111
- label: 'Check KEY',
112
- legend: 'Вы не вошли в систему, требуется проверка ключа.',
113
- class: 'error-invert'
119
+ name: 'need-login',
120
+ label: 'Войти',
121
+ legend: 'Для входа в систему нажмите «Войти».',
122
+ class: 'success-invert'
114
123
  }
124
+ }
115
125
  if(this.isChanged)
116
126
  return {
117
127
  name: 'changed',
@@ -194,8 +204,57 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
194
204
  },
195
205
 
196
206
  attached() {
197
- this.credentials = this.workSecure.getItem('credentials');
207
+ this._syncFromItem(this.$item);
198
208
  this._loadPendingInvite();
209
+ this._onAuthState = () => {
210
+ if (this.isOtherUser)
211
+ return;
212
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
213
+ if (WORK._loginError) {
214
+ this.error = WORK._loginError;
215
+ this.text = WORK._loginError?.message || String(WORK._loginError);
216
+ }
217
+ else if (this.isLogin) {
218
+ this.error = null;
219
+ this.text = '';
220
+ }
221
+ this.isLogin = undefined;
222
+ this.render?.();
223
+ };
224
+ WORK.authEvents?.addEventListener?.('auth', this._onAuthState);
225
+ WORK.authEvents?.addEventListener?.('login-state', this._onAuthState);
226
+ },
227
+ detached() {
228
+ if (this._onAuthState) {
229
+ WORK.authEvents?.removeEventListener?.('auth', this._onAuthState);
230
+ WORK.authEvents?.removeEventListener?.('login-state', this._onAuthState);
231
+ }
232
+ },
233
+ async _syncFromItem(item) {
234
+ if (item?.id && WORK?.uid && item.id !== WORK.uid) {
235
+ try { await item.init; } catch {}
236
+ const d = item.DATA || {};
237
+ this.credentials = null;
238
+ this.params = {
239
+ ...this.params,
240
+ uid: item.id,
241
+ name: d.name || '',
242
+ surname: d.surname || '',
243
+ patronymic: d.patronymic || '',
244
+ email: d.email || '',
245
+ icon: item.icon || d.icon || '',
246
+ };
247
+ this.error = null;
248
+ this.text = '';
249
+ this.showCode = false;
250
+ return;
251
+ }
252
+ this.credentials = this.workSecure.getItem('credentials');
253
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
254
+ if (WORK._loginError) {
255
+ this.error = WORK._loginError;
256
+ this.text = WORK._loginError?.message || String(WORK._loginError);
257
+ }
199
258
  },
200
259
  pendingInvite: null,
201
260
  pendingInviteToken: '',
@@ -255,78 +314,12 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
255
314
  },
256
315
  reg: null,
257
316
  showCode: false,
258
- mcpList: null,
259
- fmtDate(ms) {
260
- return ms ? new Date(ms).toLocaleDateString() : '—';
261
- },
262
- /** Список токенов MCP: подпись, срок жизни, последнее использование; каждый можно отозвать отдельно. */
263
- async mcp_list() {
264
- this.mcpList = this.mcpList ? null : await WORK.fetch('/', 'mcp_token_list', {}, {});
265
- },
266
- async mcp_revoke_one(id) {
267
- try {
268
- await WORK.showConfirm('Отозвать этот токен? Подключённый клиент перестанет работать.');
269
- }
270
- catch { return; }
271
- try {
272
- await WORK.fetch('/', 'mcp_token_revoke', {}, { id });
273
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
274
- }
275
- catch (e) {
276
- this.text = e.message;
277
- }
278
- },
279
317
  get workSecure() {
280
318
  return ODA.LocalStorage.create('work-secure');
281
319
  },
282
- /** Токен подключения (MCP и WORK Chrome Bridge): выпускается вошедшим пользователем, показывается один раз. */
283
- async mcp_token() {
284
- try {
285
- await WORK.showConfirm('Выпустить персональный токен для подключения (WORK Chrome Bridge, OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
286
- }
287
- catch { return; }
288
- try {
289
- const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'Подключение (MCP / Chrome)' });
290
- if (this.mcpList)
291
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
292
- if (typeof WORK.showModal === 'function') {
293
- const dlg = ODA.createComponent('user-token', {
294
- token: r.token,
295
- origin: location.origin,
296
- });
297
- try {
298
- await WORK.showModal(dlg, {
299
- TITLE: { label: 'Токен подключения' },
300
- allowClose: true,
301
- BUTTONS: [],
302
- });
303
- }
304
- catch { /* закрыли окно */ }
305
- }
306
- else {
307
- prompt('Токен подключения — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '\nАдрес MCP: ' + location.origin + '/mcp', r.token);
308
- }
309
- }
310
- catch (e) {
311
- this.text = e.message;
312
- }
313
- },
314
- async mcp_revoke() {
315
- try {
316
- await WORK.showConfirm('Отозвать все токены подключения? Подключённые внешние клиенты и Chrome Bridge перестанут работать.');
317
- }
318
- catch { return; }
319
- try {
320
- const r = await WORK.fetch('/', 'mcp_token_revoke', {}, { all: true });
321
- if (this.mcpList)
322
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
323
- this.text = 'Токенов отозвано: ' + (r?.revoked ?? 0);
324
- }
325
- catch (e) {
326
- this.text = e.message;
327
- }
328
- },
329
320
  async register_start(e) {
321
+ if (this.isOtherUser)
322
+ return false;
330
323
  this.params.uid = await this.uid;
331
324
  switch (this.state?.name) {
332
325
  case 'ok': {
@@ -338,14 +331,16 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
338
331
  WORK.USER = undefined;
339
332
  WORK.credentials = this.workSecure.setItem('credentials', this.params);
340
333
  this.workSecure.setItem('KEY', null);
334
+ this.workSecure.flush?.();
341
335
 
342
336
  location.reload();
343
337
  } break;
344
- case 'need-check': {
345
- this.check();
338
+ case 'need-login': {
339
+ await this.check(true);
346
340
  } break;
347
341
  case 'changed':
348
342
  case 'unregistered': {
343
+ this.error = null;
349
344
  try {
350
345
  const registrationId = globalThis.crypto?.randomUUID?.() || WORK.genGUID?.() || (Date.now().toString(36) + Math.random().toString(36).slice(2));
351
346
  const regPayload = { ...this.params, registrationId, ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}) };
@@ -364,7 +359,6 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
364
359
  }
365
360
  } break;
366
361
  }
367
- this.error = null;
368
362
  return true;
369
363
  },
370
364
  async _onCode(e) {
@@ -418,7 +412,8 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
418
412
  let privateKey = await window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
419
413
  privateKey = WORK.arrayBufferToBase64(privateKey);
420
414
  this.workSecure.setItem('KEY', privateKey);
421
- await this.check();
415
+ this.workSecure.flush?.();
416
+ await this.check(true);
422
417
  this.credentials = this.params;
423
418
  this.isLogin = undefined;
424
419
  }
@@ -428,14 +423,24 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
428
423
  this.text = e.message;
429
424
  }
430
425
  },
431
- check() {
432
- return WORK.login().then(res => {
426
+ async check(force = false) {
427
+ this.isLoggingIn = true;
428
+ this.error = null;
429
+ this.text = 'Выполняется вход в систему…';
430
+ try {
431
+ const res = await WORK.login(force);
433
432
  this.error = null;
434
- this.text = res;
435
- }).catch(e => {
433
+ this.text = res || '';
434
+ return res;
435
+ }
436
+ catch (e) {
436
437
  this.error = e;
437
- this.text = e.message;
438
- });
438
+ this.text = e?.message || String(e || '');
439
+ return null;
440
+ }
441
+ finally {
442
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
443
+ }
439
444
  }
440
445
  })
441
446
 
@@ -0,0 +1,185 @@
1
+ ODA({ is: 'user-tokens',
2
+ template: /* html */`
3
+ <style>
4
+ :host {
5
+ overflow: auto;
6
+ @apply --light;
7
+ @apply --vertical;
8
+ @apply --flex;
9
+ padding: 16px;
10
+ box-sizing: border-box;
11
+ }
12
+ .tokens-wrap {
13
+ gap: 12px;
14
+ width: min(520px, 100%);
15
+ align-self: center;
16
+ margin: 0 auto auto auto;
17
+ box-sizing: border-box;
18
+ }
19
+ button {
20
+ min-height: 40px;
21
+ padding: 8px 14px;
22
+ border-radius: 8px;
23
+ font-size: medium;
24
+ cursor: pointer;
25
+ max-width: 100%;
26
+ box-sizing: border-box;
27
+ }
28
+ .token-row {
29
+ gap: 8px;
30
+ align-items: center;
31
+ justify-content: space-between;
32
+ flex-wrap: wrap;
33
+ border: 1px solid rgba(128, 128, 128, 0.35);
34
+ border-radius: 8px;
35
+ padding: 8px 10px;
36
+ }
37
+ .hint {
38
+ font-size: small;
39
+ text-align: center;
40
+ opacity: 0.78;
41
+ line-height: 1.4;
42
+ }
43
+ .msg {
44
+ font-size: small;
45
+ text-align: center;
46
+ }
47
+ .msg[error] {
48
+ color: var(--error-color, #dc2626);
49
+ }
50
+ </style>
51
+ <div no-flex vertical class="tokens-wrap">
52
+ <div style="font-size: large; font-weight: 600; text-align: center;">Токены подключений</div>
53
+ <div class="hint">
54
+ Персональный токен используется вместе с адресом WORK в расширении <b>WORK Chrome Bridge</b> и внешних ИИ-клиентах (MCP).
55
+ </div>
56
+ <div ~if="!canManage" class="msg" error>
57
+ Управление токенами доступно только владельцу активной учётной записи.
58
+ </div>
59
+ <div ~if="canManage" vertical style="gap: 10px; width: 100%;">
60
+ <button center horizontal flex class="success-invert" @tap.stop.prevent="mcp_token" title="Выпустить персональный токен для внешних ИИ-клиентов (MCP) и расширения WORK Chrome Bridge">
61
+ <span>Выпустить токен подключения</span>
62
+ </button>
63
+ <button center horizontal flex @tap.stop.prevent="mcp_list" title="Список токенов: срок жизни, последнее использование, отзыв по одному">
64
+ <span>{{mcpList ? 'Скрыть список токенов' : 'Список токенов…'}}</span>
65
+ </button>
66
+ <div ~if="mcpList" vertical style="gap: 8px; width: 100%;">
67
+ <div ~if="!mcpList.length" class="hint">Активных токенов нет</div>
68
+ <div ~for="mcpList" horizontal class="token-row">
69
+ <span flex>{{$for.item.label}}{{$for.item.role ? ' (' + $for.item.role + ')' : ''}}</span>
70
+ <span no-flex style="font-size: small; opacity: 0.8;">{{$for.item.expired ? 'истёк' : 'до ' + fmtDate($for.item.expires)}} · был {{fmtDate($for.item.lastUsed)}}</span>
71
+ <button no-flex style="min-height: 32px; font-size: small;" @tap.stop.prevent="mcp_revoke_one($for.item.id)">Отозвать</button>
72
+ </div>
73
+ </div>
74
+ <button center horizontal flex class="error-invert" @tap.stop.prevent="mcp_revoke">
75
+ <span>Отозвать все токены</span>
76
+ </button>
77
+ </div>
78
+ <div ~if="text" class="msg" :error="!!error">{{text}}</div>
79
+ </div>
80
+ `,
81
+ $item: null,
82
+ mcpList: null,
83
+ text: '',
84
+ error: false,
85
+ get canManage() {
86
+ if (!WORK?.uid)
87
+ return false;
88
+ if (this.$item?.id)
89
+ return this.$item.id === WORK.uid;
90
+ return true;
91
+ },
92
+ attached() {
93
+ this._onAuth = () => {
94
+ if (!this.canManage)
95
+ this.mcpList = null;
96
+ this.render?.();
97
+ };
98
+ WORK.authEvents?.addEventListener?.('auth', this._onAuth);
99
+ },
100
+ detached() {
101
+ if (this._onAuth)
102
+ WORK.authEvents?.removeEventListener?.('auth', this._onAuth);
103
+ },
104
+ fmtDate(ms) {
105
+ return ms ? new Date(ms).toLocaleDateString() : '—';
106
+ },
107
+ async mcp_list() {
108
+ this.error = false;
109
+ this.text = '';
110
+ try {
111
+ this.mcpList = this.mcpList ? null : await WORK.fetch('/', 'mcp_token_list', {}, {});
112
+ }
113
+ catch (e) {
114
+ this.error = true;
115
+ this.text = e?.message || String(e || '');
116
+ }
117
+ },
118
+ async mcp_revoke_one(id) {
119
+ try {
120
+ await WORK.showConfirm('Отозвать этот токен? Подключённый клиент перестанет работать.');
121
+ }
122
+ catch { return; }
123
+ this.error = false;
124
+ try {
125
+ await WORK.fetch('/', 'mcp_token_revoke', {}, { id });
126
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
127
+ this.text = 'Токен отозван';
128
+ }
129
+ catch (e) {
130
+ this.error = true;
131
+ this.text = e?.message || String(e || '');
132
+ }
133
+ },
134
+ async mcp_token() {
135
+ try {
136
+ await WORK.showConfirm('Выпустить персональный токен для подключения (WORK Chrome Bridge, OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
137
+ }
138
+ catch { return; }
139
+ this.error = false;
140
+ this.text = '';
141
+ try {
142
+ const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'Подключение (MCP / Chrome)' });
143
+ if (this.mcpList)
144
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
145
+ if (typeof WORK.showModal === 'function') {
146
+ const dlg = ODA.createComponent('user-token', {
147
+ token: r.token,
148
+ origin: location.origin,
149
+ });
150
+ try {
151
+ await WORK.showModal(dlg, {
152
+ TITLE: { label: 'Токен подключения' },
153
+ allowClose: true,
154
+ BUTTONS: [],
155
+ });
156
+ }
157
+ catch { /* закрыли окно */ }
158
+ }
159
+ else {
160
+ prompt('Токен подключения — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '\nАдрес MCP: ' + location.origin + '/mcp', r.token);
161
+ }
162
+ }
163
+ catch (e) {
164
+ this.error = true;
165
+ this.text = e?.message || String(e || '');
166
+ }
167
+ },
168
+ async mcp_revoke() {
169
+ try {
170
+ await WORK.showConfirm('Отозвать все токены подключения? Подключённые внешние клиенты и Chrome Bridge перестанут работать.');
171
+ }
172
+ catch { return; }
173
+ this.error = false;
174
+ try {
175
+ const r = await WORK.fetch('/', 'mcp_token_revoke', {}, { all: true });
176
+ if (this.mcpList)
177
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
178
+ this.text = 'Токенов отозвано: ' + (r?.revoked ?? 0);
179
+ }
180
+ catch (e) {
181
+ this.error = true;
182
+ this.text = e?.message || String(e || '');
183
+ }
184
+ },
185
+ });
@@ -46,7 +46,7 @@ export const MEMBERS = Object.freeze({
46
46
  mail_accounts: L.READ, mail_list: L.READ, mail_read: L.READ,
47
47
  mail_draft_save: L.WRITE, mail_send: L.WRITE, mail_state: L.WRITE, mail_refresh: L.WRITE,
48
48
  calendar_list: L.READ, calendar_save: L.WRITE,
49
- agent_rules_list: L.READ, agent_rule_save: L.BOSS, agent_schedule_save: L.BOSS, agent_proactivity_save: L.BOSS,
49
+ agent_rules_list: L.READ, agent_rule_save: L.BOSS, agent_schedule_save: L.BOSS, agent_proactivity_save: L.BOSS, agent_audit_run: L.BOSS,
50
50
  agent_system_get: L.READ, agent_system_save: L.BOSS, agent_available_classes: L.READ, agent_structures_list: L.READ, agent_network_nodes: L.READ, agent_staff_context: L.READ, agent_base_module_install: L.BOSS, agent_base_class_create: L.BOSS, agent_tasks_list: L.READ,
51
51
  security_update: L.BOSS,
52
52
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
@@ -65,13 +65,14 @@ export const MEMBERS = Object.freeze({
65
65
  types: L.READ, system_types: L.READ, allowed_child_types: L.READ,
66
66
  // вошедший
67
67
  proxy: L.AUTH, node_grants: L.AUTH, mcp_token_create: L.AUTH, mcp_token_list: L.AUTH, mcp_token_revoke: L.AUTH,
68
+ store_push_subscription: L.AUTH, remove_push_subscription: L.AUTH, agent_default_model: L.AUTH,
68
69
  // сеть WORK
69
70
  network_graph: L.READ, remote: L.WRITE, node_add: L.BOSS, node_refresh: L.BOSS,
70
71
  // запись (точное право — внутри метода)
71
72
  save_file: L.WRITE, save_files: L.WRITE, save_includes: L.WRITE, save_message: L.WRITE, office_save: L.WRITE,
72
73
  append_log_includes: L.WRITE, save: L.WRITE, edit: L.WRITE, edit_file: L.WRITE,
73
74
  ensure_folder: L.WRITE, create: L.WRITE, write_to_stream: L.WRITE, close_write_stream: L.WRITE,
74
- restore_from_history: L.WRITE, store_push_subscription: L.WRITE,
75
+ restore_from_history: L.WRITE,
75
76
  // учётное ядро (sources/data/api.js): точное право — внутри метода
76
77
  ...Object.fromEntries(Object.entries(DATA_METHODS).map(([name, m]) => [name, m.level])),
77
78
  // локальные модели Hugging Face и дообучение Unsloth (sources/modules/trainer/index.js)
@@ -86,7 +87,7 @@ export const MEMBERS = Object.freeze({
86
87
  ...Object.fromEntries(Object.entries(INVITE_METHODS).map(([name, m]) => [name, m.level])),
87
88
  // адресный классификатор РФ и подразделения МВД (sources/modules/kladr/index.js)
88
89
  ...Object.fromEntries(Object.entries(KLADR_METHODS).map(([name, m]) => [name, m.level])),
89
- remove_push_subscription: L.WRITE, send_push_notification: L.WRITE,
90
+ send_push_notification: L.WRITE,
90
91
  // администрирование
91
92
  delete: L.BOSS, npm: L.BOSS, restart_normal: L.BOSS, restart_server: L.BOSS, read_secret: L.BOSS,
92
93
  save_secret: L.BOSS, clear_rag: L.BOSS, security_log: L.BOSS, agent_panel: L.BOSS,
@@ -12,9 +12,11 @@ import { FS } from '../index.js';
12
12
  import { DEV_MODE } from '../../host/config.js';
13
13
  import * as POLICY from './policy.js';
14
14
  import * as WORKPLACES from './workplaces.js';
15
+ import { departmentMetaNameSync } from '../class/scaffold.js';
15
16
 
16
17
  /** Типы, на которые ссылки не действуют (структура видна по своим правилам). */
17
18
  export const NO_LINK_TYPES = new Set(['$structure', '$group', '$user', '$project', '$server']);
19
+ const isNoLinkNode = (cls) => NO_LINK_TYPES.has(cls?.type) || cls?.DATA?.isStructure === true;
18
20
 
19
21
  /** Имена метапапок, в которых лежит class.js подразделения. */
20
22
  const STRUCTURE_METAS = WORKPLACES.STRUCTURE_META_NAMES;
@@ -59,7 +61,8 @@ async function collectSets() {
59
61
  && (e.name !== 'DATA' && e.name !== 'INDEX' || rel.split('/').some(s => s.startsWith('$'))))
60
62
  continue;
61
63
  const sub = rel ? rel + '/' + e.name : e.name;
62
- if (STRUCTURE_METAS.includes(e.name)) {
64
+ const deptMeta = departmentMetaNameSync(root);
65
+ if (STRUCTURE_METAS.includes(e.name) || (deptMeta && e.name === deptMeta)) {
63
66
  const segs = rel.split('/').filter(Boolean);
64
67
  if (segs.some(s => s.startsWith('$')))
65
68
  continue;
@@ -146,7 +149,7 @@ function linkSubject(cls, params = {}) {
146
149
  * между разными ролями права объединяются по максимуму.
147
150
  */
148
151
  export async function linkLevel(cls, params = {}) {
149
- if (NO_LINK_TYPES.has(cls.type))
152
+ if (isNoLinkNode(cls))
150
153
  return null;
151
154
  const subject = linkSubject(cls, params);
152
155
  const seenStruct = new Map();
@@ -234,7 +237,7 @@ async function structureItem(path) {
234
237
  * Учитывает RWCD, переопределение вниз по дереву классов и исключения `deniedPaths` (`none` или понижение ниже `minAccess`).
235
238
  */
236
239
  export async function scopeLinks(cls, params = {}, minAccess = 'read') {
237
- if (NO_LINK_TYPES.has(cls.type))
240
+ if (isNoLinkNode(cls))
238
241
  return [];
239
242
  const subject = linkSubject(cls, params);
240
243
  const p = String(cls.path || '').replace(/\/+$/, '');
@@ -331,7 +334,7 @@ export async function scopeLinks(cls, params = {}, minAccess = 'read') {
331
334
  * но его DATA/INDEX/LOGS ссылки не открывают.
332
335
  */
333
336
  export async function grants(cls, item, params) {
334
- if (NO_LINK_TYPES.has(cls.type))
337
+ if (isNoLinkNode(cls))
335
338
  return false;
336
339
  const area = cls.areaOf(item).kind;
337
340
  try {
@@ -388,7 +391,7 @@ export async function isLinkAncestor(clsPath, params = {}, itemPath = null) {
388
391
 
389
392
  /** Запись в прикладной класс по ссылкам (уровень `write` и выше, или заданный `requiredLevel`). */
390
393
  export async function grantsWrite(cls, params, requiredLevel = 'write') {
391
- if (NO_LINK_TYPES.has(cls.type))
394
+ if (isNoLinkNode(cls))
392
395
  return false;
393
396
  try {
394
397
  const level = await linkLevel(cls, params);
@@ -403,7 +406,7 @@ export async function grantsWrite(cls, params, requiredLevel = 'write') {
403
406
  * пользователю как каркас дерева (SYSTEM/NESTED), не открывая чужие ветки и MODULES.
404
407
  */
405
408
  export async function isStructureAncestor(cls, item, params = {}) {
406
- if (!cls || !['$domain', '$project', '$structure'].includes(cls.type))
409
+ if (!cls || (!['$domain', '$project', '$structure'].includes(cls.type) && cls.DATA?.isStructure !== true))
407
410
  return false;
408
411
  if (item?.type === '$module' || (item?.type === '$domain' && item?.id === 'MODULES'))
409
412
  return false;
@@ -583,7 +583,7 @@ export async function visibleContacts(storage, params = {}) {
583
583
  const units = [base];
584
584
  const sub = await base.items?.catch?.(() => []) || [];
585
585
  for (const s of sub) {
586
- if (s?.type === '$structure')
586
+ if (s?.type === '$structure' || s?.DATA?.isDepartment)
587
587
  units.push(s);
588
588
  }
589
589
  let callerInBase = false;
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import * as fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import { ensureBaseModulesDomainSync, extractStubClassJsSync, scaffoldModuleTreeSync } from './scaffold.js';
9
+ import { ensureBaseModulesDomainSync, extractStubClassJsSync, scaffoldModuleTreeSync, departmentMetaNameSync } from './scaffold.js';
10
10
  import { scanModulesDirSync } from './module-status.js';
11
11
 
12
12
  export const BASE_TEMPLATE_PRESETS = Object.freeze([
@@ -594,8 +594,9 @@ export function scaffoldBaseOrganizationSync({
594
594
  }
595
595
 
596
596
  if (preset === 'standard' || preset === 'demo') {
597
+ const deptMeta = departmentMetaNameSync(process.cwd()) || '$structure';
597
598
  for (const dept of buildTemplateDepartments(orgId)) {
598
- const deptClassFile = path.join(targetDir, dept.id, '$structure', 'class.js');
599
+ const deptClassFile = path.join(targetDir, dept.id, deptMeta, 'class.js');
599
600
  if (!fs.existsSync(deptClassFile)) {
600
601
  fs.mkdirSync(path.dirname(deptClassFile), { recursive: true });
601
602
  fs.writeFileSync(deptClassFile, `export default ${JSON.stringify(dept.data, null, 4)}\n`, 'utf-8');