odant-work 1.0.40 → 1.0.42
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 +26 -26
- package/$server/$folder/$file/$task/class.js +3 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +33 -1
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +65 -1
- package/$server/$folder/lib/consultant/consultant.js +9 -0
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +156 -7
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +2 -2
- package/package.json +1 -1
- package/sources/data/progress.md +12 -0
- package/sources/modules/agent/loop.js +39 -4
- package/sources/modules/agent/permissions.js +271 -111
- package/sources/modules/agent/session.js +89 -2
- package/sources/modules/agent/system.js +10 -3
- package/sources/modules/agent/tools/chrome.js +25 -4
- package/sources/modules/agent/tools/desktop.js +184 -170
- package/sources/modules/agent/tools/dev/checks.js +160 -160
- package/sources/modules/agent/tools/dev/git.js +276 -276
- package/sources/modules/agent/tools/net.js +45 -45
- package/sources/modules/agent/tools/os-proc.js +179 -169
- package/sources/modules/agent/tools/services.js +280 -275
- package/sources/modules/trainer/halogen.js +402 -10
- package/sources/modules/trainer/index.js +83 -0
- package/sources/modules/trainer/local-engine.js +321 -55
- package/sources/modules/trainer/worker/local_infer_worker.py +34 -12
|
@@ -1,275 +1,280 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Внешний мир как инструменты:
|
|
3
|
-
* - web_search / web_fetch — через сервисы-коннекторы /SERVICES с capability search / методом fetch_url;
|
|
4
|
-
* - svc_* — методы SCHEMA сервисов (Weather, ArgoCD, …);
|
|
5
|
-
* - mcp_* — инструменты MCP-серверов (сервисы с полем mcp), список кэшируется.
|
|
6
|
-
* Реестр строится из дерева: новый сервис/MCP в /SERVICES — новые инструменты без кода.
|
|
7
|
-
*/
|
|
8
|
-
import { log } from '../log.js';
|
|
9
|
-
import { clip } from '../util.js';
|
|
10
|
-
import { urlCarriesData } from '../taint.js';
|
|
11
|
-
import { callAs } from './work.js';
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
const REGISTRY_TTL = 60_000;
|
|
15
|
-
const MCP_TOOLS_TTL = 10 * 60_000;
|
|
16
|
-
const MCP_LIST_TIMEOUT = 25_000;
|
|
17
|
-
const READ_NAME = /^(search|fetch|get|list|read|find|check|weather|forecast|lookup|query|describe|info)/i;
|
|
18
|
-
|
|
19
|
-
let registry = null;
|
|
20
|
-
let registryAt = 0;
|
|
21
|
-
const mcpCache = new Map();
|
|
22
|
-
|
|
23
|
-
/** Сервисы из /SERVICES (два уровня вложенности): { id, path, item, data }. */
|
|
24
|
-
export async function listServices(force = false) {
|
|
25
|
-
if (!force && registry && Date.now() - registryAt < REGISTRY_TTL)
|
|
26
|
-
return registry;
|
|
27
|
-
const out = [];
|
|
28
|
-
let root = null;
|
|
29
|
-
try {
|
|
30
|
-
root = await WORK.get_item('/SERVICES');
|
|
31
|
-
}
|
|
32
|
-
catch (e) { log.debug('services.list', e); /* нет каталога */ }
|
|
33
|
-
const walk = async (folder, level, prefix) => {
|
|
34
|
-
let kids;
|
|
35
|
-
try {
|
|
36
|
-
kids = (await folder.items) || [];
|
|
37
|
-
}
|
|
38
|
-
catch { return; }
|
|
39
|
-
for (const kid of kids) {
|
|
40
|
-
const id = kid.id || '';
|
|
41
|
-
if (!id || /^[$.#]/.test(id) || typeof kid.import !== 'function')
|
|
42
|
-
continue;
|
|
43
|
-
let data;
|
|
44
|
-
try {
|
|
45
|
-
data = await kid.import();
|
|
46
|
-
}
|
|
47
|
-
catch { continue; }
|
|
48
|
-
if (data && typeof data === 'object' && data.enabled !== false && (data.SCHEMA || data.mcp))
|
|
49
|
-
out.push({ id: prefix + id, path: kid.path, item: kid, data });
|
|
50
|
-
if (level < 2)
|
|
51
|
-
await walk(kid, level + 1, prefix + id + '.');
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
if (root)
|
|
55
|
-
await walk(root, 1, '');
|
|
56
|
-
registry = out;
|
|
57
|
-
registryAt = Date.now();
|
|
58
|
-
return out;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function resetServiceRegistry() {
|
|
62
|
-
registry = null;
|
|
63
|
-
mcpCache.clear();
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function toolId(...parts) {
|
|
67
|
-
return parts.join('_').replace(/[^a-zA-Z0-9_-]+/g, '_').replace(/_+/g, '_').slice(0, 64);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function caps(data) {
|
|
71
|
-
return Array.isArray(data?.capabilities)
|
|
72
|
-
? data.capabilities.map(String)
|
|
73
|
-
: String(data?.capabilities || '').split(/[\s,]+/).filter(Boolean);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function formatSearch(res) {
|
|
77
|
-
if (!res || typeof res !== 'object')
|
|
78
|
-
return String(res ?? '');
|
|
79
|
-
const lines = [];
|
|
80
|
-
if (res.abstract)
|
|
81
|
-
lines.push(res.abstract);
|
|
82
|
-
for (const r of res.results || []) {
|
|
83
|
-
if (typeof r === 'string') {
|
|
84
|
-
lines.push('- ' + r);
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
lines.push('- [' + (r.title || r.url) + '](' + (r.url || r.link || '') + ')' + (r.snippet || r.description ? '\n ' + clip(r.snippet || r.description, 400) : ''));
|
|
88
|
-
}
|
|
89
|
-
return (res.source ? 'Источник: ' + res.source + '\n' : '') + lines.join('\n');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Страница по публичному адресу (внутренняя сеть сервера — не для web_fetch: см. net_http у администратора). */
|
|
93
|
-
async function plainFetch(url, signal) {
|
|
94
|
-
if (signal?.aborted)
|
|
95
|
-
throw new Error('остановлено');
|
|
96
|
-
const { guardedGet } = await import('../../../host/net-guard.js');
|
|
97
|
-
const res = await guardedGet(url, {
|
|
98
|
-
maxBytes: 5 * 1024 * 1024,
|
|
99
|
-
signal,
|
|
100
|
-
timeoutMs: 20000,
|
|
101
|
-
headers: { 'user-agent': 'Mozilla/5.0 WORK-agent', accept: 'text/html,text/plain,application/json;q=0.9,*/*;q=0.5' },
|
|
102
|
-
});
|
|
103
|
-
if (res.status < 200 || res.status >= 300)
|
|
104
|
-
throw new Error('HTTP ' + res.status);
|
|
105
|
-
const type = String(res.headers['content-type'] || '');
|
|
106
|
-
const text = res.body.toString('utf-8');
|
|
107
|
-
if (!/html/i.test(type))
|
|
108
|
-
return text;
|
|
109
|
-
return text
|
|
110
|
-
.replace(/<(script|style|noscript|svg)[\s\S]*?<\/\1>/gi, ' ')
|
|
111
|
-
.replace(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_, h, t) => '[' + t.replace(/<[^>]+>/g, '').trim() + '](' + h + ')')
|
|
112
|
-
.replace(/<br\s*\/?>|<\/(p|div|li|h\d|tr)>/gi, '\n')
|
|
113
|
-
.replace(/<[^>]+>/g, ' ')
|
|
114
|
-
.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
115
|
-
.replace(/[ \t]+/g, ' ')
|
|
116
|
-
.replace(/\s*\n\s*/g, '\n')
|
|
117
|
-
.trim();
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export const webTools = [
|
|
121
|
-
{
|
|
122
|
-
name: 'web_search',
|
|
123
|
-
readonly: true,
|
|
124
|
-
untrusted: true,
|
|
125
|
-
description: 'Поиск в интернете. Возвращает ссылки с описаниями; содержимое страницы — web_fetch.',
|
|
126
|
-
parameters: {
|
|
127
|
-
type: 'object',
|
|
128
|
-
properties: { query: { type: 'string', description: 'Поисковый запрос' } },
|
|
129
|
-
required: ['query'],
|
|
130
|
-
},
|
|
131
|
-
async run(args, ctx) {
|
|
132
|
-
// сначала объявившие capability search, затем прочие с методом search
|
|
133
|
-
const services = (await listServices()).filter(s => s.data.SCHEMA?.search)
|
|
134
|
-
.sort((a, b) => Number(caps(b.data).includes('search')) - Number(caps(a.data).includes('search')));
|
|
135
|
-
if (!services.length)
|
|
136
|
-
throw new Error('нет поисковых сервисов в /SERVICES');
|
|
137
|
-
const errors = [];
|
|
138
|
-
for (const s of services) {
|
|
139
|
-
try {
|
|
140
|
-
const res = await callAs(s.item, 'search', { query: args.query }, ctx);
|
|
141
|
-
if (res?.error) {
|
|
142
|
-
errors.push(s.id + ': ' + res.error);
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (!res?.abstract && !(res?.results || []).length) {
|
|
146
|
-
errors.push(s.id + ': пусто');
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
return formatSearch({ source: s.id, ...res });
|
|
150
|
-
}
|
|
151
|
-
catch (e) {
|
|
152
|
-
errors.push(s.id + ': ' + String(e.message || e));
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return { error: 'поиск не дал результатов: ' + errors.join('; ') };
|
|
156
|
-
},
|
|
157
|
-
},
|
|
158
|
-
{
|
|
159
|
-
name: 'web_fetch',
|
|
160
|
-
planSafe: true, // чтение: в «Плане» и «auto» — сразу; readonly нельзя: данные в адресе — см. outbound
|
|
161
|
-
outbound: urlCarriesData, // адрес уносит данные контекста (длинные/текстовые параметры) — с подтверждения (8.2)
|
|
162
|
-
untrusted: true,
|
|
163
|
-
description: 'Прочитать веб-страницу по URL: текст со ссылками [текст](url). Если в адресе есть данные (длинные или текстовые параметры) — попрошу подтверждение.',
|
|
164
|
-
parameters: {
|
|
165
|
-
type: 'object',
|
|
166
|
-
properties: { url: { type: 'string', description: 'Полный http(s) URL' } },
|
|
167
|
-
required: ['url'],
|
|
168
|
-
},
|
|
169
|
-
async run(args, ctx) {
|
|
170
|
-
const url = String(args.url || '').trim();
|
|
171
|
-
if (!/^https?:\/\//i.test(url))
|
|
172
|
-
throw new Error('нужен полный http(s) URL');
|
|
173
|
-
if (ctx.entry)
|
|
174
|
-
ctx.entry.url = url;
|
|
175
|
-
// URL проверяет закрепляющий IP транспорт, включая каждое перенаправление.
|
|
176
|
-
return clip(await plainFetch(url, ctx.signal), 30000);
|
|
177
|
-
},
|
|
178
|
-
},
|
|
179
|
-
];
|
|
180
|
-
|
|
181
|
-
/** svc_* — методы SCHEMA сервисов, кроме search/fetch_url (они в web_*). */
|
|
182
|
-
export async function serviceTools(session) {
|
|
183
|
-
const out = [];
|
|
184
|
-
for (const s of await listServices()) {
|
|
185
|
-
if (s.data.lanKind && (!session?.uid || session.principal?.kind === 'node' || !await s.item.canSee(s.item, { session })))
|
|
186
|
-
continue;
|
|
187
|
-
for (const [method, spec] of Object.entries(s.data.SCHEMA || {})) {
|
|
188
|
-
if (method === 'search' || method === 'fetch_url')
|
|
189
|
-
continue;
|
|
190
|
-
out.push({
|
|
191
|
-
name: toolId('svc', s.id, method),
|
|
192
|
-
readonly: spec?.readonly ?? READ_NAME.test(method),
|
|
193
|
-
untrusted: !s.data.lanKind, // ответ внешнего сервиса — чужой текст (taint.js); LAN-сервисы (1С, принтеры) — свои данные
|
|
194
|
-
outbound: !(spec?.readonly ?? READ_NAME.test(method)),
|
|
195
|
-
risk: (spec?.readonly ?? READ_NAME.test(method)) ? undefined : 'danger',
|
|
196
|
-
permission: s.data.lanKind && !(spec?.readonly ?? READ_NAME.test(method))
|
|
197
|
-
?
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
return
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
*
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Внешний мир как инструменты:
|
|
3
|
+
* - web_search / web_fetch — через сервисы-коннекторы /SERVICES с capability search / методом fetch_url;
|
|
4
|
+
* - svc_* — методы SCHEMA сервисов (Weather, ArgoCD, …);
|
|
5
|
+
* - mcp_* — инструменты MCP-серверов (сервисы с полем mcp), список кэшируется.
|
|
6
|
+
* Реестр строится из дерева: новый сервис/MCP в /SERVICES — новые инструменты без кода.
|
|
7
|
+
*/
|
|
8
|
+
import { log } from '../log.js';
|
|
9
|
+
import { clip } from '../util.js';
|
|
10
|
+
import { urlCarriesData } from '../taint.js';
|
|
11
|
+
import { callAs } from './work.js';
|
|
12
|
+
import { askScoped } from '../system.js';
|
|
13
|
+
|
|
14
|
+
const REGISTRY_TTL = 60_000;
|
|
15
|
+
const MCP_TOOLS_TTL = 10 * 60_000;
|
|
16
|
+
const MCP_LIST_TIMEOUT = 25_000;
|
|
17
|
+
const READ_NAME = /^(search|fetch|get|list|read|find|check|weather|forecast|lookup|query|describe|info)/i;
|
|
18
|
+
|
|
19
|
+
let registry = null;
|
|
20
|
+
let registryAt = 0;
|
|
21
|
+
const mcpCache = new Map();
|
|
22
|
+
|
|
23
|
+
/** Сервисы из /SERVICES (два уровня вложенности): { id, path, item, data }. */
|
|
24
|
+
export async function listServices(force = false) {
|
|
25
|
+
if (!force && registry && Date.now() - registryAt < REGISTRY_TTL)
|
|
26
|
+
return registry;
|
|
27
|
+
const out = [];
|
|
28
|
+
let root = null;
|
|
29
|
+
try {
|
|
30
|
+
root = await WORK.get_item('/SERVICES');
|
|
31
|
+
}
|
|
32
|
+
catch (e) { log.debug('services.list', e); /* нет каталога */ }
|
|
33
|
+
const walk = async (folder, level, prefix) => {
|
|
34
|
+
let kids;
|
|
35
|
+
try {
|
|
36
|
+
kids = (await folder.items) || [];
|
|
37
|
+
}
|
|
38
|
+
catch { return; }
|
|
39
|
+
for (const kid of kids) {
|
|
40
|
+
const id = kid.id || '';
|
|
41
|
+
if (!id || /^[$.#]/.test(id) || typeof kid.import !== 'function')
|
|
42
|
+
continue;
|
|
43
|
+
let data;
|
|
44
|
+
try {
|
|
45
|
+
data = await kid.import();
|
|
46
|
+
}
|
|
47
|
+
catch { continue; }
|
|
48
|
+
if (data && typeof data === 'object' && data.enabled !== false && (data.SCHEMA || data.mcp))
|
|
49
|
+
out.push({ id: prefix + id, path: kid.path, item: kid, data });
|
|
50
|
+
if (level < 2)
|
|
51
|
+
await walk(kid, level + 1, prefix + id + '.');
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
if (root)
|
|
55
|
+
await walk(root, 1, '');
|
|
56
|
+
registry = out;
|
|
57
|
+
registryAt = Date.now();
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function resetServiceRegistry() {
|
|
62
|
+
registry = null;
|
|
63
|
+
mcpCache.clear();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function toolId(...parts) {
|
|
67
|
+
return parts.join('_').replace(/[^a-zA-Z0-9_-]+/g, '_').replace(/_+/g, '_').slice(0, 64);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function caps(data) {
|
|
71
|
+
return Array.isArray(data?.capabilities)
|
|
72
|
+
? data.capabilities.map(String)
|
|
73
|
+
: String(data?.capabilities || '').split(/[\s,]+/).filter(Boolean);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function formatSearch(res) {
|
|
77
|
+
if (!res || typeof res !== 'object')
|
|
78
|
+
return String(res ?? '');
|
|
79
|
+
const lines = [];
|
|
80
|
+
if (res.abstract)
|
|
81
|
+
lines.push(res.abstract);
|
|
82
|
+
for (const r of res.results || []) {
|
|
83
|
+
if (typeof r === 'string') {
|
|
84
|
+
lines.push('- ' + r);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
lines.push('- [' + (r.title || r.url) + '](' + (r.url || r.link || '') + ')' + (r.snippet || r.description ? '\n ' + clip(r.snippet || r.description, 400) : ''));
|
|
88
|
+
}
|
|
89
|
+
return (res.source ? 'Источник: ' + res.source + '\n' : '') + lines.join('\n');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Страница по публичному адресу (внутренняя сеть сервера — не для web_fetch: см. net_http у администратора). */
|
|
93
|
+
async function plainFetch(url, signal) {
|
|
94
|
+
if (signal?.aborted)
|
|
95
|
+
throw new Error('остановлено');
|
|
96
|
+
const { guardedGet } = await import('../../../host/net-guard.js');
|
|
97
|
+
const res = await guardedGet(url, {
|
|
98
|
+
maxBytes: 5 * 1024 * 1024,
|
|
99
|
+
signal,
|
|
100
|
+
timeoutMs: 20000,
|
|
101
|
+
headers: { 'user-agent': 'Mozilla/5.0 WORK-agent', accept: 'text/html,text/plain,application/json;q=0.9,*/*;q=0.5' },
|
|
102
|
+
});
|
|
103
|
+
if (res.status < 200 || res.status >= 300)
|
|
104
|
+
throw new Error('HTTP ' + res.status);
|
|
105
|
+
const type = String(res.headers['content-type'] || '');
|
|
106
|
+
const text = res.body.toString('utf-8');
|
|
107
|
+
if (!/html/i.test(type))
|
|
108
|
+
return text;
|
|
109
|
+
return text
|
|
110
|
+
.replace(/<(script|style|noscript|svg)[\s\S]*?<\/\1>/gi, ' ')
|
|
111
|
+
.replace(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_, h, t) => '[' + t.replace(/<[^>]+>/g, '').trim() + '](' + h + ')')
|
|
112
|
+
.replace(/<br\s*\/?>|<\/(p|div|li|h\d|tr)>/gi, '\n')
|
|
113
|
+
.replace(/<[^>]+>/g, ' ')
|
|
114
|
+
.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
115
|
+
.replace(/[ \t]+/g, ' ')
|
|
116
|
+
.replace(/\s*\n\s*/g, '\n')
|
|
117
|
+
.trim();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const webTools = [
|
|
121
|
+
{
|
|
122
|
+
name: 'web_search',
|
|
123
|
+
readonly: true,
|
|
124
|
+
untrusted: true,
|
|
125
|
+
description: 'Поиск в интернете. Возвращает ссылки с описаниями; содержимое страницы — web_fetch.',
|
|
126
|
+
parameters: {
|
|
127
|
+
type: 'object',
|
|
128
|
+
properties: { query: { type: 'string', description: 'Поисковый запрос' } },
|
|
129
|
+
required: ['query'],
|
|
130
|
+
},
|
|
131
|
+
async run(args, ctx) {
|
|
132
|
+
// сначала объявившие capability search, затем прочие с методом search
|
|
133
|
+
const services = (await listServices()).filter(s => s.data.SCHEMA?.search)
|
|
134
|
+
.sort((a, b) => Number(caps(b.data).includes('search')) - Number(caps(a.data).includes('search')));
|
|
135
|
+
if (!services.length)
|
|
136
|
+
throw new Error('нет поисковых сервисов в /SERVICES');
|
|
137
|
+
const errors = [];
|
|
138
|
+
for (const s of services) {
|
|
139
|
+
try {
|
|
140
|
+
const res = await callAs(s.item, 'search', { query: args.query }, ctx);
|
|
141
|
+
if (res?.error) {
|
|
142
|
+
errors.push(s.id + ': ' + res.error);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (!res?.abstract && !(res?.results || []).length) {
|
|
146
|
+
errors.push(s.id + ': пусто');
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
return formatSearch({ source: s.id, ...res });
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
errors.push(s.id + ': ' + String(e.message || e));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { error: 'поиск не дал результатов: ' + errors.join('; ') };
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
name: 'web_fetch',
|
|
160
|
+
planSafe: true, // чтение: в «Плане» и «auto» — сразу; readonly нельзя: данные в адресе — см. outbound
|
|
161
|
+
outbound: urlCarriesData, // адрес уносит данные контекста (длинные/текстовые параметры) — с подтверждения (8.2)
|
|
162
|
+
untrusted: true,
|
|
163
|
+
description: 'Прочитать веб-страницу по URL: текст со ссылками [текст](url). Если в адресе есть данные (длинные или текстовые параметры) — попрошу подтверждение.',
|
|
164
|
+
parameters: {
|
|
165
|
+
type: 'object',
|
|
166
|
+
properties: { url: { type: 'string', description: 'Полный http(s) URL' } },
|
|
167
|
+
required: ['url'],
|
|
168
|
+
},
|
|
169
|
+
async run(args, ctx) {
|
|
170
|
+
const url = String(args.url || '').trim();
|
|
171
|
+
if (!/^https?:\/\//i.test(url))
|
|
172
|
+
throw new Error('нужен полный http(s) URL');
|
|
173
|
+
if (ctx.entry)
|
|
174
|
+
ctx.entry.url = url;
|
|
175
|
+
// URL проверяет закрепляющий IP транспорт, включая каждое перенаправление.
|
|
176
|
+
return clip(await plainFetch(url, ctx.signal), 30000);
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
];
|
|
180
|
+
|
|
181
|
+
/** svc_* — методы SCHEMA сервисов, кроме search/fetch_url (они в web_*). */
|
|
182
|
+
export async function serviceTools(session) {
|
|
183
|
+
const out = [];
|
|
184
|
+
for (const s of await listServices()) {
|
|
185
|
+
if (s.data.lanKind && (!session?.uid || session.principal?.kind === 'node' || !await s.item.canSee(s.item, { session })))
|
|
186
|
+
continue;
|
|
187
|
+
for (const [method, spec] of Object.entries(s.data.SCHEMA || {})) {
|
|
188
|
+
if (method === 'search' || method === 'fetch_url')
|
|
189
|
+
continue;
|
|
190
|
+
out.push({
|
|
191
|
+
name: toolId('svc', s.id, method),
|
|
192
|
+
readonly: spec?.readonly ?? READ_NAME.test(method),
|
|
193
|
+
untrusted: !s.data.lanKind, // ответ внешнего сервиса — чужой текст (taint.js); LAN-сервисы (1С, принтеры) — свои данные
|
|
194
|
+
outbound: !(spec?.readonly ?? READ_NAME.test(method)),
|
|
195
|
+
risk: (spec?.readonly ?? READ_NAME.test(method)) ? undefined : 'danger',
|
|
196
|
+
permission: s.data.lanKind && !(spec?.readonly ?? READ_NAME.test(method))
|
|
197
|
+
? askScoped(() => (s.data.label || s.id) + ': ' + method) : undefined,
|
|
198
|
+
approvalScope: () => ({
|
|
199
|
+
key: 'svc:' + s.id,
|
|
200
|
+
label: 'действия LAN-сервиса «' + (s.data.label || s.id) + '» в этой задаче',
|
|
201
|
+
buttonLabel: 'Разрешить подобные',
|
|
202
|
+
}),
|
|
203
|
+
description: '[' + (s.data.label || s.id) + '] ' + String(spec?.description || method),
|
|
204
|
+
parameters: spec?.params && typeof spec.params === 'object' ? spec.params : { type: 'object', properties: {} },
|
|
205
|
+
source: { service: s.path, method },
|
|
206
|
+
async run(args, ctx) {
|
|
207
|
+
return callAs(s.item, method, args || {}, ctx);
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function withTimeout(promise, ms, label) {
|
|
216
|
+
let t;
|
|
217
|
+
return Promise.race([
|
|
218
|
+
promise.finally(() => clearTimeout(t)),
|
|
219
|
+
new Promise((_, rej) => { t = setTimeout(() => rej(new Error(label + ': таймаут ' + ms + 'мс')), ms); }),
|
|
220
|
+
]);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** mcp_* — инструменты всех MCP-серверов реестра (список кэшируется). Ошибки сервера → пропуск. */
|
|
224
|
+
export async function mcpTools({ onError } = {}) {
|
|
225
|
+
const out = [];
|
|
226
|
+
const services = (await listServices()).filter(s => s.data.mcp);
|
|
227
|
+
await Promise.all(services.map(async s => {
|
|
228
|
+
let cached = mcpCache.get(s.path);
|
|
229
|
+
if (!cached || Date.now() - cached.at > MCP_TOOLS_TTL) {
|
|
230
|
+
try {
|
|
231
|
+
const res = await withTimeout(s.item.mcp_list_tools(), MCP_LIST_TIMEOUT, 'mcp ' + s.id);
|
|
232
|
+
if (res?.error)
|
|
233
|
+
throw new Error(res.error);
|
|
234
|
+
cached = { at: Date.now(), tools: res?.tools || [] };
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
cached = { at: Date.now(), tools: [], error: String(e.message || e) };
|
|
238
|
+
onError?.(s, e);
|
|
239
|
+
}
|
|
240
|
+
mcpCache.set(s.path, cached);
|
|
241
|
+
}
|
|
242
|
+
for (const t of cached.tools) {
|
|
243
|
+
if (!t?.name)
|
|
244
|
+
continue;
|
|
245
|
+
out.push(mcpToolDef(s, t));
|
|
246
|
+
}
|
|
247
|
+
}));
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Инструмент из декларации MCP-сервера (F17, final 8.10): чужой сервер не решает,
|
|
253
|
+
* что «только чтение» — readOnlyHint это заявка автора кода, который мы не контролируем,
|
|
254
|
+
* а readonly обходит даже подтверждения заражённого хода. Вызов чужого кода — всегда
|
|
255
|
+
* «наружу» (outbound): в заражённом ходе человек подтверждает, destructiveHint — danger.
|
|
256
|
+
* @param {{id:string, path:string, data:object, item:object}} s сервис
|
|
257
|
+
* @param {{name:string, description?:string, inputSchema?:object, annotations?:object}} t декларация
|
|
258
|
+
*/
|
|
259
|
+
export function mcpToolDef(s, t) {
|
|
260
|
+
const ro = t.annotations?.readOnlyHint === true; // подсказка — только в описании, не в правах
|
|
261
|
+
return {
|
|
262
|
+
name: toolId('mcp', s.id, t.name),
|
|
263
|
+
untrusted: true, // ответ MCP-сервера — чужой текст (taint.js)
|
|
264
|
+
outbound: true, // вызов чужого кода — действие наружу
|
|
265
|
+
risk: t.annotations?.destructiveHint ? 'danger' : 'write',
|
|
266
|
+
description: '[MCP ' + (s.data.label || s.id) + ']'
|
|
267
|
+
+ (ro ? ' (читающий, по заявлению сервера)' : '') + ' '
|
|
268
|
+
+ String(t.description || t.name).slice(0, 1000),
|
|
269
|
+
parameters: t.inputSchema && typeof t.inputSchema === 'object' ? t.inputSchema : { type: 'object', properties: {} },
|
|
270
|
+
source: { service: s.path, mcp: t.name },
|
|
271
|
+
async run(args, ctx) {
|
|
272
|
+
const res = await callAs(s.item, 'mcp_call_tool', { name: t.name, arguments: args || {} }, ctx);
|
|
273
|
+
if (res?.error)
|
|
274
|
+
return { error: String(res.error) };
|
|
275
|
+
const parts = (res?.content || []).map(c => c.type === 'text' ? c.text : (c.type === 'image' ? '[изображение ' + (c.mimeType || '') + ']' : JSON.stringify(c)));
|
|
276
|
+
const text = parts.join('\n') || JSON.stringify(res?.structuredContent ?? res ?? '');
|
|
277
|
+
return res?.isError ? { error: text } : text;
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|