odant-work 1.0.93 → 1.0.94

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 (81) hide show
  1. package/#system/package-manifest.json +620 -651
  2. package/$server/$folder/$class/$ai/class.js +1 -0
  3. package/$server/$folder/$class/$ai/handlers/pages/form/system/ai/$handler/class.js +4 -1
  4. package/$server/$folder/$class/$data/$catalog/$virtual/class.js +1 -0
  5. package/$server/$folder/$class/$data/$catalog/class.js +1 -0
  6. package/$server/$folder/$class/$data/$operation/class.js +1 -0
  7. package/$server/$folder/$class/$data/$register/$account/class.js +1 -0
  8. package/$server/$folder/$class/$data/$register/class.js +1 -0
  9. package/$server/$folder/$class/$data/$struct/class.js +1 -0
  10. package/$server/$folder/$class/$domain/class.js +1 -0
  11. package/$server/$folder/$class/$module/$mcp/class.js +1 -0
  12. package/$server/$folder/$class/$module/$provider/class.js +1 -0
  13. package/$server/$folder/$class/$module/$provider/handlers/pages/form/system/ai/$handler/class.js +38 -6
  14. package/$server/$folder/$class/$module/class.js +1 -0
  15. package/$server/$folder/$class/$structure/$project/class.js +1 -0
  16. package/$server/$folder/$class/$structure/$server/class.js +1 -0
  17. package/$server/$folder/$class/$structure/$user/class.js +2 -0
  18. package/$server/$folder/$class/$structure/class.js +1 -0
  19. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +20 -6
  20. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +23 -17
  21. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +35 -3
  22. package/$server/$folder/$class/$structure/handlers/pages/form/system/messengers/$handler/class.js +38 -3
  23. package/$server/$folder/$class/$users/class.js +1 -0
  24. package/$server/$folder/$class/handlers/pages/form/system/requisites/$handler/class.js +95 -24
  25. package/$server/$folder/$class/handlers/pages/storage/$handler/class.js +22 -4
  26. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +4 -3
  27. package/$server/$folder/handlers/pages/form/$handler/class.js +81 -7
  28. package/$server/$folder/lib/explorer/explorer.js +2 -1
  29. package/$server/$folder/lib/icon/icon.js +2 -2
  30. package/$server/$folder/lib/node/node.js +3 -11
  31. package/$server/$folder/lib/prompt-bar/prompt-bar.js +4 -2
  32. package/$server/$folder/lib/tree/tree.js +12 -1
  33. package/MODULES//320/224/320/260/320/275/320/275/321/213/320/265/Geo/$module/class.js +1 -0
  34. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/handlers/pages/form/system/engine/$handler/class.js +445 -0
  35. package/MODULES//320/243/321/207/321/221/321/202 /320/270 /320/277/321/200/320/276/321/206/320/265/321/201/321/201/321/213/Register/$module/class.js" +1 -0
  36. package/package.json +1 -1
  37. package/run.mjs +11 -0
  38. package/scripts/agent-eval.mjs +1 -1
  39. package/scripts/migrate-tree.mjs +9 -438
  40. package/sources/client/class.js +1 -1
  41. package/sources/host/auto-updater.js +34 -24
  42. package/sources/host/tree-migration.js +580 -0
  43. package/sources/host/tree-migration.json +85 -0
  44. package/sources/modules/agent/index.js +23 -10
  45. package/sources/modules/agent/session.js +22 -2
  46. package/sources/modules/agent/tools/meta.js +1 -1
  47. package/sources/modules/agent/voice.js +6 -2
  48. package/sources/modules/trainer/dataset.js +6 -4
  49. package/sources/modules/trainer/halogen.js +9 -9
  50. package/sources/modules/trainer/huggingface.js +1 -1
  51. package/sources/modules/trainer/index.js +25 -5
  52. package/sources/modules/trainer/local-engine.js +17 -11
  53. package/sources/modules/trainer/runner.js +32 -9
  54. package/sources/server/class/distro.js +1 -1
  55. package/sources/server/class.js +8 -0
  56. package/sources/server/folder.js +9 -2
  57. package/$server/$folder/$class/$data/$catalog/$folder/$class/$data/$catalog/$virtual/class.js +0 -4
  58. package/$server/$folder/$class/$data/$catalog/$folder/$class/$data/$catalog/class.js +0 -4
  59. package/$server/$folder/$class/$data/$catalog/$virtual/$folder/$class/$data/$catalog/$virtual/class.js +0 -4
  60. package/$server/$folder/$class/$data/$operation/$folder/$class/$data/$operation/class.js +0 -4
  61. package/$server/$folder/$class/$data/$register/$account/$folder/$class/$data/$register/$account/class.js +0 -4
  62. package/$server/$folder/$class/$data/$register/$folder/$class/$data/$register/$account/class.js +0 -4
  63. package/$server/$folder/$class/$data/$register/$folder/$class/$data/$register/class.js +0 -4
  64. package/$server/$folder/$class/$data/$struct/$folder/$class/$data/$struct/class.js +0 -4
  65. package/$server/$folder/$class/$domain/$folder/$class/$domain/class.js +0 -4
  66. package/$server/$folder/$class/$module/$folder/$class/$data/$catalog/class.js +0 -4
  67. package/$server/$folder/$class/$module/$folder/$class/$data/$operation/class.js +0 -4
  68. package/$server/$folder/$class/$module/$folder/$class/$data/$register/class.js +0 -4
  69. package/$server/$folder/$class/$module/$folder/$class/$data/$struct/class.js +0 -4
  70. package/$server/$folder/$class/$module/$folder/$class/$domain/class.js +0 -4
  71. package/$server/$folder/$class/$module/$folder/$class/$module/class.js +0 -4
  72. package/$server/$folder/$class/$structure/$folder/$class/$structure/class.js +0 -4
  73. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$catalog/class.js +0 -4
  74. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$operation/class.js +0 -4
  75. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$register/class.js +0 -4
  76. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$struct/class.js +0 -4
  77. package/$server/$folder/$class/$structure/$project/$folder/$class/$domain/class.js +0 -4
  78. package/$server/$folder/$class/$structure/$project/$folder/$class/$structure/$project/class.js +0 -4
  79. package/$server/$folder/$class/$structure/$project/$folder/$class/$structure/class.js +0 -4
  80. package/$server/$folder/$class/$structure/$server/$folder/$class/$domain/class.js +0 -4
  81. package/$server/$folder/$class/$users/$folder/$class/$structure/$user/class.js +0 -4
@@ -149,12 +149,25 @@ function restrictCall(tool, methods) {
149
149
  };
150
150
  }
151
151
 
152
+ const MODELS_ROOT = '/' + DEFAULT_MODEL.split('/').filter(Boolean).slice(0, 2).join('/');
153
+
154
+ /** Преобразовать прежний путь модели в актуальный. */
155
+ export function remapModelPath(modelPath) {
156
+ const raw = String(modelPath || '').trim().replace(/\\/g, '/');
157
+ if (!raw)
158
+ return '';
159
+ const norm = raw.startsWith('/') ? raw : '/' + raw;
160
+ if (/^\/MODELS(?:\/|$)/i.test(norm))
161
+ return MODELS_ROOT + norm.slice('/MODELS'.length);
162
+ return raw;
163
+ }
164
+
152
165
  /** Модель WORK → адаптер llm для цикла.
153
166
  * @param {string} modelPath
154
167
  * @returns {Promise<LLM>}
155
168
  */
156
169
  export async function llmFor(modelPath) {
157
- const path = String(modelPath || '').trim();
170
+ const path = remapModelPath(modelPath);
158
171
  if (!path)
159
172
  throw new Error('модель не задана (ai/config.js model или выбор в задаче)');
160
173
  const item = await WORK.get_item(path);
@@ -176,7 +189,7 @@ export async function llmFor(modelPath) {
176
189
  contextTokens: Number(item.maxTokens) || 32000,
177
190
  vision: caps.includes('vision'),
178
191
  fork: caps.includes('fork') || item.protocol === 'halogen',
179
- // 9.2: тарифы модели ($ за миллион токенов) — карточка MODELS pricing: { input, output }
192
+ // 9.2: тарифы модели ($ за миллион токенов) — карточка модели pricing: { input, output }
180
193
  pricing: item.pricing && typeof item.pricing === 'object' ? item.pricing : null,
181
194
  stream({ messages, tools, signal, effort, halogenKeep, halogenFrom, continueFinalMessage }) {
182
195
  /** @type {{ messages: any, temperature?: number, signal?: AbortSignal, tools?: any, maxOutput?: number, effort?: string, halogenKeep?: string, halogenFrom?: string, continueFinalMessage?: boolean }} */
@@ -338,7 +351,7 @@ const ENV_GUIDE = `# Среда WORK
338
351
  - Моделирование и структура: create_class, update_class (предпочитай вместо сырой правки class.js), inspect_class_tree, move_class, delete_class, assign (рабочие места в #security.ROLES и LINKS), escalate.
339
352
  - Учёт и данные: describe_class, find_objects, register_operation, report (для БД организаций), write_table, read_table, import_objects, create_office_file, export_presentation, render_doc.
340
353
  - Планирование и оркестрация: todo_write (в т.ч. задаёт effort: off|low|medium|high), task (субагент с effort), agent_start/status/message/stop, schema → call (прочие методы).
341
- - Ссылки в ответах — только фактическими WORK-путями из результатов (в т.ч. .task/). Код/настройки системы ($server, sources, oda, MODELS, SERVICES, *.js) меняй только с объяснением и подтверждением.
354
+ - Ссылки в ответах — только фактическими WORK-путями из результатов (в т.ч. .task/). Код/настройки системы ($server, sources, oda, MODULES, *.js) меняй только с объяснением и подтверждением.
342
355
  # Внешние сервисы (аккаунты пользователя)
343
356
  - API сервисов: connections → http_request (GET сразу, изменения с подтверждением в reason); нет подключения — connect_service (пароли и токены в чате не проси).
344
357
  - Сайты без API: только в песочнице (browser_*) или Chrome пользователя (chrome_*) по явной просьбе; для паролей/2FA/капч — chrome_handoff; иначе open_page.
@@ -588,10 +601,13 @@ export async function createEnv({ place, contextPath, session, host, tz, locatio
588
601
  return [stable, volatile].filter(Boolean).join('\n\n');
589
602
  },
590
603
  async defaultModel() {
591
- const candidate = config.model || DEFAULT_MODEL;
604
+ const candidate = remapModelPath(config.model || DEFAULT_MODEL);
592
605
  const item = await WORK.get_item(candidate).catch(() => null);
593
- if (item)
594
- return candidate;
606
+ if (item) {
607
+ await item.init?.catch?.(() => {});
608
+ if (typeof item.streamChat === 'function')
609
+ return candidate;
610
+ }
595
611
  return (await findFirstAvailableChatModel()) || candidate;
596
612
  },
597
613
  /** Память изменена инструментом memory — пересобрать блок на следующем ходе. */
@@ -650,10 +666,7 @@ async function placeBlock(place, session, location, contextPath) {
650
666
  lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник подразделения «${label}»${orgName ? ` (организация «${orgName}»)` : ''}, путь ${place.path}. Отвечай и действуй от первого лица этого подразделения.`);
651
667
  }
652
668
  else if (pt === '$project') {
653
- lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник организации «${label}» (${place.path}). Отвечай и действуй от первого лица этой организации.`);
654
- }
655
- else if (pt === '$project') {
656
- lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник проекта «${label}» (${place.path}). Отвечай и действуй от первого лица этого проекта.`);
669
+ lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник проекта/организации «${label}» (${place.path}). Отвечай и действуй от первого лица этого проекта.`);
657
670
  }
658
671
  else if (pt === '$server') {
659
672
  lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник системы WORK (корневой узел /). Отвечай и действуй от первого лица системы WORK.`);
@@ -521,9 +521,29 @@ function start(s, session, file, licenseOpts = {}) {
521
521
  if (body.childAgent && !def)
522
522
  throw new Error('субагент «' + body.childAgent + '» больше не доступен в этой точке');
523
523
  const depth = Math.max(0, Number(body.childDepth) || 0);
524
- const model = body.model || def?.meta.model || await env.defaultModel();
524
+ const rawModel = body.model || def?.meta.model || await env.defaultModel();
525
+ const tryResolveLlm = async (candidate) => {
526
+ if (!candidate)
527
+ return null;
528
+ try {
529
+ const resolved = await env.llmFor(candidate);
530
+ return { path: resolved.name || candidate, llm: resolved };
531
+ }
532
+ catch {
533
+ return null;
534
+ }
535
+ };
536
+ let picked = await tryResolveLlm(rawModel);
537
+ if (!picked && body.model && def?.meta.model)
538
+ picked = await tryResolveLlm(def.meta.model);
539
+ if (!picked) {
540
+ const fallbackDef = await env.defaultModel().catch(() => '');
541
+ if (fallbackDef)
542
+ picked = await tryResolveLlm(fallbackDef);
543
+ }
544
+ const model = picked?.path || rawModel;
525
545
  body.model = model;
526
- const llm = await env.llmFor(model); // 9.1: с запасными моделями (fallbackModels)
546
+ const llm = picked ? picked.llm : await env.llmFor(model); // 9.1: с запасными моделями (fallbackModels)
527
547
  const res = await runLoop({
528
548
  llm,
529
549
  system: () => env.makeSystemParts(def, body.items),
@@ -648,7 +648,7 @@ export const metaTools = [
648
648
  const t = body ? walk(body.items, { turns: 0, prompt: 0, completion: 0, cached: 0, cost: 0, priced: false }) : null;
649
649
  if (t?.turns)
650
650
  out.push('Задача: ' + t.turns + ' ход(ов), ' + (t.prompt + t.completion + t.cached).toLocaleString('ru-RU') + ' токенов'
651
- + (t.priced ? ', ' + money(t.cost) + ' (по тарифам моделей)' : ' (тарифы моделей не заданы — pricing в карточке MODELS)'));
651
+ + (t.priced ? ', ' + money(t.cost) + ' (по тарифам моделей)' : ' (тарифы моделей не заданы — pricing в карточке модели)'));
652
652
  else
653
653
  out.push('Задача: расходов ещё нет (списание — после каждого хода с ответом модели)');
654
654
  // дневной лимит пользователя
@@ -21,11 +21,15 @@ function sanitizeUid(uid) {
21
21
  return s;
22
22
  }
23
23
 
24
+ const MODELS_ROOT = '/MODULES/Модели';
25
+
24
26
  function sanitizeTtsModelPath(raw) {
25
27
  const s = String(raw || '').trim().replace(/\\/g, '/');
26
28
  if (!s || s.length > 240 || s.includes('..'))
27
29
  return '';
28
- const norm = s.startsWith('/') ? s : '/' + s;
30
+ let norm = s.startsWith('/') ? s : '/' + s;
31
+ if (/^\/MODELS(?:\/|$)/i.test(norm))
32
+ norm = MODELS_ROOT + norm.slice('/MODELS'.length);
29
33
  if (!/^\/(?:PROJECTS\/[^/]+\/)?MODULES\/Модели\/[^/]+\/[^/]+$/i.test(norm))
30
34
  return '';
31
35
  return norm;
@@ -203,7 +207,7 @@ async function listActiveTtsItems() {
203
207
  const out = [];
204
208
  const seen = new Set();
205
209
  try {
206
- const modelsRoot = await WORK.get_item('/MODULES/Модели').catch(() => null);
210
+ const modelsRoot = await WORK.get_item(MODELS_ROOT).catch(() => null);
207
211
  for (const prov of (await modelsRoot?.items) || []) {
208
212
  if (!prov || Array.isArray(prov))
209
213
  continue;
@@ -18,6 +18,8 @@ import { previewEntries } from '../../data/posting.js';
18
18
  import { trialBalance, journal } from '../../data/reports.js';
19
19
  import { localDatasetsDir, migrateLocalModelsLayoutSync } from './paths.js';
20
20
 
21
+ const DEFAULT_BASE_PATH = '/PROJECTS/Маслоторг';
22
+
21
23
  const SECRET_PATTERNS = [
22
24
  /\bsk-[A-Za-z0-9_-]{16,}\b/g,
23
25
  /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi,
@@ -74,7 +76,7 @@ export function collectTaskExamples(rootDir = process.cwd()) {
74
76
  const examples = [];
75
77
  const scanDirs = [
76
78
  path.join(rootDir, 'USERS'),
77
- path.join(rootDir, 'ORGANIZATIONS'),
79
+ path.join(rootDir, DEFAULT_BASE_PATH.split('/').filter(Boolean)[0]),
78
80
  ];
79
81
  const taskFiles = [];
80
82
  for (const d of scanDirs)
@@ -115,7 +117,7 @@ export function collectTaskExamples(rootDir = process.cwd()) {
115
117
  /**
116
118
  * 2. Синтез обучающих примеров по реальным данным организации (`work.db`: операции, проводки, ОСВ, справочники).
117
119
  */
118
- export async function collectAccountingExamples(rootDir = process.cwd(), basePath = '/PROJECTS/Маслоторг') {
120
+ export async function collectAccountingExamples(rootDir = process.cwd(), basePath = DEFAULT_BASE_PATH) {
119
121
  const examples = [];
120
122
  try {
121
123
  const db = await dataStore(basePath);
@@ -282,7 +284,7 @@ export async function buildWorkDataset({
282
284
  rootDir = process.cwd(),
283
285
  name = 'work-sft-dataset',
284
286
  sources = ['tasks', 'accounting', 'classes'],
285
- basePath = '/PROJECTS/Маслоторг',
287
+ basePath = DEFAULT_BASE_PATH,
286
288
  } = {}) {
287
289
  const activeSources = new Set(Array.isArray(sources) && sources.length ? sources : ['tasks', 'accounting', 'classes']);
288
290
  const all = [];
@@ -379,7 +381,7 @@ export async function listWorkDatasets(rootDir = process.cwd()) {
379
381
  * и возвращает оценку `reward` в диапазоне `[0.0 .. 1.0]` и список причин `reasons`.
380
382
  */
381
383
  export async function verifyCompletion({
382
- basePath = '/PROJECTS/Маслоторг',
384
+ basePath = DEFAULT_BASE_PATH,
383
385
  taskType = 'operation',
384
386
  completion = '',
385
387
  } = {}) {
@@ -787,25 +787,25 @@ export function computeHalogenMemoryPlan({
787
787
 
788
788
  // Нативная подготовка движка Halowin Bubo (AMD ROCm 10.0.0 gfx1151) и запуск нейросети из её метапапки `$ai/#weights`
789
789
  const windowsPrepareCommand = [
790
- `.\\bubo.exe prepare runtime --runtime-dir "MODELS\\Local\\$provider\\#runtime\\bubo\\runtime\\rocm-10.0.0-gfx1151" --yes`,
790
+ `.\\bubo.exe prepare runtime --runtime-dir "MODULES\\Модели\\Local\\$provider\\#runtime\\bubo\\runtime\\rocm-10.0.0-gfx1151" --yes`,
791
791
  ].join('\n');
792
792
 
793
793
  const windowsCommand = [
794
794
  `bubo.exe serve llm ^`,
795
795
  ` --host 127.0.0.1 --port ${HALOGEN_DEFAULT_PORT} ^`,
796
- ` --model "MODELS\\Local\\Qwen3.8-Flash-Next\\$ai\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" ^`,
796
+ ` --model "MODULES\\Модели\\Local\\Qwen3.8-Flash-Next\\$ai\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" ^`,
797
797
  ` --served-model-name halogen-qwen3.8-flash-next ^`,
798
798
  ` --profile ${kvSlots > 1 ? 'subagents' : 'default'} --context ${contextTokens} ^`,
799
799
  ` --npu-prefill on`,
800
800
  ].join('\n');
801
801
 
802
802
  const windowsGufoServicesCommand = [
803
- `gufo.exe serve --host 127.0.0.1 --port ${HALOGEN_DEFAULT_PORT} llm --model "MODELS\\Local\\Qwen3.8-Flash-Next\\$ai\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" --served-model-name halogen-qwen3.8-flash-next --speculative mtp`,
804
- `gufo.exe serve asr --model "MODELS\\Local\\Qwen3-ASR-NPU\\$ai\\#weights"`,
805
- `gufo.exe serve tts --model "MODELS\\Local\\Qwen3-TTS-NPU\\$ai\\#weights"`,
806
- `gufo.exe serve embedding --model "MODELS\\Local\\Qwen3-Embedding-NPU\\$ai\\#weights"`,
807
- `gufo.exe serve image --model "MODELS\\Local\\Flux2-Klein-NPU\\$ai\\#weights"`,
808
- `gufo.exe serve decision --model "MODELS\\Local\\Decider-NPU\\$ai\\#weights"`,
803
+ `gufo.exe serve --host 127.0.0.1 --port ${HALOGEN_DEFAULT_PORT} llm --model "MODULES\\Модели\\Local\\Qwen3.8-Flash-Next\\$ai\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" --served-model-name halogen-qwen3.8-flash-next --speculative mtp`,
804
+ `gufo.exe serve asr --model "MODULES\\Модели\\Local\\Qwen3-ASR-NPU\\$ai\\#weights"`,
805
+ `gufo.exe serve tts --model "MODULES\\Модели\\Local\\Qwen3-TTS-NPU\\$ai\\#weights"`,
806
+ `gufo.exe serve embedding --model "MODULES\\Модели\\Local\\Qwen3-Embedding-NPU\\$ai\\#weights"`,
807
+ `gufo.exe serve image --model "MODULES\\Модели\\Local\\Flux2-Klein-NPU\\$ai\\#weights"`,
808
+ `gufo.exe serve decision --model "MODULES\\Модели\\Local\\Decider-NPU\\$ai\\#weights"`,
809
809
  ].join('\n');
810
810
 
811
811
  const windowsStrataCommand = `strata launch --family qwen --model iq3_s --port ${HALOGEN_DEFAULT_PORT}`;
@@ -2230,7 +2230,7 @@ export async function startHalogenBackend({
2230
2230
  port,
2231
2231
  windowsEnv: winEnv,
2232
2232
  note: os.platform() === 'win32'
2233
- ? 'Нативный движок Halowin Bubo (bubo.exe) или модель ещё не подготовлены. Нажмите «Установить Halowin Bubo (ROCm 10.0 gfx1151)» во вкладке Halogen; пока работает автономный контур WORK.'
2233
+ ? 'Нативный движок Halowin Bubo (bubo.exe) или модель ещё не подготовлены. Нажмите «Подготовить Windows Runtime» во вкладке «Движок и настройка»; пока работает автономный контур WORK.'
2234
2234
  : 'Контейнер halogen-flash-server не запущен; активирован автономный контур WORK.',
2235
2235
  };
2236
2236
  }
@@ -2169,7 +2169,7 @@ export async function resumeHuggingFaceDownload({
2169
2169
  const stateHasCustomUrls = Array.isArray(state.files) && state.files.some(f => f?.url || f?.destRelPath);
2170
2170
  const resolvedCustomFiles = customFiles ?? entry?.customFiles ?? (stateHasCustomUrls ? state.files : null);
2171
2171
  const rawCustomDir = customFilesDir || entry?.customFilesDir || state.customFilesDir || '';
2172
- const resolvedCustomDir = /^MODELS[\\/]+Local[\\/]+models([\\/]|$)/i.test(rawCustomDir) ? '' : rawCustomDir;
2172
+ const resolvedCustomDir = /(?:^|[\\/])Local[\\/]models([\\/]|$)/i.test(rawCustomDir) ? '' : rawCustomDir;
2173
2173
  const stateFileNames = Array.isArray(state.files) && state.files.length
2174
2174
  ? state.files.map(f => f?.name).filter(Boolean)
2175
2175
  : null;
@@ -906,6 +906,25 @@ async function restartHalogenEngine(settings = null, params = {}) {
906
906
  });
907
907
  }
908
908
 
909
+ const DEFAULT_PROJECT_PATH = '/PROJECTS/Маслоторг';
910
+
911
+ function resolveDefaultProjectBasePath(rootDir = process.cwd()) {
912
+ const rootFolder = DEFAULT_PROJECT_PATH.split('/').filter(Boolean)[0];
913
+ const projectsDir = path.join(rootDir, rootFolder);
914
+ try {
915
+ if (fs.existsSync(projectsDir)) {
916
+ const dirs = fs.readdirSync(projectsDir, { withFileTypes: true })
917
+ .filter(d => d.isDirectory() && !d.name.startsWith('$') && !d.name.startsWith('#'))
918
+ .map(d => d.name)
919
+ .sort((a, b) => a.localeCompare(b, 'ru'));
920
+ if (dirs.length)
921
+ return `/${rootFolder}/${dirs[0]}`;
922
+ }
923
+ }
924
+ catch { /* ignore */ }
925
+ return DEFAULT_PROJECT_PATH;
926
+ }
927
+
909
928
  export const TRAINER_METHODS = Object.freeze({
910
929
  trainer_status: {
911
930
  level: 'read',
@@ -991,7 +1010,7 @@ export const TRAINER_METHODS = Object.freeze({
991
1010
  const d = this?.DATA || {};
992
1011
  const itemPath = String(this?.path || this?.short || '');
993
1012
  const parsedAi = parseAiNodePath(itemPath);
994
- const providerId = parsedAi?.providerId || 'Модели';
1013
+ const providerId = parsedAi?.providerId || 'Local';
995
1014
  const isLocal = providerId === 'Local' || d.protocol === 'local' || d.protocol === 'halogen';
996
1015
  if (isLocal) {
997
1016
  // Миграция раскладки не должна ломать карточку модели (занятые файлы, EBUSY на Windows).
@@ -1224,7 +1243,7 @@ export const TRAINER_METHODS = Object.freeze({
1224
1243
  fn: async function (p = {}) {
1225
1244
  await this?.init;
1226
1245
  const modelId = p.modelId || p.id || this?.id || '';
1227
- const cleanId = String(modelId).replace(/^\/?MODELS\/Local\//i, '').replace(/[<>:"/\\|?*]/g, '').trim();
1246
+ const cleanId = String(modelId).split(/[\\/]/).filter(Boolean).pop()?.replace(/[<>:"/\\|?*]/g, '').trim() || '';
1228
1247
  if (!cleanId)
1229
1248
  throw new Error('Не указана модель');
1230
1249
  const wDir = modelWeightsDir(process.cwd(), cleanId, 'Local');
@@ -1655,7 +1674,7 @@ export const TRAINER_METHODS = Object.freeze({
1655
1674
  return buildWorkDataset({
1656
1675
  name: p.name || 'work-sft-dataset',
1657
1676
  sources,
1658
- basePath: p.basePath || '/PROJECTS/Маслоторг',
1677
+ basePath: p.basePath || resolveDefaultProjectBasePath(),
1659
1678
  });
1660
1679
  },
1661
1680
  },
@@ -1668,11 +1687,12 @@ export const TRAINER_METHODS = Object.freeze({
1668
1687
  trainer_start: {
1669
1688
  level: 'admin',
1670
1689
  fn: async function (p = {}) {
1690
+ const basePath = p.basePath || resolveDefaultProjectBasePath();
1671
1691
  const job = await startTrainingJob({
1672
- adapterName: p.adapterName || 'Маслоторг-Ассистент-LoRA',
1692
+ adapterName: p.adapterName || `${basePath.split('/').pop() || 'work'}-Ассистент-LoRA`,
1673
1693
  baseModel: p.baseModel || '',
1674
1694
  datasetName: p.datasetName || 'work-sft-dataset',
1675
- basePath: p.basePath || '/PROJECTS/Маслоторг',
1695
+ basePath,
1676
1696
  mode: p.mode || 'sft',
1677
1697
  loraR: p.loraR ?? 0,
1678
1698
  loraAlpha: p.loraAlpha ?? 0,
@@ -16,7 +16,7 @@ import { classesOfType } from '../../data/classes.js';
16
16
  import { classSchema } from '../../data/schema.js';
17
17
  import { trialBalance } from '../../data/reports.js';
18
18
  import { ensureHalogenBackendRunning, recordHalogenSessionHandle, stopHalogenBackend } from './halogen.js';
19
- import { inspectWeightsDirectorySync } from './paths.js';
19
+ import { inspectWeightsDirectorySync, modelWeightsDir } from './paths.js';
20
20
  import { loadTrainerNetworkSettings, createNetworkFetch } from './downloader.js';
21
21
 
22
22
  const money = v => Number(v || 0).toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
@@ -92,16 +92,22 @@ export function releaseLocalEngineMemory() {
92
92
 
93
93
  function resolveWeightsDir(ai, rootDir = process.cwd()) {
94
94
  const modelId = String(ai?.id || ai?.label || ai?.model || 'Local-Model').split('/').pop();
95
- const weightsRel = ai?.weightsDir || ai?.DATA?.weightsDir || `MODELS/Local/${modelId}/$ai/#weights`;
96
- const primary = path.resolve(rootDir, weightsRel);
95
+ const primary = ai?.weightsDir || ai?.DATA?.weightsDir
96
+ ? path.resolve(rootDir, ai.weightsDir || ai.DATA.weightsDir)
97
+ : modelWeightsDir(rootDir, modelId, 'Local');
97
98
  if (fs.existsSync(primary))
98
99
  return primary;
99
- const canonical = path.resolve(rootDir, `MODELS/Local/${modelId}/$ai/#weights`);
100
+ const canonical = modelWeightsDir(rootDir, modelId, 'Local');
100
101
  if (fs.existsSync(canonical))
101
102
  return canonical;
102
- const legacy = path.resolve(rootDir, `MODELS/Local/${modelId}/#weights`);
103
- if (fs.existsSync(legacy))
104
- return legacy;
103
+ for (const rel of [
104
+ path.join(path.dirname(path.dirname(canonical)), '#weights'),
105
+ `MODELS/Local/${modelId}/#weights`,
106
+ ]) {
107
+ const candidate = path.resolve(rootDir, rel);
108
+ if (fs.existsSync(candidate))
109
+ return candidate;
110
+ }
105
111
  return primary;
106
112
  }
107
113
 
@@ -147,8 +153,8 @@ function runtimeVenvPython(rootDir = process.cwd()) {
147
153
 
148
154
  function venvPythonCandidates(rootDir = process.cwd()) {
149
155
  const rel = os.platform() === 'win32'
150
- ? ['.venv/Scripts/python.exe', 'venv/Scripts/python.exe', 'MODELS/Local/.venv/Scripts/python.exe']
151
- : ['.venv/bin/python', 'venv/bin/python', 'MODELS/Local/.venv/bin/python'];
156
+ ? ['.venv/Scripts/python.exe', 'venv/Scripts/python.exe', 'MODULES/Модели/Local/.venv/Scripts/python.exe', 'MODELS/Local/.venv/Scripts/python.exe']
157
+ : ['.venv/bin/python', 'venv/bin/python', 'MODULES/Модели/Local/.venv/bin/python', 'MODELS/Local/.venv/bin/python'];
152
158
  return [runtimeVenvPython(rootDir), ...rel.map(r => path.resolve(rootDir, r))];
153
159
  }
154
160
 
@@ -418,7 +424,7 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
418
424
  function makePythonMissingError(detail = '') {
419
425
  const isOffline = /fetch failed|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNREFUSED|network|Не удалось скачать uv/i.test(String(detail || ''));
420
426
  const msg = isOffline
421
- ? 'Не удалось автоматически подготовить среду Python: нет доступа к сети для первичной загрузки изолированного рантайма (MODELS/Local/$provider/#runtime/). Подключите интернет один раз или перенесите готовую папку #runtime с другой машины.'
427
+ ? 'Не удалось автоматически подготовить среду Python: нет доступа к сети для первичной загрузки изолированного рантайма (MODULES/Модели/Local/$provider/#runtime/). Подключите интернет один раз или перенесите готовую папку #runtime с другой машины.'
422
428
  : ('Не удалось автоматически подготовить среду Python' + (detail ? `: ${detail}` : '.'));
423
429
  const err = new Error(msg);
424
430
  err.pythonMissing = true;
@@ -1608,7 +1614,7 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1608
1614
  const rawErr = (res.err || res.out || `Установка завершилась с кодом ${res.code}`).trim();
1609
1615
  const isOffline = /Failed to fetch|Temporary failure|ConnectionError|ConnectTimeout|ENOTFOUND|network/i.test(rawErr);
1610
1616
  const finalErr = isOffline
1611
- ? `Нет доступа к сети для автоматической установки пакетов (${clean.join(', ')}). Подключите интернет один раз или перенесите готовую папку MODELS/Local/$provider/#runtime/.`
1617
+ ? `Нет доступа к сети для автоматической установки пакетов (${clean.join(', ')}). Подключите интернет один раз или перенесите готовую папку MODULES/Модели/Local/$provider/#runtime/.`
1612
1618
  : rawErr;
1613
1619
  _pythonProvisionState = { active: false, stage: '', packages: [], startedAt: 0, lastError: finalErr };
1614
1620
  return { ok: false, packages: clean, error: finalErr };
@@ -323,27 +323,50 @@ export async function listLocalModelsAndAdapters(rootDir = process.cwd()) {
323
323
  const localRoot = localRootDir(rootDir);
324
324
  const legacyHalogenRoot = path.join(rootDir, 'MODULES', 'Модели', 'Halogen');
325
325
 
326
- // Автоматическая миграция и очистка устаревшей дублирующей папки MODELS/Halogen
326
+ // Безопасная миграция устаревшей папки MODULES/Модели/Halogen (объединена с Local) без потери данных
327
327
  if (fs.existsSync(legacyHalogenRoot)) {
328
328
  try {
329
329
  const halEntries = await fsp.readdir(legacyHalogenRoot, { withFileTypes: true }).catch(() => []);
330
+ let allSafeToDelete = true;
330
331
  for (const he of halEntries) {
331
- if (!he.isDirectory() || he.name.startsWith('$') || he.name.startsWith('#'))
332
+ if (he.name.startsWith('$') || he.name.startsWith('#'))
332
333
  continue;
333
- const oldWeights = path.join(legacyHalogenRoot, he.name, '#weights');
334
- if (fs.existsSync(oldWeights)) {
335
- const wf = await fsp.readdir(oldWeights).catch(() => []);
334
+ if (!he.isDirectory()) {
335
+ allSafeToDelete = false;
336
+ continue;
337
+ }
338
+ const oldModelDir = path.join(legacyHalogenRoot, he.name);
339
+ const oldWeights = path.join(oldModelDir, '#weights');
340
+ const oldNestedWeights = modelWeightsDir(rootDir, he.name, 'Halogen');
341
+ const srcWeights = fs.existsSync(oldNestedWeights) ? oldNestedWeights : oldWeights;
342
+ const targetModelDir = path.join(localRoot, he.name);
343
+ if (fs.existsSync(srcWeights)) {
344
+ const wf = await fsp.readdir(srcWeights).catch(() => []);
336
345
  const hasRealWeight = wf.some(f => !f.endsWith('.part') && WEIGHT_FILE_EXT_RE.test(f));
337
346
  if (hasRealWeight) {
338
- const targetModelDir = path.join(localRoot, he.name);
339
347
  if (!fs.existsSync(targetModelDir)) {
340
348
  await fsp.mkdir(localRoot, { recursive: true });
341
- await fsp.cp(path.join(legacyHalogenRoot, he.name), targetModelDir, { recursive: true });
349
+ await fsp.cp(oldModelDir, targetModelDir, { recursive: true });
350
+ await fsp.rm(oldModelDir, { recursive: true, force: true });
351
+ }
352
+ else {
353
+ allSafeToDelete = false;
342
354
  }
343
355
  }
356
+ else {
357
+ allSafeToDelete = false;
358
+ }
359
+ }
360
+ else {
361
+ allSafeToDelete = false;
344
362
  }
345
363
  }
346
- await fsp.rm(legacyHalogenRoot, { recursive: true, force: true });
364
+ if (allSafeToDelete) {
365
+ const rest = await fsp.readdir(legacyHalogenRoot).catch(() => []);
366
+ const nonMeta = rest.filter(n => !n.startsWith('$') && !n.startsWith('#'));
367
+ if (nonMeta.length === 0)
368
+ await fsp.rm(legacyHalogenRoot, { recursive: true, force: true });
369
+ }
347
370
  }
348
371
  catch { /* ignore */ }
349
372
  }
@@ -458,7 +481,7 @@ export async function listLocalModelsAndAdapters(rootDir = process.cwd()) {
458
481
  * Полностью удалить локальную модель `/MODULES/Модели/Local/<modelId>` вместе с её весами `#weights` и узлом `$ai`.
459
482
  */
460
483
  export async function deleteLocalModel({ rootDir = process.cwd(), modelId } = {}) {
461
- const cleanId = String(modelId || '').replace(/^\/?MODELS\/Local\//i, '').replace(/[<>:"/\\|?*]/g, '').trim();
484
+ const cleanId = String(modelId || '').split(/[\\/]/).filter(Boolean).pop()?.replace(/[<>:"/\\|?*]/g, '').trim() || '';
462
485
  if (!cleanId || cleanId.startsWith('$') || cleanId.startsWith('.'))
463
486
  throw new Error('Некорректное имя удаляемой модели: ' + modelId);
464
487
  const targetDir = path.join(rootDir, 'MODULES', 'Модели', 'Local', cleanId);
@@ -440,7 +440,7 @@ export function exportDistroToFolderSync(rootDir, targetDir, opts = {}) {
440
440
  }
441
441
 
442
442
  // Создаём пустые папки-контейнеры для быстрого старта
443
- for (const emptyDir of ['ORGANIZATIONS', 'PROJECTS', 'USERS', 'NODES', 'MODELS/Local', '#system']) {
443
+ for (const emptyDir of ['PROJECTS', 'USERS', 'NODES', 'MODULES/Модели/Local', '#system']) {
444
444
  fs.mkdirSync(path.join(absTarget, emptyDir), { recursive: true });
445
445
  }
446
446
 
@@ -746,6 +746,14 @@ export class $class extends $folder {
746
746
  add(readDeclaredChildTypesSync(dir));
747
747
  }
748
748
  catch { /* без типизатора */ }
749
+ await this.init?.catch?.(() => {});
750
+ const rawAllow = this.DATA?.allowTypes;
751
+ if (typeof rawAllow === 'string') {
752
+ add(rawAllow.split(/[\s,]+/).filter(Boolean));
753
+ }
754
+ else if (Array.isArray(rawAllow)) {
755
+ add(rawAllow);
756
+ }
749
757
  if (myType === '$class' && !declared.length)
750
758
  return ['$class'];
751
759
  return declared;
@@ -11,6 +11,7 @@ import { isUpload } from './upload-mark.js';
11
11
  import { DEV_MODE } from '../host/config.js';
12
12
  import { assertNotMemory } from './memory-mark.js';
13
13
  import { markClassesDirty, classObjectCount } from '../data/api.js';
14
+ import { isModuleType } from './class/module-status.js';
14
15
 
15
16
  function readOwnAncestorSync(metaRealDir) {
16
17
  if (!metaRealDir)
@@ -298,6 +299,10 @@ export class $folder extends $item{
298
299
  if (files.length) {
299
300
  let script = await $server.mergeFiles(files);
300
301
  script = await this.constructor.importScript(script, this.path || this.id);
302
+ // Визуальный компонент (component) — только для клиента; на сервере его реактивация
303
+ // в DATA вызывает браузерные геттеры (ODA.states и т.п.) и роняет инициализацию узла.
304
+ if (script && typeof script === 'object' && Object.prototype.hasOwnProperty.call(script, 'component'))
305
+ delete script.component;
301
306
  if (script)
302
307
  this.DATA = script;
303
308
  }
@@ -306,7 +311,7 @@ export class $folder extends $item{
306
311
  const cnt = await classObjectCount(this.path, this.type);
307
312
  if (cnt > 0 && this.DATA)
308
313
  this.DATA.objectCount = cnt;
309
- if (this.type === '$module' && this.DATA) {
314
+ if (isModuleType(this.type) && this.DATA) {
310
315
  const localEnabled = this._ownModuleEnabledSync();
311
316
  const sysBlocked = await this.isSystemModuleBlocked();
312
317
  this.DATA.localEnabled = localEnabled;
@@ -1200,7 +1205,7 @@ export class $folder extends $item{
1200
1205
  hNodes.unshift(hAnc);
1201
1206
  }
1202
1207
  // Если хендлер лежит внутри метапапки экземпляра (Local/$provider/handlers/pages/form)
1203
- // или внутри вложенного типа-ветки (MODELS/$ai/$folder/$class/$provider/handlers/pages/form),
1208
+ // или внутри вложенного типа-ветки (MODULES/Модели/$ai/$folder/$class/$provider/handlers/pages/form),
1204
1209
  // подбираем одноимённые хендлеры из слоёв владельца (включая базовый /$server/$folder/handlers/pages/form).
1205
1210
  let cur = this;
1206
1211
  const relSegs = [];
@@ -1333,6 +1338,8 @@ export class $folder extends $item{
1333
1338
  if ((this.type === '$domain' && (this.id === 'MODULES' || /\/MODULES$/.test(p)))
1334
1339
  || (this.type === '$folder' && /(?:^|\/)MODULES(?:\/|$)/.test(p)))
1335
1340
  return new Set(['$folder', '$module', '$provider', '$mcp']);
1341
+ if (this.type === '$folder')
1342
+ return null;
1336
1343
  if (this.parent?.type === '$server')
1337
1344
  return ENV_TYPES;
1338
1345
  if (this.type === '$project' || this.type === '$structure')
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:filter',
3
- label: 'Виртуальный справочник',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:catalog',
3
- label: 'Справочник',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:filter',
3
- label: 'Виртуальный справочник',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:task-complete',
3
- label: 'Операция',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:data-base',
3
- label: 'Счёт',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:data-base',
3
- label: 'Счёт',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'lineawesome:journal-whills-solid',
3
- label: 'Журнал проводок',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- icon: 'carbon:data-structured',
3
- label: 'Структура',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Домен',
3
- icon: 'odant:domain',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Справочник',
3
- icon: 'carbon:catalog',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Операция',
3
- icon: 'carbon:task-complete',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Журнал проводок',
3
- icon: 'lineawesome:journal-whills-solid',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Структура',
3
- icon: 'carbon:data-structured',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Домен',
3
- icon: 'odant:domain',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Модуль',
3
- icon: 'odant:module',
4
- }
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Подразделение',
3
- icon: 'odant:structure',
4
- }