odant-work 1.0.110 → 1.0.111
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/$server/$folder/$class/$ai/class.js +2 -0
- package/$server/$folder/$class/ai/system.md +1 -1
- package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +1 -2
- package/$server/$folder/$class/handlers/pages/form/system/folder/$handler/class.js +12 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +5 -1
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +75 -28
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +2 -2
- package/$server/$folder/handlers/readme.md +1 -1
- package/$server/$folder/lib/explorer/explorer.js +5 -2
- package/$server/$folder/lib/folder-browser/readme.md +1 -1
- package/AGENTS.md +1 -1
- package/package.json +1 -1
- package/sources/client.js +29 -10
- package/sources/host/auth-methods.js +1 -0
- package/sources/host/http-server.js +12 -0
- package/sources/host/websocket.js +42 -14
- package/sources/modules/agent/index.js +33 -10
- package/sources/modules/agent/loop.js +112 -35
- package/sources/modules/agent/session.js +6 -1
- package/sources/modules/agent/tools/sandbox.js +7 -7
- package/sources/modules/agent/tools/tool-groups.js +267 -0
- package/sources/modules/sandbox/config.js +1 -0
- package/sources/modules/sandbox/manager.js +50 -3
- package/sources/modules/sandbox/vnc-proxy.js +4 -3
- /package/$server/$folder/$class/$structure/$user/handlers/pages/form/{folder → system/folder}/$handler/class.js +0 -0
|
@@ -35,6 +35,7 @@ export class MovedError extends Error {
|
|
|
35
35
|
import { newNonce, wrapUntrusted, taintSources, untrustedNames } from './taint.js';
|
|
36
36
|
import { runPreTool, runAppend, runNotify } from './hooks.js';
|
|
37
37
|
import { costOf, recordUsage, budgetExceeded } from './cost.js';
|
|
38
|
+
import { collectActiveGroups, filterLazyTools, createToolsEnableTool } from './tools/tool-groups.js';
|
|
38
39
|
|
|
39
40
|
/** 9.5: самопроверка перед завершением — открытые пункты плана (todo_write). */
|
|
40
41
|
export const SELF_CHECK_NUDGE = '[Самопроверка] Перед завершением: в плане задачи остались незакрытые пункты';
|
|
@@ -180,13 +181,33 @@ async function notifyStop(opts, res) {
|
|
|
180
181
|
async function runLoopCore(opts) {
|
|
181
182
|
const { llm, items, host } = opts;
|
|
182
183
|
const maxTurns = opts.maxTurns ?? MAX_TURNS;
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
|
|
184
|
+
const lazy = Boolean(opts.lazyTools && !opts.depth);
|
|
185
|
+
const allTools = visibleTools(opts.tools || [], host.mode);
|
|
186
|
+
if (lazy && !allTools.some(t => t.name === 'tools_enable'))
|
|
187
|
+
allTools.unshift(createToolsEnableTool(() => allTools));
|
|
188
|
+
let activeGroups = lazy ? collectActiveGroups(items, opts.initialToolGroups) : null;
|
|
189
|
+
let tools = lazy ? filterLazyTools(allTools, activeGroups) : allTools;
|
|
190
|
+
let byName = new Map(tools.map(t => [t.name, t]));
|
|
191
|
+
let schemas = tools.map(toSchema);
|
|
192
|
+
let lastToolsSig = tools.map(t => t.name).join(',');
|
|
193
|
+
const syncLazyTools = () => {
|
|
194
|
+
if (!lazy)
|
|
195
|
+
return;
|
|
196
|
+
activeGroups = collectActiveGroups(items, opts.initialToolGroups);
|
|
197
|
+
const nextTools = filterLazyTools(allTools, activeGroups);
|
|
198
|
+
const sig = nextTools.map(t => t.name).join(',');
|
|
199
|
+
if (sig !== lastToolsSig) {
|
|
200
|
+
tools = nextTools;
|
|
201
|
+
byName = new Map(tools.map(t => [t.name, t]));
|
|
202
|
+
schemas = tools.map(toSchema);
|
|
203
|
+
lastToolsSig = sig;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
186
206
|
try {
|
|
187
207
|
// подтверждённые после рестарта вызовы последнего хода (и оставшиеся за ними pending) — исполнить до продолжения
|
|
188
208
|
const last = [...items].reverse().find(i => i.type === 'assistant');
|
|
189
209
|
if (last?.tools?.some(t => t.status === 'approved')) {
|
|
210
|
+
syncLazyTools();
|
|
190
211
|
for (const entry of last.tools) {
|
|
191
212
|
if (entry.status === 'approved')
|
|
192
213
|
await runOne({ entry, tool: byName.get(entry.name), it: last, host, llm, opts, preapproved: true });
|
|
@@ -199,6 +220,7 @@ async function runLoopCore(opts) {
|
|
|
199
220
|
let selfChecked = false; // 9.5: самопроверка — не чаще одного раза на задачу (без зацикливания)
|
|
200
221
|
for (let turn = 0; ; turn++) {
|
|
201
222
|
throwIfStopped(host.signal);
|
|
223
|
+
syncLazyTools();
|
|
202
224
|
if (turn >= maxTurns) {
|
|
203
225
|
items.push({ id: genId(), type: 'error', time: Date.now(), content: 'Лимит шагов (' + maxTurns + ') исчерпан. Напишите «продолжай», чтобы идти дальше.' });
|
|
204
226
|
await host.save();
|
|
@@ -213,7 +235,7 @@ async function runLoopCore(opts) {
|
|
|
213
235
|
return { status: 'limit' };
|
|
214
236
|
}
|
|
215
237
|
}
|
|
216
|
-
const system = typeof opts.system === 'function' ? await opts.system() : (opts.system ?? '');
|
|
238
|
+
const system = typeof opts.system === 'function' ? await opts.system(activeGroups) : (opts.system ?? '');
|
|
217
239
|
const toolsTokens = estimateTokens(schemas);
|
|
218
240
|
const compactLlm = typeof opts.ctx?.env?.compactLlm === 'function'
|
|
219
241
|
? await opts.ctx.env.compactLlm(llm.name).catch(() => llm)
|
|
@@ -505,16 +527,54 @@ export function createThinkSplitter(onContent, onReasoning) {
|
|
|
505
527
|
};
|
|
506
528
|
}
|
|
507
529
|
|
|
530
|
+
/**
|
|
531
|
+
* Сторожок деградации потока (локальные MoE-модели на длинном контексте иногда срываются в бесконечные
|
|
532
|
+
* эмодзи или зацикленный мусор вместо стоп-токена).
|
|
533
|
+
* Возвращает обрезанный текст до мусорного хвоста, если сработала деградация, иначе null.
|
|
534
|
+
*/
|
|
535
|
+
export function detectStreamDegeneration(text) {
|
|
536
|
+
const s = String(text || '');
|
|
537
|
+
if (s.length < 36)
|
|
538
|
+
return null;
|
|
539
|
+
// 1. Хвост из >= 18 подряд идущих пиктограмм/эмодзи (разделённых максимум пробелами/пунктуацией)
|
|
540
|
+
const emojiTail = s.match(/(?:\s*[\p{Extended_Pictographic}\uFE0F\u200D]){18,}\s*$/u);
|
|
541
|
+
if (emojiTail && typeof emojiTail.index === 'number')
|
|
542
|
+
return s.slice(0, emojiTail.index).replace(/\s+$/, '');
|
|
543
|
+
// 2. Один и тот же блок 8..120 символов, повторённый в хвосте >= 8 раз подряд
|
|
544
|
+
const repTail = s.match(/(.{8,120}?)\1{7,}\s*$/s);
|
|
545
|
+
if (repTail && typeof repTail.index === 'number')
|
|
546
|
+
return s.slice(0, repTail.index + repTail[1].length).replace(/\s+$/, '');
|
|
547
|
+
return null;
|
|
548
|
+
}
|
|
549
|
+
|
|
508
550
|
/** Один ход модели: стрим текста/рассуждения, ретраи до первого токена. */
|
|
509
551
|
async function streamTurn({ llm, host, it, messages, schemas, effort, halogenKeep, halogenFrom }) {
|
|
510
552
|
const t0 = Date.now();
|
|
511
553
|
for (let attempt = 0; ; attempt++) {
|
|
512
554
|
let calls = [];
|
|
513
555
|
let finish = null;
|
|
556
|
+
let degenerated = false;
|
|
557
|
+
const turnController = new AbortController();
|
|
558
|
+
const combinedSignal = host.signal
|
|
559
|
+
? (typeof AbortSignal?.any === 'function' ? AbortSignal.any([host.signal, turnController.signal]) : turnController.signal)
|
|
560
|
+
: turnController.signal;
|
|
561
|
+
const onHostAbort = () => {
|
|
562
|
+
try { turnController.abort(); } catch { /* ignore */ }
|
|
563
|
+
};
|
|
564
|
+
if (host.signal && combinedSignal === turnController.signal)
|
|
565
|
+
host.signal.addEventListener('abort', onHostAbort, { once: true });
|
|
514
566
|
const splitter = createThinkSplitter(
|
|
515
567
|
token => {
|
|
516
568
|
it.content += token;
|
|
517
569
|
host.emit?.({ type: 'delta', item: it.id, field: 'content', token });
|
|
570
|
+
if (!degenerated) {
|
|
571
|
+
const cleaned = detectStreamDegeneration(it.content);
|
|
572
|
+
if (cleaned !== null) {
|
|
573
|
+
degenerated = true;
|
|
574
|
+
it.content = cleaned;
|
|
575
|
+
try { turnController.abort(); } catch { /* ignore */ }
|
|
576
|
+
}
|
|
577
|
+
}
|
|
518
578
|
},
|
|
519
579
|
token => {
|
|
520
580
|
it.reasoning = (it.reasoning || '') + token;
|
|
@@ -522,39 +582,56 @@ async function streamTurn({ llm, host, it, messages, schemas, effort, halogenKee
|
|
|
522
582
|
}
|
|
523
583
|
);
|
|
524
584
|
try {
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
585
|
+
try {
|
|
586
|
+
for await (const ch of llm.stream({ messages, tools: schemas, signal: combinedSignal, effort, halogenKeep, halogenFrom })) {
|
|
587
|
+
if (host.signal?.aborted || degenerated)
|
|
588
|
+
break;
|
|
589
|
+
if (typeof ch === 'string') {
|
|
590
|
+
splitter.push(ch);
|
|
591
|
+
if (degenerated)
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
else if (ch?.type === 'reasoning') {
|
|
595
|
+
it.reasoning = (it.reasoning || '') + ch.content;
|
|
596
|
+
host.emit?.({ type: 'delta', item: it.id, field: 'reasoning', token: ch.content });
|
|
597
|
+
}
|
|
598
|
+
else if (ch?.type === 'tool_progress') {
|
|
599
|
+
host.emit?.({ type: 'delta', item: it.id, field: 'tool', name: ch.name, target: ch.target || '', chars: ch.chars || 0 });
|
|
600
|
+
}
|
|
601
|
+
else if (ch?.type === 'usage')
|
|
602
|
+
it.usage = {
|
|
603
|
+
prompt: ch.prompt_tokens, completion: ch.completion_tokens, total: ch.total_tokens,
|
|
604
|
+
...(ch.cached_tokens ? { cached: ch.cached_tokens } : {}),
|
|
605
|
+
...(ch.cache_creation_tokens ? { cacheWrite: ch.cache_creation_tokens } : {}),
|
|
606
|
+
...(ch.ttftMs ? { ttftMs: ch.ttftMs } : {}),
|
|
607
|
+
...(ch.tokPerSec ? { tokPerSec: ch.tokPerSec } : {}),
|
|
608
|
+
...(ch.promptTokPerSec ? { promptTokPerSec: ch.promptTokPerSec } : {}),
|
|
609
|
+
...(ch.timings ? { timings: ch.timings } : {}),
|
|
610
|
+
...(ch.halogen_from ? { halogenFrom: ch.halogen_from } : {}),
|
|
611
|
+
};
|
|
612
|
+
// подписанные блоки размышлений (Anthropic): без них следующий шаг цикла инструментов при включённом thinking — ошибка API
|
|
613
|
+
else if (ch?.type === 'thinking_blocks')
|
|
614
|
+
it.thinkingBlocks = ch.blocks;
|
|
615
|
+
else if (ch?.type === 'tool_calls')
|
|
616
|
+
calls = ch.calls || [];
|
|
617
|
+
else if (ch?.type === 'finish')
|
|
618
|
+
finish = ch;
|
|
537
619
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
...(ch.timings ? { timings: ch.timings } : {}),
|
|
547
|
-
...(ch.halogen_from ? { halogenFrom: ch.halogen_from } : {}),
|
|
548
|
-
};
|
|
549
|
-
// подписанные блоки размышлений (Anthropic): без них следующий шаг цикла инструментов при включённом thinking — ошибка API
|
|
550
|
-
else if (ch?.type === 'thinking_blocks')
|
|
551
|
-
it.thinkingBlocks = ch.blocks;
|
|
552
|
-
else if (ch?.type === 'tool_calls')
|
|
553
|
-
calls = ch.calls || [];
|
|
554
|
-
else if (ch?.type === 'finish')
|
|
555
|
-
finish = ch;
|
|
620
|
+
}
|
|
621
|
+
catch (streamErr) {
|
|
622
|
+
if (!degenerated)
|
|
623
|
+
throw streamErr;
|
|
624
|
+
}
|
|
625
|
+
finally {
|
|
626
|
+
if (host.signal && combinedSignal === turnController.signal)
|
|
627
|
+
host.signal.removeEventListener('abort', onHostAbort);
|
|
556
628
|
}
|
|
557
629
|
splitter.flush();
|
|
630
|
+
if (degenerated) {
|
|
631
|
+
const cleaned = detectStreamDegeneration(it.content);
|
|
632
|
+
if (cleaned !== null)
|
|
633
|
+
it.content = cleaned;
|
|
634
|
+
}
|
|
558
635
|
if (host.signal?.aborted) {
|
|
559
636
|
it.stopped = true;
|
|
560
637
|
throw new StopError();
|
|
@@ -562,7 +639,7 @@ async function streamTurn({ llm, host, it, messages, schemas, effort, halogenKee
|
|
|
562
639
|
if (finish?.reason)
|
|
563
640
|
it.finish = String(finish.reason);
|
|
564
641
|
// соединение закрылось без [DONE] и без finish_reason — обрыв, а не ответ
|
|
565
|
-
if (finish && !finish.done && !finish.reason && !calls.length && !it.content && !it.reasoning)
|
|
642
|
+
if (!degenerated && finish && !finish.done && !finish.reason && !calls.length && !it.content && !it.reasoning)
|
|
566
643
|
throw new Error('поток ответа оборвался');
|
|
567
644
|
it.content = stripThink(it.content).replace(/^\s+/, '').replace(/\s+$/, '');
|
|
568
645
|
it.durationMs = Date.now() - t0;
|
|
@@ -23,6 +23,7 @@ import path from 'node:path';
|
|
|
23
23
|
import { log } from './log.js';
|
|
24
24
|
import { runLoop, maybeCompact } from './loop.js';
|
|
25
25
|
import { createEnv, shouldEnforceAgentLicense } from './index.js';
|
|
26
|
+
import { inferInitialGroups } from './tools/tool-groups.js';
|
|
26
27
|
import { assertAgentSystemLicensed } from '../license/index.js';
|
|
27
28
|
import { genId } from './util.js';
|
|
28
29
|
import { collectUndo, applyUndo } from './undo.js';
|
|
@@ -616,13 +617,17 @@ function start(s, session, file, licenseOpts = {}) {
|
|
|
616
617
|
const model = picked?.path || rawModel;
|
|
617
618
|
body.model = model;
|
|
618
619
|
const llm = picked ? picked.llm : await env.llmFor(model); // 9.1: с запасными моделями (fallbackModels)
|
|
620
|
+
const lazyTools = !def;
|
|
621
|
+
const initialToolGroups = lazyTools ? inferInitialGroups({ place, contextPath: body.contextPath, items: body.items }) : undefined;
|
|
619
622
|
const res = await runLoop({
|
|
620
623
|
llm,
|
|
621
|
-
system: () => env.makeSystemParts(def, body.items),
|
|
624
|
+
system: (activeGroups) => env.makeSystemParts(def, body.items, { lazyTools, activeGroups }),
|
|
622
625
|
hooks: env.hooks,
|
|
623
626
|
items: body.items,
|
|
624
627
|
// R3 (8.31): ограничение call родителя из тела задачи (agent_start записал callRestrict)
|
|
625
628
|
tools: await env.makeTools(def, depth, undefined, body.callRestrict),
|
|
629
|
+
lazyTools,
|
|
630
|
+
initialToolGroups,
|
|
626
631
|
host,
|
|
627
632
|
depth,
|
|
628
633
|
ctx: { session, place, contextPath: body.contextPath, env, task: file, tz: body.tz, role: body.role },
|
|
@@ -9,7 +9,7 @@ import { loadSandboxConfig } from '../../sandbox/config.js';
|
|
|
9
9
|
import { getDocker, dockerAvailable } from '../../sandbox/driver.js';
|
|
10
10
|
import {
|
|
11
11
|
ownerOf, computerName, assertSandboxPath, ensureComputer, findComputer, listComputers,
|
|
12
|
-
execCommand, readText, writeText, readBytes,
|
|
12
|
+
execCommand, readText, writeText, readBytes, writeArchiveBytes, listDir, setNetwork, statusOf, destroyComputer,
|
|
13
13
|
touchComputer, formatExec,
|
|
14
14
|
} from '../../sandbox/manager.js';
|
|
15
15
|
import { getItem, writeBinary, absPath } from './work.js';
|
|
@@ -113,10 +113,10 @@ export const sandboxTools = [
|
|
|
113
113
|
outbound: a => !!a?.on,
|
|
114
114
|
permission: a => (a?.on
|
|
115
115
|
? { verdict: 'ask', noAlways: true, hideArgs: true,
|
|
116
|
-
reason: 'включить
|
|
116
|
+
reason: 'включить выход в интернет для изолированной песочницы Docker (чтобы устанавливать пакеты и открывать сайты)'
|
|
117
117
|
+ (a?.reason ? ': ' + a.reason : '') }
|
|
118
118
|
: { verdict: 'allow' }),
|
|
119
|
-
description: '
|
|
119
|
+
description: 'Выход в интернет для изолированной песочницы Docker (выключен по умолчанию; без него pip/npm/apt и сайты не работают). Включение — с подтверждением человека, выключение — сразу. Автоматически отключается через ' + ((Number(loadSandboxConfig().network?.ttlMin) || 0) || '∞') + ' мин.',
|
|
120
120
|
parameters: {
|
|
121
121
|
type: 'object',
|
|
122
122
|
properties: { ...NAME_PROP, on: { type: 'boolean', description: 'true — включить, false — выключить' }, reason: { type: 'string', description: 'Зачем нужен интернет — для подтверждения' } },
|
|
@@ -132,8 +132,8 @@ export const sandboxTools = [
|
|
|
132
132
|
},
|
|
133
133
|
{
|
|
134
134
|
name: 'computer_destroy',
|
|
135
|
-
permission: askEach(a => '
|
|
136
|
-
description: '
|
|
135
|
+
permission: askEach(a => 'сбросить и пересоздать Docker-песочницу «' + (a?.name || 'main') + '»' + (a?.owner ? ' пользователя ' + a.owner : '') + ' — контейнер и том с данными /workspace будут удалены (файлы внутри песочницы пропадут насовсем; файлы в WORK и на вашем ПК не затронуты)'),
|
|
136
|
+
description: 'Полностью сбросить Docker-песочницу вместе с её томом: файлы внутри /workspace пропадут насовсем (файлы WORK и ваш реальный ПК не затрагиваются), новая песочница создастся пустой. Сначала при необходимости заберите нужное через sandbox_read. Не вызывай без крайней необходимости.',
|
|
137
137
|
parameters: { type: 'object', properties: { ...NAME_PROP, owner: { type: 'string', description: 'Только админу: чей компьютер (uid)' } } },
|
|
138
138
|
run: ctxRun('computer_destroy', async (args, ctx) => {
|
|
139
139
|
const docker = await getDocker();
|
|
@@ -222,7 +222,7 @@ export const sandboxTools = [
|
|
|
222
222
|
{
|
|
223
223
|
name: 'sandbox_import',
|
|
224
224
|
risk: 'write',
|
|
225
|
-
description: 'Скопировать файл из дерева WORK
|
|
225
|
+
description: 'Скопировать файл из дерева WORK в песочницу (в /workspace). Читается с вашими правами; лимит размера — до 25 МБ.',
|
|
226
226
|
parameters: {
|
|
227
227
|
type: 'object',
|
|
228
228
|
properties: {
|
|
@@ -241,7 +241,7 @@ export const sandboxTools = [
|
|
|
241
241
|
const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data ?? ''));
|
|
242
242
|
if (!buf.length)
|
|
243
243
|
throw new Error('файл пуст или не читается: ' + args?.from);
|
|
244
|
-
return 'из WORK: ' + args.from + '\n' + await
|
|
244
|
+
return 'из WORK: ' + args.from + '\n' + await writeArchiveBytes(docker, pc.id, assertSandboxPath(args?.to, cfg.workdir), buf, cfg);
|
|
245
245
|
}),
|
|
246
246
|
},
|
|
247
247
|
{
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Группировка инструментов агента для отложенной подгрузки (Tool Discovery).
|
|
4
|
+
* Стартовый запрос к модели получает только компактное ядро (~21 инструмент) и
|
|
5
|
+
* мета-инструмент tools_enable — остальные группы подключаются по требованию
|
|
6
|
+
* (через tools_enable или автоматически по контексту места / текста сообщения).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const TOOL_GROUP_NAMES = Object.freeze([
|
|
10
|
+
'accounting',
|
|
11
|
+
'classes',
|
|
12
|
+
'work_extra',
|
|
13
|
+
'dev',
|
|
14
|
+
'docs',
|
|
15
|
+
'calendar_mail',
|
|
16
|
+
'twin',
|
|
17
|
+
'agents',
|
|
18
|
+
'connect',
|
|
19
|
+
'computer',
|
|
20
|
+
'browser',
|
|
21
|
+
'desktop',
|
|
22
|
+
'chrome',
|
|
23
|
+
'os',
|
|
24
|
+
'services',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const GROUP_DESCRIPTIONS = {
|
|
28
|
+
accounting: 'бухгалтерия и данные организации (describe_class, find_objects, register_operation, report)',
|
|
29
|
+
classes: 'создание/изменение классов и таблиц (create_class, update_class, inspect_class_tree, move_class, delete_class, write_table)',
|
|
30
|
+
work_extra: 'история/откат/назначения WORK (append, history, restore, send, assign, escalate)',
|
|
31
|
+
dev: 'разработка кода, поиск grep/glob, git, патчи, тесты и ветки (grep, glob, apply_patch, run_checks, git_*, lsp_*, branch)',
|
|
32
|
+
docs: 'таблицы/офисные документы/PDF/презентации (read_table, import_objects, render_doc, export_pdf, export_presentation, create_office_file)',
|
|
33
|
+
calendar_mail: 'календарь и почта (calendar_*, mail_*)',
|
|
34
|
+
twin: 'цифровой двойник и правила (twin_*)',
|
|
35
|
+
agents: 'расписание, фоновые агенты, публикация, навыки, изображения (agent_start/status/message/stop, schedule, plugin, save_skill, install_skill, generate_image, publish, panel, budget)',
|
|
36
|
+
connect: 'внешние API-подключения и A2A (connections, connect_service, http_request, disconnect_service, a2a_call)',
|
|
37
|
+
computer: 'Docker-песочница и экран компьютера (sandbox_*, computer_*)',
|
|
38
|
+
browser: 'браузер Chromium в песочнице (browser_*)',
|
|
39
|
+
desktop: 'управление реальным ПК пользователя (desktop_*)',
|
|
40
|
+
chrome: 'настоящий Chrome пользователя через расширение (chrome_*)',
|
|
41
|
+
os: 'ОС сервера и локальная сеть для BOSS (os_*, net_*, shell, install_package, restart_server)',
|
|
42
|
+
services: 'внешние MCP-серверы и сервисы (mcp_*, svc_*)',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const EXACT_GROUP = new Map([
|
|
46
|
+
// accounting
|
|
47
|
+
['describe_class', 'accounting'],
|
|
48
|
+
['find_objects', 'accounting'],
|
|
49
|
+
['register_operation', 'accounting'],
|
|
50
|
+
['report', 'accounting'],
|
|
51
|
+
// classes
|
|
52
|
+
['create_class', 'classes'],
|
|
53
|
+
['update_class', 'classes'],
|
|
54
|
+
['inspect_class_tree', 'classes'],
|
|
55
|
+
['move_class', 'classes'],
|
|
56
|
+
['delete_class', 'classes'],
|
|
57
|
+
['write_table', 'classes'],
|
|
58
|
+
// work_extra
|
|
59
|
+
['append', 'work_extra'],
|
|
60
|
+
['history', 'work_extra'],
|
|
61
|
+
['restore', 'work_extra'],
|
|
62
|
+
['send', 'work_extra'],
|
|
63
|
+
['assign', 'work_extra'],
|
|
64
|
+
['escalate', 'work_extra'],
|
|
65
|
+
// dev
|
|
66
|
+
['grep', 'dev'],
|
|
67
|
+
['glob', 'dev'],
|
|
68
|
+
['apply_patch', 'dev'],
|
|
69
|
+
['run_checks', 'dev'],
|
|
70
|
+
['branch', 'dev'],
|
|
71
|
+
// docs
|
|
72
|
+
['read_table', 'docs'],
|
|
73
|
+
['import_objects', 'docs'],
|
|
74
|
+
['render_doc', 'docs'],
|
|
75
|
+
['export_pdf', 'docs'],
|
|
76
|
+
['export_presentation', 'docs'],
|
|
77
|
+
['create_office_file', 'docs'],
|
|
78
|
+
// agents & meta extra
|
|
79
|
+
['agent_start', 'agents'],
|
|
80
|
+
['agent_status', 'agents'],
|
|
81
|
+
['agent_message', 'agents'],
|
|
82
|
+
['agent_stop', 'agents'],
|
|
83
|
+
['publish', 'agents'],
|
|
84
|
+
['save_skill', 'agents'],
|
|
85
|
+
['install_skill', 'agents'],
|
|
86
|
+
['generate_image', 'agents'],
|
|
87
|
+
['panel', 'agents'],
|
|
88
|
+
['budget', 'agents'],
|
|
89
|
+
['schedule', 'agents'],
|
|
90
|
+
['plugin', 'agents'],
|
|
91
|
+
// connect
|
|
92
|
+
['connections', 'connect'],
|
|
93
|
+
['connect_service', 'connect'],
|
|
94
|
+
['http_request', 'connect'],
|
|
95
|
+
['disconnect_service', 'connect'],
|
|
96
|
+
['a2a_call', 'connect'],
|
|
97
|
+
// os
|
|
98
|
+
['shell', 'os'],
|
|
99
|
+
['install_package', 'os'],
|
|
100
|
+
['restart_server', 'os'],
|
|
101
|
+
]);
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Определить группу отложенного инструмента (null = стартовое ядро, доступно всегда).
|
|
105
|
+
* @param {string} name
|
|
106
|
+
* @returns {string | null}
|
|
107
|
+
*/
|
|
108
|
+
export function toolGroupOf(name) {
|
|
109
|
+
const n = String(name || '');
|
|
110
|
+
if (!n || n === 'tools_enable')
|
|
111
|
+
return null;
|
|
112
|
+
const exact = EXACT_GROUP.get(n);
|
|
113
|
+
if (exact)
|
|
114
|
+
return exact;
|
|
115
|
+
if (n.startsWith('git_') || n.startsWith('lsp_') || n.startsWith('dev_'))
|
|
116
|
+
return 'dev';
|
|
117
|
+
if (n.startsWith('calendar_') || n.startsWith('mail_'))
|
|
118
|
+
return 'calendar_mail';
|
|
119
|
+
if (n.startsWith('twin_'))
|
|
120
|
+
return 'twin';
|
|
121
|
+
if (n.startsWith('sandbox_') || n.startsWith('computer_'))
|
|
122
|
+
return 'computer';
|
|
123
|
+
if (n.startsWith('browser_'))
|
|
124
|
+
return 'browser';
|
|
125
|
+
if (n.startsWith('desktop_'))
|
|
126
|
+
return 'desktop';
|
|
127
|
+
if (n.startsWith('chrome_'))
|
|
128
|
+
return 'chrome';
|
|
129
|
+
if (n.startsWith('os_') || n.startsWith('net_'))
|
|
130
|
+
return 'os';
|
|
131
|
+
if (n.startsWith('mcp_') || n.startsWith('svc_'))
|
|
132
|
+
return 'services';
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Подобрать стартовые группы по контексту узла (place / contextPath) и текстам пользователя.
|
|
138
|
+
* Работает детерминированно; используется на старте задачи и при продолжении.
|
|
139
|
+
*/
|
|
140
|
+
export function inferInitialGroups({ place, items } = {}) {
|
|
141
|
+
const groups = new Set();
|
|
142
|
+
if (place?.DATA?.objects || place?.isRegistry)
|
|
143
|
+
groups.add('accounting');
|
|
144
|
+
|
|
145
|
+
const userText = (Array.isArray(items) ? items : [])
|
|
146
|
+
.filter(i => i?.type === 'user' && i.content)
|
|
147
|
+
.map(i => String(i.content))
|
|
148
|
+
.join('\n')
|
|
149
|
+
.toLowerCase();
|
|
150
|
+
if (userText) {
|
|
151
|
+
if (/\b(?:git|grep|glob|патч|исходник|репозитор|коммит|тест[ыа]?|линтер|sources\/)\b/i.test(userText))
|
|
152
|
+
groups.add('dev');
|
|
153
|
+
if (/\b(?:почт|письм|писем|email|e-mail|календар|встреч|событи[еяй])\b/i.test(userText))
|
|
154
|
+
groups.add('calendar_mail');
|
|
155
|
+
if (/\b(?:экран|скриншот|песочниц|docker|докер|компьютер)\b/i.test(userText))
|
|
156
|
+
groups.add('computer');
|
|
157
|
+
if (/\b(?:браузер|chromium|chrome|хром|открой\s+сайт|на\s+сайте|веб-?страниц)\b/i.test(userText)) {
|
|
158
|
+
groups.add('browser');
|
|
159
|
+
groups.add('chrome');
|
|
160
|
+
}
|
|
161
|
+
if (/\b(?:excel|xlsx|docx|word|pdf|презентац|pptx|таблиц[уы]\s+импорт|отч[её]т\s+pdf)\b/i.test(userText))
|
|
162
|
+
groups.add('docs');
|
|
163
|
+
if (/\b(?:класс[аы]?|реквизит|проводк|справочник|каталог|регистр|операци[юия])\b/i.test(userText)) {
|
|
164
|
+
groups.add('classes');
|
|
165
|
+
groups.add('accounting');
|
|
166
|
+
}
|
|
167
|
+
if (/\b(?:mcp|1с|сервис|подключен|интеграц|http_request|api)\b/i.test(userText)) {
|
|
168
|
+
groups.add('services');
|
|
169
|
+
groups.add('connect');
|
|
170
|
+
}
|
|
171
|
+
if (/\b(?:процесс|порт|сервер|nginx|caddy|systemd|ip|подсет|принтер|сканер|shell|терминал)\b/i.test(userText))
|
|
172
|
+
groups.add('os');
|
|
173
|
+
if (/\b(?:расписани|будильник|напомни|каждый\s+день|cron|фонов(?:ый|ую)\s+агент|плагин|навык|картинк|сгенерируй\s+изображ)\b/i.test(userText))
|
|
174
|
+
groups.add('agents');
|
|
175
|
+
}
|
|
176
|
+
return groups;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Собрать все группы, активированные к текущему ходу (начальные + вызовы tools_enable + уже использованные инструменты).
|
|
181
|
+
*/
|
|
182
|
+
export function collectActiveGroups(items, initialGroups = null) {
|
|
183
|
+
const active = new Set(initialGroups || []);
|
|
184
|
+
for (const item of Array.isArray(items) ? items : []) {
|
|
185
|
+
if (item?.type !== 'assistant' || !Array.isArray(item.tools))
|
|
186
|
+
continue;
|
|
187
|
+
for (const t of item.tools) {
|
|
188
|
+
if (!t?.name)
|
|
189
|
+
continue;
|
|
190
|
+
const g = toolGroupOf(t.name);
|
|
191
|
+
if (g)
|
|
192
|
+
active.add(g);
|
|
193
|
+
if (t.name === 'tools_enable' && t.status !== 'denied' && t.status !== 'error') {
|
|
194
|
+
const req = Array.isArray(t.args?.groups) ? t.args.groups : (t.args?.group ? [t.args.group] : []);
|
|
195
|
+
for (const name of req) {
|
|
196
|
+
const clean = String(name || '').trim();
|
|
197
|
+
if (clean)
|
|
198
|
+
active.add(clean);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return active;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Отфильтровать массив инструментов по активным группам.
|
|
208
|
+
*/
|
|
209
|
+
export function filterLazyTools(tools, activeGroups) {
|
|
210
|
+
const groups = activeGroups instanceof Set ? activeGroups : new Set(activeGroups || []);
|
|
211
|
+
return (tools || []).filter(t => {
|
|
212
|
+
const g = toolGroupOf(t?.name);
|
|
213
|
+
return !g || groups.has(g);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Создать мета-инструмент tools_enable для ленивого подключения специализированных групп.
|
|
219
|
+
* @param {() => Array<{ name: string }>} [getAllTools]
|
|
220
|
+
*/
|
|
221
|
+
export function createToolsEnableTool(getAllTools) {
|
|
222
|
+
const groupHelp = TOOL_GROUP_NAMES.map(g => `${g}: ${GROUP_DESCRIPTIONS[g]}`).join('; ');
|
|
223
|
+
return {
|
|
224
|
+
name: 'tools_enable',
|
|
225
|
+
readonly: true,
|
|
226
|
+
planSafe: true,
|
|
227
|
+
description: 'Подключить дополнительные группы инструментов для текущей задачи (на старте загружено только базовое ядро). Вызови перед использованием инструментов нужных групп: ' + groupHelp,
|
|
228
|
+
parameters: {
|
|
229
|
+
type: 'object',
|
|
230
|
+
properties: {
|
|
231
|
+
groups: {
|
|
232
|
+
type: 'array',
|
|
233
|
+
items: { type: 'string', enum: [...TOOL_GROUP_NAMES] },
|
|
234
|
+
description: 'Список имён групп для подключения',
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
required: ['groups'],
|
|
238
|
+
},
|
|
239
|
+
async run(args) {
|
|
240
|
+
const requested = Array.isArray(args?.groups)
|
|
241
|
+
? args.groups.map(s => String(s || '').trim()).filter(Boolean)
|
|
242
|
+
: (args?.group ? [String(args.group).trim()] : []);
|
|
243
|
+
if (!requested.length)
|
|
244
|
+
return { error: 'Укажи хотя бы одну группу в groups' };
|
|
245
|
+
const all = typeof getAllTools === 'function' ? (getAllTools() || []) : [];
|
|
246
|
+
const enabled = [];
|
|
247
|
+
const unavailable = [];
|
|
248
|
+
const unknown = [];
|
|
249
|
+
for (const g of requested) {
|
|
250
|
+
if (!GROUP_DESCRIPTIONS[g]) {
|
|
251
|
+
unknown.push(g);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const matched = all.filter(t => toolGroupOf(t?.name) === g).map(t => t.name);
|
|
255
|
+
if (matched.length)
|
|
256
|
+
enabled.push({ group: g, tools: matched });
|
|
257
|
+
else
|
|
258
|
+
unavailable.push(g);
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
enabled,
|
|
262
|
+
...(unavailable.length ? { unavailable, note: 'Недоступны в текущей роли или среде' } : {}),
|
|
263
|
+
...(unknown.length ? { unknown } : {}),
|
|
264
|
+
};
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
@@ -46,6 +46,7 @@ const DEFAULTS = {
|
|
|
46
46
|
execTimeoutSec: 120,
|
|
47
47
|
maxReadBytes: 1_000_000,
|
|
48
48
|
maxWriteBytes: 200_000,
|
|
49
|
+
maxImportBytes: 25 * 1024 * 1024,
|
|
49
50
|
maxOutput: 200_000,
|
|
50
51
|
network: { egressName: 'work-egress', sandboxName: 'work-sandbox', ttlMin: 0 },
|
|
51
52
|
// ttlMin: авто-выключение интернета через N минут (0 = выключено)
|
|
@@ -9,6 +9,7 @@ import path from 'node:path';
|
|
|
9
9
|
import { loadSandboxConfig } from './config.js';
|
|
10
10
|
import { demux, demuxBytes } from './stream.js';
|
|
11
11
|
import { clip } from '../agent/util.js';
|
|
12
|
+
import { encodeTarHeader } from '../trainer/tar-stream.js';
|
|
12
13
|
|
|
13
14
|
export const LABEL = 'work.sandbox';
|
|
14
15
|
const NAME_RE = /^[\w.-]{1,32}$/;
|
|
@@ -101,9 +102,9 @@ export function readOnlyTmpfs(cfg) {
|
|
|
101
102
|
const gid = num(cfg.homeGid, uid);
|
|
102
103
|
const home = '/' + String(cfg.homeDir || 'home/agent').replace(/^\/+|\/+$/g, '');
|
|
103
104
|
return {
|
|
104
|
-
['/tmp']: 'rw,size=256m',
|
|
105
|
-
[home]: 'rw,size=512m,uid=' + uid + ',gid=' + gid,
|
|
106
|
-
['/var/tmp']: 'rw,size=64m',
|
|
105
|
+
['/tmp']: 'rw,exec,size=256m',
|
|
106
|
+
[home]: 'rw,exec,size=512m,uid=' + uid + ',gid=' + gid,
|
|
107
|
+
['/var/tmp']: 'rw,exec,size=64m',
|
|
107
108
|
['/run']: 'rw,size=64m',
|
|
108
109
|
};
|
|
109
110
|
}
|
|
@@ -609,6 +610,52 @@ export async function writeBytes(docker, id, spath, data, cfg = loadSandboxConfi
|
|
|
609
610
|
return 'записано ' + r.stdout.trim() + ' байт в ' + spath;
|
|
610
611
|
}
|
|
611
612
|
|
|
613
|
+
/** Собрать минимальный POSIX tar для одного файла (с uid/gid пользователя контейнера). */
|
|
614
|
+
export function buildSingleFileTar(fileName, data, { uid = 1000, gid = 1000, mode = 0o644 } = {}) {
|
|
615
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data ?? '');
|
|
616
|
+
const cleanName = String(fileName || 'file').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
617
|
+
const header = encodeTarHeader({ name: cleanName, size: buf.length, mode });
|
|
618
|
+
const oct = (v, w) => Math.max(0, Math.floor(Number(v) || 0)).toString(8).padStart(w - 1, '0').slice(-(w - 1)) + '\0';
|
|
619
|
+
header.write(oct(uid, 8), 108, 8, 'ascii');
|
|
620
|
+
header.write(oct(gid, 8), 116, 8, 'ascii');
|
|
621
|
+
header.fill(0x20, 148, 156);
|
|
622
|
+
let sum = 0;
|
|
623
|
+
for (let i = 0; i < 512; i++)
|
|
624
|
+
sum += header[i];
|
|
625
|
+
header.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'ascii');
|
|
626
|
+
const padLen = (512 - (buf.length % 512)) % 512;
|
|
627
|
+
return Buffer.concat([header, buf, Buffer.alloc(padLen), Buffer.alloc(1024)]);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Потоковая загрузка файла любого разумного размера (до maxImportBytes, дефолт 25 МБ) через Docker putArchive. */
|
|
631
|
+
export async function writeArchiveBytes(docker, id, spath, data, cfg = loadSandboxConfig()) {
|
|
632
|
+
const raw = Buffer.isBuffer(data) ? data : Buffer.from(data ?? '');
|
|
633
|
+
const limit = Number(cfg.maxImportBytes) || 25 * 1024 * 1024;
|
|
634
|
+
if (raw.length > limit)
|
|
635
|
+
throw new Error('файл слишком большой (' + raw.length + ' байт, лимит ' + limit + ')');
|
|
636
|
+
const container = docker.getContainer(id);
|
|
637
|
+
if (typeof container?.putArchive !== 'function')
|
|
638
|
+
return writeBytes(docker, id, spath, raw, cfg);
|
|
639
|
+
const dir = path.posix.dirname(spath) || '/workspace';
|
|
640
|
+
const base = path.posix.basename(spath);
|
|
641
|
+
const mk = await execRaw(docker, id, {
|
|
642
|
+
cmd: ['mkdir', '-p', '--', dir],
|
|
643
|
+
timeoutSec: 20, maxBytes: 1000,
|
|
644
|
+
});
|
|
645
|
+
if (mk.code !== 0)
|
|
646
|
+
throw new Error('не удалось создать папку ' + dir + (mk.stderr.trim() ? ': ' + mk.stderr.trim().slice(0, 200) : ''));
|
|
647
|
+
const uid = Number.isFinite(Number(cfg.homeUid)) ? Number(cfg.homeUid) : 1000;
|
|
648
|
+
const gid = Number.isFinite(Number(cfg.homeGid)) ? Number(cfg.homeGid) : uid;
|
|
649
|
+
const tarBuf = buildSingleFileTar(base, raw, { uid, gid });
|
|
650
|
+
try {
|
|
651
|
+
await container.putArchive(tarBuf, { path: dir });
|
|
652
|
+
}
|
|
653
|
+
catch (e) {
|
|
654
|
+
throw friendly(e);
|
|
655
|
+
}
|
|
656
|
+
return 'записано ' + raw.length + ' байт в ' + spath;
|
|
657
|
+
}
|
|
658
|
+
|
|
612
659
|
/** Содержимое папки. */
|
|
613
660
|
export async function listDir(docker, id, spath) {
|
|
614
661
|
const r = await execRaw(docker, id, { cmd: ['ls', '-la', '--', spath], timeoutSec: 30, maxBytes: 20000 });
|