odant-work 1.0.20 → 1.0.21
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 +33 -20
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
- package/$server/$folder/lib/chat-item/chat-item.js +17 -1
- package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +408 -111
- package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
- package/package.json +1 -1
- package/rules/threats.md +117 -116
- package/sources/client.js +1 -0
- package/sources/data/progress.md +11 -0
- package/sources/host/auto-updater.js +6 -2
- package/sources/host/http-server.js +23 -0
- package/sources/host/websocket.js +127 -120
- package/sources/modules/agent/index.js +6 -1
- package/sources/modules/agent/readme.md +217 -216
- package/sources/modules/agent/tools/chrome.js +263 -0
- package/sources/modules/bridge/chrome.js +673 -0
- package/sources/modules/bridge/hub.js +395 -361
- package/sources/modules/chrome-extension/background.js +299 -0
- package/sources/modules/chrome-extension/manifest.json +25 -0
- package/sources/modules/chrome-extension/options.html +48 -0
- package/sources/modules/chrome-extension/options.js +104 -0
- package/sources/modules/chrome-extension/popup.html +25 -0
- package/sources/modules/chrome-extension/popup.js +32 -0
- package/sources/modules/trainer/huggingface.js +412 -65
- package/sources/modules/trainer/index.js +288 -1
- package/sources/modules/trainer/tar-stream.js +458 -0
- package/sources/modules/trainer/transfer.js +1570 -0
- package/sources/modules/user-profile/user-profile.js +34 -10
- package/sources/modules/user-profile/user-token.js +168 -0
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Инструменты управления настоящим Chrome пользователя через расширение WORK Chrome Bridge:
|
|
3
|
+
* chrome_status — статус подключения расширения, режим «только просмотр» (readOnly), домены задачи и журнал;
|
|
4
|
+
* chrome_mode — переключить режим «только просмотр» (readOnly) с подтверждением человека;
|
|
5
|
+
* chrome_open — открыть http/https-адрес в собственной сгруппированной вкладке агента (с одобрением домена);
|
|
6
|
+
* chrome_snapshot — текстовый снимок страницы с пронумерованными элементами [ref] (работает и в readOnly);
|
|
7
|
+
* chrome_click — клик по [ref] (с подтверждением человека + проверка домена после перехода);
|
|
8
|
+
* chrome_type — ввод текста в поле [ref] (без паролей! Для паролей — chrome_handoff);
|
|
9
|
+
* chrome_nav — назад / вперёд / обновить (с подтверждением + проверка домена);
|
|
10
|
+
* chrome_handoff — передать управление человеку (вход, 2FA, капча, пароль) со скриншотом и вопросом.
|
|
11
|
+
*
|
|
12
|
+
* Безопасность:
|
|
13
|
+
* - Видимы ТОЛЬКО когда расширение Chrome подключено для текущего пользователя (uid);
|
|
14
|
+
* - Режим «только просмотр» (`readOnly: true`) включён по умолчанию при каждом подключении;
|
|
15
|
+
* - Все изменяющие действия требуют отдельного подтверждения (`noAlways: true`);
|
|
16
|
+
* - Разрешённые домены привязаны только к текущей задаче (в памяти); редирект на чужой домен останавливается;
|
|
17
|
+
* - Пароли в `chrome_type` не передаются — используйте `chrome_handoff`;
|
|
18
|
+
* - Произвольный JS (`eval`) запрещён жёстко;
|
|
19
|
+
* - Все результаты страниц помечены `untrusted: true` (изоляция чужого содержимого, taint.js).
|
|
20
|
+
*/
|
|
21
|
+
import { randomBytes } from 'node:crypto';
|
|
22
|
+
import {
|
|
23
|
+
getChromeForUser, setChromeReadOnly, getChromeAllowedDomains,
|
|
24
|
+
isChromeDomainAllowed, hostnameOf,
|
|
25
|
+
chromeOpen, chromeSnapshot, chromeClick, chromeType, chromeNav, chromeScreenshot,
|
|
26
|
+
} from '../../bridge/chrome.js';
|
|
27
|
+
import { assertPageUrl } from './browse.js';
|
|
28
|
+
import { askEach } from '../system.js';
|
|
29
|
+
|
|
30
|
+
const hostScopes = new WeakMap();
|
|
31
|
+
|
|
32
|
+
function scopeKeyOf(ctx) {
|
|
33
|
+
if (ctx?.host && typeof ctx.host === 'object') {
|
|
34
|
+
let id = hostScopes.get(ctx.host);
|
|
35
|
+
if (!id) {
|
|
36
|
+
id = 'task-' + randomBytes(6).toString('hex');
|
|
37
|
+
hostScopes.set(ctx.host, id);
|
|
38
|
+
}
|
|
39
|
+
return id;
|
|
40
|
+
}
|
|
41
|
+
return String(ctx?.session?.id || 'default');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function uidOf(ctx) {
|
|
45
|
+
const uid = ctx?.session?.uid;
|
|
46
|
+
if (!uid)
|
|
47
|
+
throw new Error('Управление Chrome пользователя доступно после входа в систему.');
|
|
48
|
+
return String(uid);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Видимы в списке инструментов, только когда расширение Chrome подключено к WORK для этого uid. */
|
|
52
|
+
export function chromeBridgeAvailable(session) {
|
|
53
|
+
const uid = session?.uid;
|
|
54
|
+
return Boolean(uid && getChromeForUser(uid));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function fmtSnap(snap) {
|
|
58
|
+
if (!snap || typeof snap !== 'object')
|
|
59
|
+
return String(snap ?? '');
|
|
60
|
+
return snap.text || ('Страница: ' + (snap.title || '(без названия)') + ' — ' + (snap.url || ''));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const chromeTools = [
|
|
64
|
+
{
|
|
65
|
+
name: 'chrome_status',
|
|
66
|
+
readonly: true,
|
|
67
|
+
description: 'Состояние расширения WORK Chrome Bridge в вашем браузере: подключено ли, включён ли режим «только просмотр» (readOnly), открытая вкладка агента, разрешённые в этой задаче домены и журнал последних действий.',
|
|
68
|
+
parameters: { type: 'object', properties: {} },
|
|
69
|
+
async run(_args, ctx) {
|
|
70
|
+
const uid = uidOf(ctx);
|
|
71
|
+
const conn = getChromeForUser(uid);
|
|
72
|
+
if (!conn)
|
|
73
|
+
return 'Расширение WORK Chrome Bridge не подключено.';
|
|
74
|
+
const domains = getChromeAllowedDomains(uid, scopeKeyOf(ctx));
|
|
75
|
+
const recent = conn.history.slice(-10).map(h =>
|
|
76
|
+
' ' + h.time.slice(11, 19) + ' ' + h.action
|
|
77
|
+
+ (h.domain ? ' (' + h.domain + ')' : '')
|
|
78
|
+
+ (h.ref != null ? ' [' + h.ref + ']' : '')
|
|
79
|
+
+ ' → ' + h.outcome
|
|
80
|
+
).join('\n');
|
|
81
|
+
return 'Браузер: ' + conn.browserName + ' (расширение v' + conn.extensionVersion + ')\n'
|
|
82
|
+
+ 'Режим: ' + (conn.readOnly ? 'ТОЛЬКО ПРОСМОТР (readOnly — изменения запрещены)' : 'действия с подтверждением каждого шага') + '\n'
|
|
83
|
+
+ 'Вкладка агента: ' + (conn.tabId != null ? (conn.lastTitle || '(открыта)') + ' — ' + (conn.lastUrl || 'about:blank') : 'не открыта') + '\n'
|
|
84
|
+
+ 'Разрешённые домены задачи: ' + (domains.join(', ') || 'нет') + '\n'
|
|
85
|
+
+ 'Журнал Chrome-моста:\n' + (recent || ' (пусто)');
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'chrome_mode',
|
|
90
|
+
risk: 'write',
|
|
91
|
+
description: 'Включить или выключить режим «только просмотр» (readOnly) для вашего Chrome. В режиме readOnly=true агент может только снимать снимки (chrome_snapshot) и передавать экран человеку (chrome_handoff); любые открытия страниц, клики и ввод заблокированы.',
|
|
92
|
+
parameters: {
|
|
93
|
+
type: 'object',
|
|
94
|
+
properties: {
|
|
95
|
+
readOnly: { type: 'boolean', description: 'true — только просмотр; false — разрешить действия с подтверждением' },
|
|
96
|
+
},
|
|
97
|
+
required: ['readOnly'],
|
|
98
|
+
},
|
|
99
|
+
permission: askEach(args => args?.readOnly
|
|
100
|
+
? 'включить режим «только просмотр» для вашего Chrome'
|
|
101
|
+
: 'разрешить агенту действия в вашем Chrome (каждый клик и ввод всё равно потребует подтверждения)'),
|
|
102
|
+
async run(args, ctx) {
|
|
103
|
+
const r = setChromeReadOnly(uidOf(ctx), Boolean(args?.readOnly));
|
|
104
|
+
return 'Режим Chrome пользователя: ' + (r.readOnly ? 'только просмотр (readOnly)' : 'действия с подтверждением') + '.';
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: 'chrome_open',
|
|
109
|
+
risk: 'write',
|
|
110
|
+
outbound: true,
|
|
111
|
+
untrusted: true,
|
|
112
|
+
description: 'Открыть адрес http/https в собственной сгруппированной вкладке агента в вашем Chrome (чужие вкладки не трогаются). Возвращает текстовый снимок с [ref]. При первом обращении к домену спрашивает разрешение для этой задачи.',
|
|
113
|
+
parameters: {
|
|
114
|
+
type: 'object',
|
|
115
|
+
properties: {
|
|
116
|
+
url: { type: 'string', description: 'Адрес http:// или https://' },
|
|
117
|
+
},
|
|
118
|
+
required: ['url'],
|
|
119
|
+
},
|
|
120
|
+
permission(args, ctx) {
|
|
121
|
+
let host = '';
|
|
122
|
+
try {
|
|
123
|
+
host = hostnameOf(assertPageUrl(args?.url));
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
return { verdict: 'deny', reason: e.message };
|
|
127
|
+
}
|
|
128
|
+
const uid = ctx?.session?.uid;
|
|
129
|
+
if (uid && isChromeDomainAllowed(uid, scopeKeyOf(ctx), host))
|
|
130
|
+
return { verdict: 'allow' };
|
|
131
|
+
return {
|
|
132
|
+
verdict: 'ask',
|
|
133
|
+
noAlways: true,
|
|
134
|
+
reason: 'открыть сайт ' + host + ' в вашем Chrome и добавить домен в список разрешённых для этой задачи',
|
|
135
|
+
};
|
|
136
|
+
},
|
|
137
|
+
async run(args, ctx) {
|
|
138
|
+
const snap = await chromeOpen(uidOf(ctx), scopeKeyOf(ctx), args?.url);
|
|
139
|
+
return fmtSnap(snap);
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
name: 'chrome_snapshot',
|
|
144
|
+
readonly: true,
|
|
145
|
+
untrusted: true,
|
|
146
|
+
description: 'Текстовый снимок текущей вкладки агента в Chrome: заголовок, URL и интерактивные элементы с номерами [ref]. Работает и в режиме readOnly.',
|
|
147
|
+
parameters: { type: 'object', properties: {} },
|
|
148
|
+
async run(_args, ctx) {
|
|
149
|
+
const snap = await chromeSnapshot(uidOf(ctx));
|
|
150
|
+
return fmtSnap(snap);
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
name: 'chrome_click',
|
|
155
|
+
risk: 'danger',
|
|
156
|
+
outbound: true,
|
|
157
|
+
untrusted: true,
|
|
158
|
+
description: 'Клик по элементу [ref] из последнего chrome_snapshot. Требует подтверждения человека и отключённого readOnly. Если клик увёл вкладку на новый домен, агент остановится и попросит подтвердить его.',
|
|
159
|
+
parameters: {
|
|
160
|
+
type: 'object',
|
|
161
|
+
properties: {
|
|
162
|
+
ref: { type: 'integer', description: 'Номер элемента [ref] из chrome_snapshot' },
|
|
163
|
+
reason: { type: 'string', description: 'Что и зачем нажимаем (увидит человек при подтверждении)' },
|
|
164
|
+
},
|
|
165
|
+
required: ['ref'],
|
|
166
|
+
},
|
|
167
|
+
permission: askEach(args => (args?.reason ? args.reason + ' — ' : '') + 'клик по элементу [' + args?.ref + '] в вашем Chrome'),
|
|
168
|
+
async run(args, ctx) {
|
|
169
|
+
const r = await chromeClick(uidOf(ctx), scopeKeyOf(ctx), args?.ref);
|
|
170
|
+
return r.label + ' — проверьте результат новым chrome_snapshot.';
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
name: 'chrome_type',
|
|
175
|
+
risk: 'danger',
|
|
176
|
+
outbound: true,
|
|
177
|
+
untrusted: true,
|
|
178
|
+
description: 'Ввести текст в поле [ref] в вашем Chrome. Пароли, коды и секреты сюда передавать ЗАПРЕЩЕНО — для входа и паролей используйте chrome_handoff.',
|
|
179
|
+
parameters: {
|
|
180
|
+
type: 'object',
|
|
181
|
+
properties: {
|
|
182
|
+
ref: { type: 'integer', description: 'Номер поля [ref] из chrome_snapshot' },
|
|
183
|
+
text: { type: 'string', description: 'Обычный текст (НЕ пароль и НЕ токен)' },
|
|
184
|
+
submit: { type: 'boolean', description: 'Нажать Enter после ввода' },
|
|
185
|
+
reason: { type: 'string', description: 'Что и зачем вводим (увидит человек при подтверждении)' },
|
|
186
|
+
},
|
|
187
|
+
required: ['ref', 'text'],
|
|
188
|
+
},
|
|
189
|
+
permission: askEach(args => (args?.reason ? args.reason + ' — ' : '') + 'ввод текста в поле [' + args?.ref + '] в вашем Chrome'),
|
|
190
|
+
async run(args, ctx) {
|
|
191
|
+
const r = await chromeType(uidOf(ctx), scopeKeyOf(ctx), args?.ref, args?.text, Boolean(args?.submit));
|
|
192
|
+
return r.label + ' — проверьте результат новым chrome_snapshot.';
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
name: 'chrome_nav',
|
|
197
|
+
risk: 'write',
|
|
198
|
+
outbound: true,
|
|
199
|
+
untrusted: true,
|
|
200
|
+
description: 'Навигация во вкладке агента Chrome: назад (back), вперёд (forward) или обновить (reload).',
|
|
201
|
+
parameters: {
|
|
202
|
+
type: 'object',
|
|
203
|
+
properties: {
|
|
204
|
+
action: { type: 'string', enum: ['back', 'forward', 'reload'], description: 'Действие навигации' },
|
|
205
|
+
},
|
|
206
|
+
required: ['action'],
|
|
207
|
+
},
|
|
208
|
+
permission: askEach(args => 'навигация в вашем Chrome: ' + String(args?.action || 'reload')),
|
|
209
|
+
async run(args, ctx) {
|
|
210
|
+
const snap = await chromeNav(uidOf(ctx), scopeKeyOf(ctx), args?.action);
|
|
211
|
+
return fmtSnap(snap);
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
name: 'chrome_handoff',
|
|
216
|
+
risk: 'write',
|
|
217
|
+
description: 'Передать управление человеку в его Chrome (логин, пароль, 2FA, капча, оплата или подтверждение): прикладывает скриншот текущей вкладки и ждёт ответа человека.',
|
|
218
|
+
parameters: {
|
|
219
|
+
type: 'object',
|
|
220
|
+
properties: {
|
|
221
|
+
reason: { type: 'string', description: 'Что именно нужно сделать человеку в браузере' },
|
|
222
|
+
},
|
|
223
|
+
required: ['reason'],
|
|
224
|
+
},
|
|
225
|
+
async run(args, ctx) {
|
|
226
|
+
const uid = uidOf(ctx);
|
|
227
|
+
const conn = getChromeForUser(uid);
|
|
228
|
+
if (!conn)
|
|
229
|
+
throw new Error('Расширение WORK Chrome Bridge не подключено.');
|
|
230
|
+
const png = await chromeScreenshot(uid);
|
|
231
|
+
const host = ctx?.host;
|
|
232
|
+
const entry = ctx?.entry;
|
|
233
|
+
const turn = ctx?.turn;
|
|
234
|
+
if (typeof host?.wait !== 'function') {
|
|
235
|
+
return 'Человек недоступен (автономный запуск). Опиши, что нужно сделать в Chrome вручную.'
|
|
236
|
+
+ (png ? ' Скриншот приложен.' : '');
|
|
237
|
+
}
|
|
238
|
+
if (entry)
|
|
239
|
+
entry.status = 'waiting';
|
|
240
|
+
await host.save?.();
|
|
241
|
+
const res = await host.wait({
|
|
242
|
+
kind: 'question',
|
|
243
|
+
item: turn?.id,
|
|
244
|
+
call: entry?.id,
|
|
245
|
+
question: 'Ваш Chrome ждёт вас (' + (conn.lastUrl || 'вкладка агента') + '): '
|
|
246
|
+
+ (args?.reason || 'нужно ваше действие в браузере'),
|
|
247
|
+
}) || {};
|
|
248
|
+
if (entry)
|
|
249
|
+
entry.status = 'running';
|
|
250
|
+
const answer = String(res.content ?? res.answer ?? '').trim();
|
|
251
|
+
if (answer && entry)
|
|
252
|
+
entry.answer = answer;
|
|
253
|
+
const afterPng = await chromeScreenshot(uid);
|
|
254
|
+
const shot = afterPng || png;
|
|
255
|
+
const out = answer
|
|
256
|
+
? 'Ответ человека: ' + answer + ' (обновите chrome_snapshot, если страница изменилась).'
|
|
257
|
+
: 'Человек завершил шаг без текста — обновите chrome_snapshot.';
|
|
258
|
+
if (!shot)
|
|
259
|
+
return out;
|
|
260
|
+
return { text: out + ' Скриншот вкладки приложен.', images: [{ png: shot, label: 'вкладка Chrome после ответа человека' }] };
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
];
|