odant-work 1.0.87 → 1.0.88

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 (60) hide show
  1. package/#system/package-manifest.json +54 -60
  2. package/$server/$folder/$class/$module/class.js +2 -0
  3. package/$server/$folder/$class/$structure/class.js +1 -0
  4. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +123 -1
  5. package/$server/$folder/$class/handlers/pages/form/system/$handler/class.js +9 -0
  6. package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/system.js +82 -14
  7. package/$server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-root.js +167 -0
  8. package/{SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler → $server/$folder/$class/handlers/pages/form/system/$handler/tabs}/mcp.js +2 -2
  9. package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/modules.js +51 -4
  10. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +25 -0
  11. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +17 -0
  12. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/panel.js +7 -1
  13. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +1 -0
  14. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-policy.js +6 -2
  15. package/$server/$folder/handlers/pages/form/$handler/form.js +21 -6
  16. package/$server/$folder/lib/chat-item/chat-item.js +4 -1
  17. package/$server/$folder/lib/tree/tree.js +77 -10
  18. package/MODELS/$ai/$folder/$class/$ai/class.js +2 -1
  19. package/MODELS/$ai/$folder/$class/$provider/class.js +2 -1
  20. package/MODELS/$ai/class.js +1 -1
  21. package/MODELS/GigaChat/$provider/class.js +1 -1
  22. package/MODELS/Local/$provider/class.js +2 -1
  23. package/MODELS/MTS-AI/$provider/class.js +1 -1
  24. package/MODELS/T-Bank/$provider/class.js +1 -1
  25. package/MODELS/Yandex/$provider/class.js +1 -1
  26. package/MODULES/$domain/$folder/$class/$module/class.js +2 -0
  27. package/ORGANIZATIONS/$domain/$folder/$class/$base/class.js +1 -0
  28. package/PROJECTS/$domain/$folder/$class/$project/class.js +1 -0
  29. package/SERVICES/$service/class.js +2 -1
  30. package/package.json +1 -1
  31. package/sources/client/folder.js +1 -1
  32. package/sources/client.js +12 -0
  33. package/sources/host/auto-updater.js +1 -1
  34. package/sources/modules/agent/index.js +5 -2
  35. package/sources/modules/agent/loop.js +65 -0
  36. package/sources/modules/agent/node-rules.js +9 -4
  37. package/sources/modules/agent/scope.js +387 -0
  38. package/sources/modules/agent/session.js +350 -15
  39. package/sources/modules/agent/tools/meta.js +60 -0
  40. package/sources/modules/trainer/providers.js +1 -1
  41. package/sources/server/chat-threads.js +12 -1
  42. package/sources/server/class.js +3 -0
  43. package/sources/server/folder.js +72 -4
  44. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/class.js +0 -10
  45. package/$server/$folder/$class/handlers/pages/form/editor/$handler/class.js +0 -24
  46. package/$server/$folder/$class/handlers/pages/form/editor/$handler/editor.js +0 -20
  47. package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +0 -10
  48. package/$server/$folder/$class/handlers/pages/form/folder/$handler/folder.js +0 -16
  49. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/class.js +0 -13
  50. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/class.js +0 -13
  51. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/class.js +0 -13
  52. package/SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler/class.js +0 -12
  53. /package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/agent.js +0 -0
  54. /package/{MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js → $server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-local.js} +0 -0
  55. /package/{MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js → $server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-model.js} +0 -0
  56. /package/{MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/provider.js → $server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-provider.js} +0 -0
  57. /package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/database.js +0 -0
  58. /package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/license.js +0 -0
  59. /package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/messengers.js +0 -0
  60. /package/$server/$folder/$class/{$structure/handlers → handlers}/pages/form/system/$handler/tabs/staff.js +0 -0
@@ -17,6 +17,7 @@
17
17
  * События в UI (session.send): chat.start / chat.done (занятость), task.state { status },
18
18
  * task.delta { item, field, token } (стрим), { path } — файл изменился (перечитать).
19
19
  */
20
+ import fsp from 'node:fs/promises';
20
21
  import { log } from './log.js';
21
22
  import { runLoop, maybeCompact } from './loop.js';
22
23
  import { createEnv, shouldEnforceAgentLicense } from './index.js';
@@ -24,6 +25,10 @@ import { assertAgentSystemLicensed } from '../license/index.js';
24
25
  import { genId } from './util.js';
25
26
  import { collectUndo, applyUndo } from './undo.js';
26
27
  import { getItem, callAs, writeFile } from './tools/work.js';
28
+ import { resolveTargetPlace, checkTargetMoveAccess } from './scope.js';
29
+ import * as LOGS from '../../server/logs.js';
30
+ import * as CHAT from '../../server/chat-threads.js';
31
+ import * as REFS from '../../server/access/refs.js';
27
32
 
28
33
  const RUNS = new Map();
29
34
  const MODES = ['auto', 'ask', 'plan'];
@@ -201,6 +206,8 @@ export const PUSH_BODY_MAX = 180;
201
206
  /** Состояние задачи словами для тела уведомления. */
202
207
  function pushStateText(kind, detail) {
203
208
  if (kind === 'waiting') {
209
+ if (detail.waitingKind === 'move')
210
+ return 'Нужен перенос задачи';
204
211
  if (detail.waitingKind === 'approval')
205
212
  return 'Нужно ваше разрешение';
206
213
  if (detail.waitingKind === 'question')
@@ -363,7 +370,17 @@ function makeHost(s, session) {
363
370
  /** Состав контекста последнего хода (оценка): лимит модели, system, схемы инструментов, диалог. */
364
371
  noteContext: c => { body.context = { ...c, time: Date.now() }; },
365
372
  wait: req => {
366
- body.waiting = { kind: req.kind, item: req.item, call: req.call };
373
+ body.waiting = {
374
+ kind: req.kind,
375
+ item: req.item,
376
+ call: req.call,
377
+ ...(req.kind === 'move' ? {
378
+ targetPath: req.targetPath,
379
+ targetLabel: req.targetLabel,
380
+ targetRole: req.targetRole,
381
+ reason: req.reason,
382
+ } : {}),
383
+ };
367
384
  setStatus(s, session, 'waiting');
368
385
  send(s, session, { type: 'chat.done' });
369
386
  const p = new Promise(resolve => s.waiters.set(req.call, resolve));
@@ -371,12 +388,13 @@ function makeHost(s, session) {
371
388
  const hit = findCall(body.items, req.call)?.entry;
372
389
  // 9.7: разрешение — с кнопками «Разрешить/Отклонить» в уведомлении (reason — что именно)
373
390
  pushNotify(s, session, 'waiting', req.kind === 'question' ? req.question
374
- : req.kind === 'connect' ? 'подключить ' + (hit?.connect?.label || hit?.connect?.provider || 'сервис')
375
- : 'разрешить: ' + (req.reason || req.tool || ''),
391
+ : req.kind === 'move' ? ('перенести в ' + (req.targetLabel || req.targetPath || 'WORK'))
392
+ : req.kind === 'connect' ? 'подключить ' + (hit?.connect?.label || hit?.connect?.provider || 'сервис')
393
+ : 'разрешить: ' + (req.reason || req.tool || ''),
376
394
  { waitingKind: req.kind, call: req.call, reason: req.reason || req.tool || '' });
377
395
  return p.then(res => {
378
396
  delete body.waiting;
379
- if (!s.controller?.signal.aborted) {
397
+ if (!s.controller?.signal.aborted && !s.movedAway) {
380
398
  setStatus(s, session, 'running');
381
399
  send(s, session, { type: 'chat.start' });
382
400
  }
@@ -481,6 +499,7 @@ async function assertTaskOwner(file, params) {
481
499
  /** Запуск петли (фоном). Возвращает сразу; ход работы — событиями и сохранениями. */
482
500
  function start(s, session, file, licenseOpts = {}) {
483
501
  const body = s.body;
502
+ s.movedAway = false;
484
503
  s.controller = new AbortController();
485
504
  s.startedAt = Date.now();
486
505
  setStatus(s, session, 'running');
@@ -489,6 +508,7 @@ function start(s, session, file, licenseOpts = {}) {
489
508
  s.running = (async () => {
490
509
  let restart;
491
510
  let aborted;
511
+ let movedAway = false;
492
512
  try {
493
513
  if (shouldEnforceAgentLicense(licenseOpts)) {
494
514
  assertAgentSystemLicensed({ license: licenseOpts.license, systemDir: licenseOpts.systemDir });
@@ -518,7 +538,7 @@ function start(s, session, file, licenseOpts = {}) {
518
538
  effort: body.effort || def?.meta.effort,
519
539
  maxTurns: Number(def?.meta.maxTurns || env.config.maxTurns) || undefined,
520
540
  });
521
- body.status = res.status === 'done' ? 'idle' : res.status;
541
+ body.status = (res.status === 'done' || res.status === 'moved') ? 'idle' : res.status;
522
542
  }
523
543
  catch (e) {
524
544
  if (!e?.reported)
@@ -526,6 +546,7 @@ function start(s, session, file, licenseOpts = {}) {
526
546
  body.status = 'error';
527
547
  }
528
548
  finally {
549
+ movedAway = !!s.movedAway;
529
550
  s.body = body;
530
551
  delete body.waiting;
531
552
  s.waiters.clear();
@@ -533,18 +554,27 @@ function start(s, session, file, licenseOpts = {}) {
533
554
  s.interrupted = false;
534
555
  aborted = !!s.controller?.signal.aborted && !wasInterrupted;
535
556
  s.controller = null;
536
- // реплики, пришедшие под конец (или при стопе/перебивании), не теряются: в ленту; без стопа (или при перебивании) — новый прогон
537
- const rest = body.queue || [];
538
- delete body.queue;
539
- for (const u of rest) {
540
- if (u.voice)
541
- body.voice = true;
542
- body.items.push({ ...u, queued: undefined });
557
+ if (movedAway) {
558
+ delete body.queue;
559
+ s.running = null;
560
+ RUNS.delete(s.key);
561
+ }
562
+ else {
563
+ // реплики, пришедшие под конец (или при стопе/перебивании), не теряются: в ленту; без стопа (или при перебивании) — новый прогон
564
+ const rest = body.queue || [];
565
+ delete body.queue;
566
+ for (const u of rest) {
567
+ if (u.voice)
568
+ body.voice = true;
569
+ body.items.push({ ...u, queued: undefined });
570
+ }
571
+ restart = rest.length > 0 && !aborted && body.status !== 'error';
572
+ await save(s, session);
573
+ s.running = null;
543
574
  }
544
- restart = rest.length > 0 && !aborted && body.status !== 'error';
545
- await save(s, session);
546
- s.running = null;
547
575
  }
576
+ if (movedAway)
577
+ return;
548
578
  if (restart) {
549
579
  start(s, session, file);
550
580
  return;
@@ -594,6 +624,7 @@ function applyOffline(body, reply) {
594
624
  }
595
625
  else {
596
626
  entry.status = 'denied';
627
+ delete entry.moveRequest;
597
628
  delete entry.approvalScope;
598
629
  delete entry.approvalLabel;
599
630
  delete entry.alwaysLabel;
@@ -791,6 +822,301 @@ function normAttachments(list) {
791
822
  return arr.map(a => typeof a === 'string' ? { path: a, name: a.split('/').pop() } : a).filter(a => a?.path);
792
823
  }
793
824
 
825
+ /**
826
+ * Определить, является ли перенос на текущем шаге первым шагом задачи (move)
827
+ * или сменой темы в уже работавшей задаче (fork).
828
+ */
829
+ export function isFirstTurnOfTask(body) {
830
+ const items = Array.isArray(body?.items) ? body.items : [];
831
+ let lastUserIdx = -1;
832
+ for (let i = items.length - 1; i >= 0; i--) {
833
+ if (items[i]?.type === 'user') {
834
+ lastUserIdx = i;
835
+ break;
836
+ }
837
+ }
838
+ if (lastUserIdx <= 0)
839
+ return true;
840
+ for (let i = 0; i < lastUserIdx; i++) {
841
+ const it = items[i];
842
+ if (!it)
843
+ continue;
844
+ if (it.type === 'user' || it.type === 'summary')
845
+ return false;
846
+ if (it.type === 'assistant' && (String(it.content || '').trim() || (it.tools || []).some(t => t.status === 'ok')))
847
+ return false;
848
+ }
849
+ return true;
850
+ }
851
+
852
+ function buildForkSummary(body, targetPath, oldPath) {
853
+ const items = Array.isArray(body?.items) ? body.items : [];
854
+ const lines = [`Контекст: продолжение диалога из задачи ${oldPath}.`];
855
+ // При переносе в корень WORK (/) даём краткую выжимку предыдущего шага; при межотдельском переносе — только нейтральную ссылку
856
+ if (targetPath === '/') {
857
+ let lastUser = '';
858
+ let lastAsst = '';
859
+ for (let i = items.length - 1; i >= 0; i--) {
860
+ const it = items[i];
861
+ if (!lastAsst && it?.type === 'assistant' && !it.error && String(it.content || '').trim())
862
+ lastAsst = String(it.content).replace(/\s+/g, ' ').trim().slice(0, 220);
863
+ if (!lastUser && it?.type === 'user' && String(it.content || '').trim() && i < items.length - 1) {
864
+ lastUser = String(it.content).replace(/\s+/g, ' ').trim().slice(0, 160);
865
+ break;
866
+ }
867
+ }
868
+ if (lastUser)
869
+ lines.push(`Предыдущий запрос: «${lastUser}»`);
870
+ if (lastAsst)
871
+ lines.push(`Предыдущий результат: «${lastAsst}»`);
872
+ }
873
+ return lines.join('\n');
874
+ }
875
+
876
+ async function copyTaskAttachments(attachments, targetTaskItem, newTaskPath, session, { deleteSource = false } = {}) {
877
+ if (!Array.isArray(attachments) || !attachments.length || !targetTaskItem?.save_file)
878
+ return attachments || [];
879
+ const moved = [];
880
+ for (const att of attachments) {
881
+ if (!att?.path)
882
+ continue;
883
+ try {
884
+ let src = await globalThis.WORK?.get_item?.(att.path);
885
+ if (Array.isArray(src))
886
+ src = src[src.length - 1] || null;
887
+ if (!src) {
888
+ moved.push(att);
889
+ continue;
890
+ }
891
+ let buf = null;
892
+ if (src.real_dir)
893
+ buf = await fsp.readFile(src.real_dir).catch(() => null);
894
+ if (!buf && typeof src.load === 'function') {
895
+ const raw = await src.load({ session });
896
+ buf = Buffer.isBuffer(raw) ? raw : Buffer.from(String(raw ?? ''), 'utf-8');
897
+ }
898
+ if (!buf) {
899
+ moved.push(att);
900
+ continue;
901
+ }
902
+ const name = String(att.name || att.path.split('/').pop() || 'file');
903
+ const fLog = await targetTaskItem.save_file({
904
+ filename: name,
905
+ post: buf,
906
+ encoding: 'binary',
907
+ ignore_save_logs: true,
908
+ mainContext: newTaskPath,
909
+ session,
910
+ });
911
+ const rawNew = fLog?.logFullPath || (typeof fLog?.path?.then === 'function' ? await fLog.path : fLog?.path) || '';
912
+ const newPath = rawNew ? (rawNew.startsWith('/') ? rawNew : '/' + rawNew) : att.path;
913
+ moved.push({ ...att, path: newPath, name });
914
+ if (deleteSource && src.real_dir) {
915
+ await fsp.rm(src.real_dir, { force: true }).catch(() => {});
916
+ src.parent?.reset?.();
917
+ await REFS.removeTarget(att.path).catch(() => {});
918
+ }
919
+ }
920
+ catch (e) {
921
+ log.debug('task.moveAttachment', e);
922
+ moved.push(att);
923
+ }
924
+ }
925
+ return moved;
926
+ }
927
+
928
+ /**
929
+ * Выполнить перенос (1-й шаг) или ответвление (2-й+ шаг) задачи в целевой узел и продолжить её там.
930
+ */
931
+ export async function performTaskMove({ file, s, body, session, waiting }) {
932
+ const resolved = await resolveTargetPlace(waiting?.targetPath || '/');
933
+ const access = await checkTargetMoveAccess(resolved.node, session, {
934
+ needAdmin: resolved.path === '/',
935
+ needBoss: waiting?.targetRole === 'BOSS',
936
+ });
937
+ if (!access.allowed)
938
+ throw new Error(access.reason || 'Недостаточно прав для переноса в целевой узел');
939
+
940
+ const targetPlace = resolved.node;
941
+ const targetRole = access.targetRole || 'USER';
942
+ const uid = String(session?.uid || taskOwnerUid(file) || 'system');
943
+ const oldPath = file.path;
944
+ const oldOwner = file.$class || file.$owner || file.$parent || null;
945
+ const mode = isFirstTurnOfTask(body) ? 'move' : 'fork';
946
+ const safeName = String(body.name || body.title || 'task')
947
+ .replace(/[<>:"/\\|?*\n\r]/g, ' ')
948
+ .replace(/\s+/g, ' ')
949
+ .trim()
950
+ .slice(0, 90) || 'task';
951
+
952
+ let nextItems = [];
953
+ let moveAttachmentsList = [];
954
+ if (mode === 'move') {
955
+ nextItems = JSON.parse(JSON.stringify(body.items || []));
956
+ // Закрываем ожидающий вызов сообщением о переносе, чтобы модель продолжила выполнение в новом узле
957
+ const hit = waiting?.call ? findCall(nextItems, waiting.call) : null;
958
+ if (hit?.entry) {
959
+ delete hit.entry.moveRequest;
960
+ hit.entry.status = 'ok';
961
+ hit.entry.durationMs = 0;
962
+ hit.entry.result = `Задача перенесена в узел «${resolved.label}» (${resolved.path}). Теперь ты работаешь в целевом узле — выполни исходный запрос здесь.`;
963
+ }
964
+ }
965
+ else {
966
+ // Ответвление: берём последний user turn (с его вложениями) + краткую выжимку контекста
967
+ const origItems = body.items || [];
968
+ let lastUser = null;
969
+ for (let i = origItems.length - 1; i >= 0; i--) {
970
+ if (origItems[i]?.type === 'user') {
971
+ lastUser = origItems[i];
972
+ break;
973
+ }
974
+ }
975
+ const summary = buildForkSummary(body, resolved.path, oldPath);
976
+ const userText = String(lastUser?.content || '').trim();
977
+ const combinedPrompt = [summary, userText].filter(Boolean).join('\n\n');
978
+ moveAttachmentsList = Array.isArray(lastUser?.attachments) ? lastUser.attachments : [];
979
+ nextItems = [{
980
+ id: genId(),
981
+ type: 'user',
982
+ time: Date.now(),
983
+ content: combinedPrompt,
984
+ ...(lastUser?.voice ? { voice: true } : {}),
985
+ ...(moveAttachmentsList.length ? { attachments: JSON.parse(JSON.stringify(moveAttachmentsList)) } : {}),
986
+ }];
987
+ }
988
+
989
+ const newBody = {
990
+ type: 'task',
991
+ version: 2,
992
+ name: safeName,
993
+ ...(body.title ? { title: body.title } : {}),
994
+ created: mode === 'move' ? (body.created || Date.now()) : Date.now(),
995
+ updated: Date.now(),
996
+ ...(body.model ? { model: body.model } : {}),
997
+ ...(body.effort ? { effort: body.effort } : {}),
998
+ mode: body.mode || 'auto',
999
+ role: targetRole,
1000
+ contextPath: resolved.path,
1001
+ ...(body.tz ? { tz: body.tz } : {}),
1002
+ ...(body.location ? { location: body.location } : {}),
1003
+ ...(body.voice ? { voice: true } : {}),
1004
+ status: 'idle',
1005
+ items: nextItems,
1006
+ todos: mode === 'move' ? (body.todos || []) : [],
1007
+ allowed: mode === 'move' ? (body.allowed || []) : [],
1008
+ results: [],
1009
+ };
1010
+
1011
+ const saveLog = await targetPlace.save_file({
1012
+ filename: safeName + '.task',
1013
+ post: JSON.stringify(newBody, null, 2),
1014
+ role: targetRole,
1015
+ skip_file_handler: true,
1016
+ session,
1017
+ sender: uid,
1018
+ encoding: 'utf-8',
1019
+ });
1020
+ const rawNewPath = saveLog?.logFullPath || (typeof saveLog?.path?.then === 'function' ? await saveLog.path : saveLog?.path) || '';
1021
+ const newPath = rawNewPath ? (rawNewPath.startsWith('/') ? rawNewPath : '/' + rawNewPath) : '';
1022
+ if (!newPath)
1023
+ throw new Error('Не удалось создать задачу в целевом узле ' + resolved.path);
1024
+
1025
+ let newTaskItem = await globalThis.WORK.get_item(newPath);
1026
+ if (Array.isArray(newTaskItem))
1027
+ newTaskItem = newTaskItem[newTaskItem.length - 1] || null;
1028
+ if (!newTaskItem)
1029
+ throw new Error('Перенесённая задача не найдена по пути ' + newPath);
1030
+
1031
+ // Перенос / копирование вложений
1032
+ const newState = stateOf(newTaskItem);
1033
+ newState.body = normalizeBody(newBody);
1034
+ const includePaths = [];
1035
+ if (mode === 'move') {
1036
+ for (const it of newState.body.items) {
1037
+ if (it?.type === 'user' && Array.isArray(it.attachments) && it.attachments.length) {
1038
+ it.attachments = await copyTaskAttachments(it.attachments, newTaskItem, newPath, session, { deleteSource: true });
1039
+ for (const a of it.attachments)
1040
+ if (a?.path) includePaths.push(a.path);
1041
+ }
1042
+ }
1043
+ }
1044
+ else if (moveAttachmentsList.length) {
1045
+ const copied = await copyTaskAttachments(moveAttachmentsList, newTaskItem, newPath, session, { deleteSource: false });
1046
+ if (newState.body.items[0])
1047
+ newState.body.items[0].attachments = copied;
1048
+ for (const a of copied)
1049
+ if (a?.path) includePaths.push(a.path);
1050
+ }
1051
+ await save(newState, session);
1052
+ if (includePaths.length && typeof targetPlace.append_log_includes === 'function')
1053
+ await targetPlace.append_log_includes({ entryPath: newPath, includePaths, session }).catch(() => {});
1054
+
1055
+ // Регистрация сообщения в twin-чате целевого узла (как в chat.js)
1056
+ if (typeof CHAT.sendMessage === 'function') {
1057
+ const firstPromptText = String((newState.body.items.find(i => i?.type === 'user')?.content) || safeName);
1058
+ await CHAT.sendMessage(targetPlace, {
1059
+ uid,
1060
+ kind: targetPlace.type === '$user' ? 'dm' : 'twin',
1061
+ ...(targetPlace.type === '$user' ? { peerId: targetPlace.id } : {}),
1062
+ message: firstPromptText,
1063
+ taskPath: newPath,
1064
+ session,
1065
+ }).catch(() => {});
1066
+ }
1067
+
1068
+ if (mode === 'move') {
1069
+ s.movedAway = true;
1070
+ delete body.waiting;
1071
+ // Полная очистка исходной задачи из исходного узла
1072
+ if (file.real_dir)
1073
+ await fsp.rm(file.real_dir, { force: true }).catch(() => {});
1074
+ file.parent?.reset?.();
1075
+ if (oldOwner) {
1076
+ await LOGS.deleteLogEntry(oldOwner, { path: oldPath }).catch(() => {});
1077
+ await CHAT.deleteTaskMessages(oldOwner, oldPath).catch(() => {});
1078
+ oldOwner.reset?.();
1079
+ }
1080
+ await REFS.removeTarget(oldPath).catch(() => {});
1081
+ await REFS.removeEntry(oldPath).catch(() => {});
1082
+ }
1083
+ else {
1084
+ // В исходной задаче закрываем перенесённый шаг ссылкой на новую задачу
1085
+ const hit = waiting?.call ? findCall(body.items, waiting.call) : null;
1086
+ if (hit?.entry) {
1087
+ delete hit.entry.moveRequest;
1088
+ hit.entry.status = 'ok';
1089
+ hit.entry.durationMs = 0;
1090
+ hit.entry.result = `Продолжено в новой задаче в «${resolved.label}»: ${newPath}`;
1091
+ }
1092
+ delete body.waiting;
1093
+ body.items.push({
1094
+ id: genId(),
1095
+ type: 'assistant',
1096
+ time: Date.now(),
1097
+ content: `Запрос перенесён в новую задачу в «${resolved.label}»: ${newPath}`,
1098
+ });
1099
+ body.status = 'idle';
1100
+ await save(s, session);
1101
+ }
1102
+
1103
+ // Запускаем выполнение в целевом узле
1104
+ start(newState, session, newTaskItem);
1105
+
1106
+ const moved = {
1107
+ mode,
1108
+ oldPath,
1109
+ newPath,
1110
+ targetNodePath: resolved.path,
1111
+ targetLabel: resolved.label,
1112
+ targetRole,
1113
+ };
1114
+ session?.send?.({ type: 'task.moved', path: oldPath, ...moved });
1115
+ if (uid && uid !== 'system')
1116
+ CHAT.notifyChatEvent([uid], { type: 'task.moved', path: oldPath, ...moved });
1117
+ return moved;
1118
+ }
1119
+
794
1120
  /** Подтверждение вызова / ответ формой. { call, accept, always, content, values }
795
1121
  * @param {any} file элемент .task
796
1122
  * @param {{ [key: string]: any }} params
@@ -808,6 +1134,15 @@ export async function approve(file, params = {}) {
808
1134
  content: p.content,
809
1135
  values: p.values && typeof p.values === 'object' ? p.values : undefined,
810
1136
  };
1137
+ if (body.waiting?.kind === 'move' && reply.accept) {
1138
+ const moved = await performTaskMove({ file, s, body, session: p.session, waiting: body.waiting });
1139
+ if (call && s.waiters.has(call)) {
1140
+ const resolve = s.waiters.get(call);
1141
+ s.waiters.delete(call);
1142
+ resolve({ accept: true, moved });
1143
+ }
1144
+ return { ok: true, moved };
1145
+ }
811
1146
  if (call && s.waiters.has(call)) {
812
1147
  const resolve = s.waiters.get(call);
813
1148
  s.waiters.delete(call);
@@ -188,6 +188,66 @@ export const metaTools = [
188
188
  return answer ? 'Ответ человека: ' + answer : 'Человек не ответил по существу.';
189
189
  },
190
190
  },
191
+ {
192
+ name: 'move_task',
193
+ planSafe: true,
194
+ permission: () => ({ verdict: 'allow' }),
195
+ description: 'Предложить пользователю перенести текущую задачу в надлежащий узел (например, в корень WORK «/» для системных/серверных/сетевых задач, правок ядра, /$server, /MODULES, /USERS, /NODES, или в другое подразделение/организацию) и продолжить выполнение там. Перед переносом проверяет права пользователя в целевом узле.',
196
+ parameters: {
197
+ type: 'object',
198
+ properties: {
199
+ target_path: { type: 'string', description: 'Целевой WORK-путь («/» для корня WORK или путь подразделения/организации/узла)' },
200
+ reason: { type: 'string', description: 'Коротко и по-человечески, почему задачу нужно перенести туда' },
201
+ },
202
+ required: ['target_path', 'reason'],
203
+ },
204
+ async run(args, ctx) {
205
+ const { host, entry, turn } = ctx;
206
+ if ((ctx.depth || 0) > 0)
207
+ return { error: 'Субагент не может переносить родительскую задачу.' };
208
+ const { resolveTargetPlace, checkTargetMoveAccess } = await import('../scope.js');
209
+ const { normalizeWorkPath } = await import('../permissions.js');
210
+ const { MovedError } = await import('../loop.js');
211
+ const placePath = normalizeWorkPath(ctx.contextPath || ctx.place?.path || '/') || '/';
212
+ const resolved = await resolveTargetPlace(args.target_path || '/');
213
+ if (placePath === resolved.path)
214
+ return `Задача уже находится в узле ${resolved.path} («${resolved.label}»).`;
215
+ const needAdmin = resolved.path === '/';
216
+ const access = await checkTargetMoveAccess(resolved.node, ctx.session, { needAdmin });
217
+ if (!access.allowed)
218
+ return { error: (access.reason || 'У вас нет прав доступа к целевому узлу.') + ' Используй escalate, чтобы запросить права у руководителя (BOSS).' };
219
+ if (typeof host.wait !== 'function')
220
+ return { error: 'В автономном запуске перенос задачи недоступен.' };
221
+ const reason = String(args.reason || '').trim() || `Требуется контекст узла ${resolved.path}`;
222
+ entry.status = 'waiting';
223
+ entry.moveRequest = {
224
+ targetPath: resolved.path,
225
+ targetLabel: resolved.label,
226
+ targetRole: access.targetRole,
227
+ reason,
228
+ };
229
+ await host.save();
230
+ const res = await host.wait({
231
+ kind: 'move',
232
+ item: turn.id,
233
+ call: entry.id,
234
+ targetPath: resolved.path,
235
+ targetLabel: resolved.label,
236
+ targetRole: access.targetRole,
237
+ reason,
238
+ }) || {};
239
+ delete entry.moveRequest;
240
+ if (!res.accept) {
241
+ entry.status = 'denied';
242
+ entry.answer = res.content ? String(res.content) : 'Перенос отклонён пользователем';
243
+ return entry.answer;
244
+ }
245
+ if (res.moved)
246
+ throw new MovedError(res.moved);
247
+ entry.status = 'ok';
248
+ return `Задача перенесена в ${resolved.path}.`;
249
+ },
250
+ },
191
251
  {
192
252
  name: 'task',
193
253
  concurrent: true,
@@ -640,7 +640,7 @@ export function buildProviderClassScripts(preset, overrides = {}) {
640
640
  const providerObj = {
641
641
  icon,
642
642
  label,
643
- form: 'provider',
643
+ form: 'system',
644
644
  protocol,
645
645
  baseUrl,
646
646
  };
@@ -16,7 +16,7 @@ import * as WORKPLACES from './access/workplaces.js';
16
16
  import { baseDbFile, dataDb, tx } from '../data/db.js';
17
17
  import { DEV_MODE } from '../host/config.js';
18
18
 
19
- function notifyChatEvent(uids, payload) {
19
+ export function notifyChatEvent(uids, payload) {
20
20
  import('../host/websocket.js')
21
21
  .then(m => m.broadcastChatEvent?.(uids, payload))
22
22
  .catch(() => {});
@@ -702,3 +702,14 @@ export async function resolveApproval(storage, params = {}) {
702
702
  });
703
703
  return { ok: true, message: updated };
704
704
  }
705
+
706
+ /** Удалить сообщения беседы, привязанные к перенесённой задаче (`task_path`). */
707
+ export async function deleteTaskMessages(storage, taskPath) {
708
+ const raw = String(taskPath || '').trim();
709
+ if (!storage || !raw)
710
+ return { ok: true, deleted: 0 };
711
+ const norm = REFS.normPath(raw);
712
+ const db = await dbForThreadStorage(storage, storage?.type === '$user' ? 'dm' : 'twin');
713
+ const res = db.prepare('DELETE FROM chat_messages WHERE task_path = ? OR task_path = ?').run(raw, norm);
714
+ return { ok: true, deleted: Number(res?.changes) || 0 };
715
+ }
@@ -157,6 +157,9 @@ export class $class extends $folder {
157
157
  get declaredRoles() {
158
158
  return this._declaredRolesSync();
159
159
  },
160
+ get mainTreeChildren() {
161
+ return this.DATA?.mainTreeChildren;
162
+ },
160
163
  get objectCount() {
161
164
  return this.DATA?.objectCount;
162
165
  },