odant-work 1.0.20 → 1.0.22

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 (36) hide show
  1. package/#system/package-manifest.json +37 -24
  2. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
  3. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +58 -0
  4. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +2 -2
  5. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +2 -11
  6. package/$server/$folder/lib/chat-item/chat-item.js +17 -1
  7. package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
  8. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +408 -111
  9. package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
  10. package/logo.png +0 -0
  11. package/package.json +1 -1
  12. package/rules/threats.md +117 -116
  13. package/sources/client.js +1 -0
  14. package/sources/data/progress.md +15 -0
  15. package/sources/host/auto-updater.js +6 -2
  16. package/sources/host/http-server.js +23 -0
  17. package/sources/host/websocket.js +127 -120
  18. package/sources/modules/agent/index.js +6 -1
  19. package/sources/modules/agent/readme.md +217 -216
  20. package/sources/modules/agent/session.js +43 -8
  21. package/sources/modules/agent/tools/chrome.js +263 -0
  22. package/sources/modules/bridge/chrome.js +673 -0
  23. package/sources/modules/bridge/hub.js +395 -361
  24. package/sources/modules/chrome-extension/background.js +299 -0
  25. package/sources/modules/chrome-extension/manifest.json +25 -0
  26. package/sources/modules/chrome-extension/options.html +48 -0
  27. package/sources/modules/chrome-extension/options.js +104 -0
  28. package/sources/modules/chrome-extension/popup.html +25 -0
  29. package/sources/modules/chrome-extension/popup.js +32 -0
  30. package/sources/modules/trainer/huggingface.js +412 -65
  31. package/sources/modules/trainer/index.js +288 -1
  32. package/sources/modules/trainer/tar-stream.js +458 -0
  33. package/sources/modules/trainer/transfer.js +1570 -0
  34. package/sources/modules/user-profile/user-profile.js +34 -10
  35. package/sources/modules/user-profile/user-token.js +168 -0
  36. package/sw.js +85 -9
@@ -42,12 +42,16 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
42
42
  <span>{{state.label}}</span>
43
43
  <oda-icon ~if="state.icon" :icon="state.icon"></oda-icon>
44
44
  </button>
45
- <div ~if="isLogin && state?.name === 'ok' && !showCode" vertical style="gap: 8px; width: 100%;">
46
- <button center horizontal flex @tap.stop.prevent="mcp_token" title="Доступ к WORK для внешних ИИ-клиентов (OpenCode, Claude Code…) по MCP">
47
- <span>Токен для MCP</span>
45
+ <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;">
46
+ <div style="font-size: medium; font-weight: 600; text-align: center;">Подключения</div>
47
+ <button center horizontal flex @tap.stop.prevent="mcp_token" title="Один токен для внешних ИИ-клиентов (MCP) и расширения WORK Chrome Bridge">
48
+ <span>Токен для подключения</span>
48
49
  </button>
50
+ <div style="font-size: small; text-align: center; opacity: 0.75; line-height: 1.35;">
51
+ Этот же токен вместе с адресом WORK вводится в расширении <b>WORK Chrome Bridge</b> и MCP-клиентах.
52
+ </div>
49
53
  <button center horizontal flex @tap.stop.prevent="mcp_list" title="Список токенов: срок жизни, последнее использование, отзыв по одному">
50
- <span>Токены MCP…</span>
54
+ <span>Список токенов…</span>
51
55
  </button>
52
56
  <div ~if="mcpList" vertical style="gap: 8px; width: 100%;">
53
57
  <div ~if="!mcpList.length" style="font-size: small; text-align: center;">токенов нет</div>
@@ -58,7 +62,7 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
58
62
  </div>
59
63
  </div>
60
64
  <button center horizontal flex @tap.stop.prevent="mcp_revoke">
61
- <span>Отозвать токены MCP</span>
65
+ <span>Отозвать все токены</span>
62
66
  </button>
63
67
  </div>
64
68
  </div>
@@ -229,15 +233,33 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
229
233
  get workSecure() {
230
234
  return ODA.LocalStorage.create('work-secure');
231
235
  },
232
- /** Токен внешнего ИИ-клиента (modules/mcp): выпускается вошедшим пользователем, показывается один раз. */
236
+ /** Токен подключения (MCP и WORK Chrome Bridge): выпускается вошедшим пользователем, показывается один раз. */
233
237
  async mcp_token() {
234
238
  try {
235
- await WORK.showConfirm('Выпустить токен для внешнего ИИ-клиента (OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
239
+ await WORK.showConfirm('Выпустить персональный токен для подключения (WORK Chrome Bridge, OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
236
240
  }
237
241
  catch { return; }
238
242
  try {
239
- const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'MCP-клиент' });
240
- prompt('Токен MCP — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '/mcp', r.token);
243
+ const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'Подключение (MCP / Chrome)' });
244
+ if (this.mcpList)
245
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
246
+ if (typeof WORK.showModal === 'function') {
247
+ const dlg = ODA.createComponent('user-token', {
248
+ token: r.token,
249
+ origin: location.origin,
250
+ });
251
+ try {
252
+ await WORK.showModal(dlg, {
253
+ TITLE: { label: 'Токен подключения' },
254
+ allowClose: true,
255
+ BUTTONS: [],
256
+ });
257
+ }
258
+ catch { /* закрыли окно */ }
259
+ }
260
+ else {
261
+ prompt('Токен подключения — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '\nАдрес MCP: ' + location.origin + '/mcp', r.token);
262
+ }
241
263
  }
242
264
  catch (e) {
243
265
  this.text = e.message;
@@ -245,11 +267,13 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
245
267
  },
246
268
  async mcp_revoke() {
247
269
  try {
248
- await WORK.showConfirm('Отозвать все токены MCP? Подключённые внешние клиенты перестанут работать.');
270
+ await WORK.showConfirm('Отозвать все токены подключения? Подключённые внешние клиенты и Chrome Bridge перестанут работать.');
249
271
  }
250
272
  catch { return; }
251
273
  try {
252
274
  const r = await WORK.fetch('/', 'mcp_token_revoke', {}, { all: true });
275
+ if (this.mcpList)
276
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
253
277
  this.text = 'Токенов отозвано: ' + (r?.revoked ?? 0);
254
278
  }
255
279
  catch (e) {
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Модальное окно однократного показа выпущенного токена подключения (MCP и WORK Chrome Bridge).
3
+ * Отображается один раз после выпуска — повторно восстановить секрет из БД невозможно.
4
+ */
5
+ ODA({
6
+ is: 'user-token',
7
+ imports: 'oda//button',
8
+ template: /* html */`
9
+ <style>
10
+ :host {
11
+ @apply --vertical;
12
+ gap: 12px;
13
+ padding: 16px;
14
+ min-width: 340px;
15
+ max-width: 520px;
16
+ box-sizing: border-box;
17
+ @apply --light;
18
+ }
19
+ .warn {
20
+ padding: 10px 12px;
21
+ border-radius: 8px;
22
+ background: var(--accent-soft, #eff6ff);
23
+ border: 1px solid var(--border-color, #d1d5db);
24
+ font-size: 13px;
25
+ line-height: 1.45;
26
+ }
27
+ .field {
28
+ @apply --vertical;
29
+ gap: 4px;
30
+ }
31
+ .label {
32
+ font-size: 12px;
33
+ font-weight: 600;
34
+ opacity: 0.8;
35
+ }
36
+ .row {
37
+ @apply --horizontal;
38
+ gap: 8px;
39
+ align-items: stretch;
40
+ }
41
+ .val {
42
+ flex: 1;
43
+ min-width: 0;
44
+ padding: 8px 10px;
45
+ border-radius: 6px;
46
+ border: 1px solid var(--border-color, #d1d5db);
47
+ background: var(--subtle-background, #f8fafc);
48
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
49
+ font-size: 12.5px;
50
+ line-height: 1.4;
51
+ word-break: break-all;
52
+ user-select: all;
53
+ }
54
+ .copy-btn {
55
+ flex-shrink: 0;
56
+ padding: 0 12px;
57
+ border-radius: 6px;
58
+ border: 1px solid var(--border-color, #d1d5db);
59
+ background: var(--content, #fff);
60
+ cursor: pointer;
61
+ font-size: 12.5px;
62
+ white-space: nowrap;
63
+ }
64
+ .copy-btn.ok {
65
+ border-color: var(--success-color, #16a34a);
66
+ color: var(--success-color, #16a34a);
67
+ }
68
+ .hint {
69
+ font-size: 12px;
70
+ opacity: 0.75;
71
+ line-height: 1.4;
72
+ }
73
+ </style>
74
+ <div class="warn">
75
+ <strong>Сохраните токен сейчас.</strong> Он показывается только один раз.
76
+ Если потеряете — отзовите в профиле и выпустите новый.
77
+ </div>
78
+
79
+ <div class="field">
80
+ <div class="label">Персональный токен (для Chrome Bridge и MCP)</div>
81
+ <div class="row">
82
+ <div class="val">{{token}}</div>
83
+ <button class="copy-btn" :class="{ok: copied === 'token'}" @tap.stop="copy('token', token)">
84
+ {{copied === 'token' ? 'Скопировано' : 'Скопировать'}}
85
+ </button>
86
+ </div>
87
+ </div>
88
+
89
+ <div class="field">
90
+ <div class="label">Адрес сервера WORK (для расширения Chrome Bridge)</div>
91
+ <div class="row">
92
+ <div class="val">{{origin}}</div>
93
+ <button class="copy-btn" :class="{ok: copied === 'origin'}" @tap.stop="copy('origin', origin)">
94
+ {{copied === 'origin' ? 'Скопировано' : 'Скопировать'}}
95
+ </button>
96
+ </div>
97
+ </div>
98
+
99
+ <div class="field">
100
+ <div class="label">Адрес MCP-сервера (для OpenCode / Claude Code)</div>
101
+ <div class="row">
102
+ <div class="val">{{mcpUrl}}</div>
103
+ <button class="copy-btn" :class="{ok: copied === 'mcp'}" @tap.stop="copy('mcp', mcpUrl)">
104
+ {{copied === 'mcp' ? 'Скопировано' : 'Скопировать'}}
105
+ </button>
106
+ </div>
107
+ </div>
108
+
109
+ <div class="field">
110
+ <div class="label">Готовая строка для WORK Chrome Bridge (можно вставить целиком в поле токена)</div>
111
+ <div class="row">
112
+ <div class="val">{{bridgeJson}}</div>
113
+ <button class="copy-btn" :class="{ok: copied === 'json'}" @tap.stop="copy('json', bridgeJson)">
114
+ {{copied === 'json' ? 'Скопировано' : 'Скопировать'}}
115
+ </button>
116
+ </div>
117
+ </div>
118
+
119
+ <div class="hint">
120
+ В Chrome: иконка расширения <b>WORK Chrome Bridge</b> → <b>Настройки</b> → вставьте адрес и токен (или готовую строку) → <b>Сохранить и подключить</b>.
121
+ </div>
122
+ `,
123
+ token: '',
124
+ origin: '',
125
+ copied: '',
126
+ get mcpUrl() {
127
+ return (this.origin || location.origin) + '/mcp';
128
+ },
129
+ get bridgeJson() {
130
+ return JSON.stringify({
131
+ server: this.origin || location.origin,
132
+ token: this.token || '',
133
+ });
134
+ },
135
+ async copy(key, text) {
136
+ const val = String(text ?? '');
137
+ let ok = false;
138
+ try {
139
+ if (navigator.clipboard?.writeText) {
140
+ await navigator.clipboard.writeText(val);
141
+ ok = true;
142
+ }
143
+ }
144
+ catch { /* fallback ниже */ }
145
+ if (!ok && typeof document !== 'undefined') {
146
+ try {
147
+ const ta = document.createElement('textarea');
148
+ ta.value = val;
149
+ ta.setAttribute('readonly', '');
150
+ ta.style.position = 'fixed';
151
+ ta.style.opacity = '0';
152
+ document.body.appendChild(ta);
153
+ ta.select();
154
+ ok = document.execCommand('copy');
155
+ ta.remove();
156
+ }
157
+ catch { /* ignore */ }
158
+ }
159
+ if (ok) {
160
+ this.copied = key;
161
+ clearTimeout(this._copyTimer);
162
+ this._copyTimer = setTimeout(() => {
163
+ if (this.copied === key)
164
+ this.copied = '';
165
+ }, 2000);
166
+ }
167
+ },
168
+ });
package/sw.js CHANGED
@@ -127,6 +127,21 @@
127
127
  pushHandler.remove();
128
128
  }
129
129
  });
130
+ // Страница сообщает, что задача снова на экране (человек открыл/вернулся): уведомление
131
+ // по ней уже лишнее — закрываем, даже если оно висело с requireInteraction.
132
+ self.addEventListener('message', async (event) => {
133
+ const msg = event.data || {};
134
+ if (msg.type !== 'work:task-visible' || !msg.path)
135
+ return;
136
+ const tag = 'task:' + String(msg.path);
137
+ delete pushHandlers[tag];
138
+ try {
139
+ const list = await self.registration.getNotifications({ tag });
140
+ for (const n of list)
141
+ n.close();
142
+ }
143
+ catch { /* ignore */ }
144
+ });
130
145
 
131
146
  const OFFLINE_PAGE = `<!DOCTYPE html><html lang="ru"><head><meta charset="utf-8">
132
147
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -149,6 +164,44 @@ const OFFLINE_PAGE = `<!DOCTYPE html><html lang="ru"><head><meta charset="utf-8"
149
164
  <button onclick="location.reload()">Повторить</button>
150
165
  </div></body></html>`;
151
166
 
167
+ /**
168
+ * Задача прямо сейчас на экране у пользователя? Спрашиваем сами страницы: URL не всегда
169
+ * содержит путь задачи (в ленте чата карточка задачи разворачивается без смены адреса),
170
+ * поэтому видимая форма задачи отвечает `{ visible: true }`; молчание/таймаут — «нет».
171
+ * @param {string} taskPath путь задачи
172
+ * @param {Array<any>} wins окна WORK
173
+ */
174
+ async function taskOnScreen(taskPath, wins) {
175
+ if (!taskPath || !wins?.length)
176
+ return false;
177
+ if (typeof MessageChannel !== 'function' || typeof setTimeout !== 'function')
178
+ return false;
179
+ const ask = c => new Promise(resolve => {
180
+ if (typeof c?.postMessage !== 'function')
181
+ return resolve(false);
182
+ const ch = new MessageChannel();
183
+ let settled = false;
184
+ const done = v => {
185
+ if (settled)
186
+ return;
187
+ settled = true;
188
+ try { ch.port1.close(); } catch { /* ignore */ }
189
+ resolve(v);
190
+ };
191
+ const timer = setTimeout(() => done(false), 350);
192
+ ch.port1.onmessage = e => {
193
+ clearTimeout(timer);
194
+ done(!!e.data?.visible);
195
+ };
196
+ try { c.postMessage({ type: 'work:is-task-visible', path: taskPath }, [ch.port2]); }
197
+ catch {
198
+ clearTimeout(timer);
199
+ done(false);
200
+ }
201
+ });
202
+ return (await Promise.all(wins.map(ask))).some(Boolean);
203
+ }
204
+
152
205
  /**@param {{type: string, [key: string]: any}} data */
153
206
  async function handleNotification(data) { if (!(self.Notification && self.Notification.permission === "granted")) {
154
207
  return;
@@ -230,22 +283,45 @@ const OFFLINE_PAGE = `<!DOCTYPE html><html lang="ru"><head><meta charset="utf-8"
230
283
  }
231
284
  } break;
232
285
  default: {
233
- // Вопрос/разрешение/ошибка требуют внимания даже при открытой другой вкладке WORK.
234
- // Завершение подавляем только когда пользователь уже смотрит именно эту задачу.
286
+ // Пуш по задаче не нужен, если эта задача уже на экране (видимая вкладка показывает
287
+ // её в проводнике или отдельной страницей) — даже когда окно не в фокусе: человек
288
+ // видит запрос и так, а второй раз он только сбивает. Открытый и сфокусированный
289
+ // проводник WORK подавляет push целиком.
235
290
  if (String(data.type || '').startsWith('task:')) {
236
291
  const wins = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
292
+ let taskPath = String(data.data?.task || '').replace(/\/+$/, '');
293
+ try { taskPath = decodeURI(taskPath); } catch { /* как есть */ }
294
+ const clientPlace = c => {
295
+ try {
296
+ const u = new URL(c.url);
297
+ return decodeURI(u.pathname + u.hash);
298
+ }
299
+ catch { return c.url || ''; }
300
+ };
301
+ const showsTask = c => {
302
+ if (!taskPath || c.visibilityState !== 'visible')
303
+ return false;
304
+ const place = clientPlace(c);
305
+ const at = place.indexOf(taskPath);
306
+ if (at < 0)
307
+ return false;
308
+ // путь задачи целиком, а не префикс другой (…/1.task ≠ …/1.task2)
309
+ const next = place[at + taskPath.length];
310
+ return !next || '/#?'.includes(next);
311
+ };
312
+ if (wins.some(showsTask))
313
+ return;
314
+ // задача открыта в ленте чата/вкладкой — форма на экране отвечает сама
315
+ if (await taskOnScreen(taskPath, wins))
316
+ return;
237
317
  const target = data.data?.url && new URL(data.data.url, self.location.origin).pathname;
238
- const isViewingTask = c => {
318
+ const isViewingExplorer = c => {
239
319
  if (c.visibilityState !== 'visible' || !c.focused)
240
320
  return false;
241
321
  const p = new URL(c.url).pathname;
242
- if (target && p === target)
243
- return true;
244
- if (p === '/' || p === '/index.html' || p.startsWith('/~/handlers/pages/explorer'))
245
- return true;
246
- return false;
322
+ return p === target || p === '/' || p === '/index.html' || p.startsWith('/~/handlers/pages/explorer');
247
323
  };
248
- if (wins.some(isViewingTask))
324
+ if (wins.some(isViewingExplorer))
249
325
  return;
250
326
  // 9.7: ожидающее разрешение — кнопки «Разрешить/Отклонить» прямо в уведомлении:
251
327
  // подтверждение уходит на сервер (POST file?approve — те же права, что в интерфейсе),