odant-work 1.0.103 → 1.0.105

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 (72) hide show
  1. package/$server/$folder/$class/$ai/handlers/pages/form/system/ai/$handler/class.js +15 -12
  2. package/$server/$folder/$class/$module/$mcp/handlers/pages/form/system/mcp/$handler/class.js +17 -24
  3. package/$server/$folder/$class/$module/$provider/handlers/pages/form/system/ai/$handler/class.js +15 -12
  4. package/$server/$folder/$class/$structure/$project/class.js +39 -5
  5. package/$server/$folder/$class/$structure/$project/handlers/pages/form/system/modules/$handler/class.js +40 -25
  6. package/$server/$folder/$class/$structure/$project/handlers/pages/form/system/requisites/$handler/class.js +1 -0
  7. package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/license/$handler/class.js +13 -12
  8. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/agent/$handler/class.js +11 -1
  9. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/messengers/$handler/class.js +11 -1
  10. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/profile/$handler/class.js +1 -0
  11. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/requisites/$handler/class.js +3 -0
  12. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/settings/$handler/class.js +261 -0
  13. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/skills/$handler/class.js +11 -1
  14. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/tokens/$handler/class.js +2 -0
  15. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/users/$handler/class.js +1 -0
  16. package/$server/$folder/$class/$structure/class.js +15 -0
  17. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +17 -4
  18. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +19 -40
  19. package/$server/$folder/$class/$structure/handlers/pages/form/system/database/$handler/class.js +1 -0
  20. package/$server/$folder/$class/$structure/handlers/pages/form/system/messengers/$handler/class.js +1 -0
  21. package/$server/$folder/$class/$structure/handlers/pages/form/system/skills/$handler/class.js +276 -179
  22. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +1 -0
  23. package/$server/$folder/$class/ai/system.md +2 -2
  24. package/$server/$folder/$class/class.js +5 -1
  25. package/$server/$folder/$class/handlers/pages/form/system/requisites/$handler/class.js +39 -45
  26. package/$server/$folder/$file/$html/handlers/preview/$handler/preview.js +7 -0
  27. package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +11 -0
  28. package/$server/$folder/$file/$md/handlers/preview/$handler/preview.js +29 -8
  29. package/$server/$folder/$file/$office/handlers/preview/$handler/preview.js +6 -0
  30. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +34 -2
  31. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +14 -11
  32. package/$server/$folder/$file/$task/handlers/preview/$handler/preview.js +1 -0
  33. package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +9 -0
  34. package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +15 -0
  35. package/$server/$folder/handlers/pages/form/$handler/class.js +187 -3
  36. package/$server/$folder/handlers/pages/form/folder/$handler/class.js +3 -114
  37. package/$server/$folder/lib/explorer/explorer.js +63 -0
  38. package/$server/$folder/lib/folder-browser/folder-browser.js +793 -0
  39. package/$server/$folder/lib/folder-browser/readme.md +5 -0
  40. package/$server/$folder/lib/tree/tree.js +61 -20
  41. package/AGENTS.md +2 -2
  42. package/MODULES/$domain/handlers/pages/form/system/mcp/$handler/class.js +10 -21
  43. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/handlers/pages/form/system/engine/$handler/class.js +1 -0
  44. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/handlers/pages/form/system/models/$handler/class.js +5 -10
  45. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/handlers/pages/form/system/training/$handler/class.js +1 -0
  46. 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/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/241/321/207/321/221/321/202 /320/275/320/260 /320/276/320/277/320/273/320/260/321/202/321/203.html" +5 -1
  47. 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/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/242/320/276/320/262/320/260/321/200/320/275/320/260/321/217 /320/275/320/260/320/272/320/273/320/260/320/264/320/275/320/260/321/217.html" +1 -1
  48. package/NODES/$node/handlers/pages/form/network/$handler/class.js +552 -36
  49. package/oda/components/icon/icon.js +20 -7
  50. package/oda/components/layouts/editor-form/editor-form.js +54 -9
  51. package/package.json +1 -1
  52. package/sources/client.js +24 -0
  53. package/sources/data/print.js +27 -3
  54. package/sources/host/websocket.js +28 -1
  55. package/sources/modules/agent/index.js +25 -6
  56. package/sources/modules/agent/permissions.js +4 -2
  57. package/sources/modules/agent/scope.js +72 -5
  58. package/sources/modules/agent/session.js +59 -6
  59. package/sources/modules/agent/tools/work/classes.js +16 -1
  60. package/sources/modules/license/index.js +120 -0
  61. package/sources/modules/nodes/registry.js +57 -7
  62. package/sources/modules/trainer/local-engine.js +22 -9
  63. package/sources/modules/user-profile/user-profile.js +0 -129
  64. package/sources/modules/user-profile/user-tokens.js +381 -86
  65. package/sources/server/access/gateway.js +32 -5
  66. package/sources/server/class/base-template.js +18 -18
  67. package/sources/server/class.js +9 -0
  68. package/sources/server/folder.js +5 -1
  69. package/sources/server/handler.js +6 -0
  70. package/sources/server/node.js +16 -0
  71. package/sources/server/server.js +14 -5
  72. package/sources/server/user.js +3 -0
@@ -150,16 +150,29 @@ ODA({is: 'oda-icon',
150
150
  this.bb = undefined;
151
151
  if (this.iconTag === 'image')
152
152
  return;
153
- const bb = this.bb;
154
- if ((!bb || !bb.height || !bb.width) && !this[R].states.sleep) {
155
- this._icon.error = e;
156
- this._index += 1;
157
- }
153
+ const checkBox = () => {
154
+ const bb = this.bb;
155
+ if ((!bb || !bb.height || !bb.width) && !this[R]?.states?.sleep) {
156
+ if (this._index + 1 < this._icons_list.length) {
157
+ this._icon.error = e;
158
+ this._index += 1;
159
+ }
160
+ else {
161
+ this.bb = undefined;
162
+ }
163
+ }
164
+ };
165
+ if (typeof requestAnimationFrame === 'function')
166
+ requestAnimationFrame(checkBox);
167
+ else
168
+ checkBox();
158
169
  },
159
170
  _onError(e){
160
171
  this.bb = undefined;
161
- this._icon.error = e;
162
- this._index += 1;
172
+ if (this._icon)
173
+ this._icon.error = e;
174
+ if (this._index + 1 < this._icons_list.length)
175
+ this._index += 1;
163
176
  },
164
177
  // $listeners:{
165
178
  // wake(e) {
@@ -5,8 +5,44 @@ import { CONTROLS, controlOf } from '/oda/components/structure/controls-map.js';
5
5
  /** Типы полей (паритет FORM_SPEC_TYPES + Table как текстовый, DateTime с временем, File). */
6
6
  export const EDITOR_FIELD_TYPES = ['String', 'Text', 'Number', 'Date', 'DateTime', 'Boolean', 'Select', 'Radio', 'Table', 'Link', 'Struct', 'File'];
7
7
 
8
- const COMPACT_FIELD_RE = /^(time|date|doc_date|valid_from|until|num|number|doc_num|doc_number|order_number|in_num|doc_n|num_d|invoice_n|sum|amount|total|price|qty|count|nds|nds_rate|nds_sum|vat|vat_sum|inn|kpp|ogrn|okpo|bik|priority|order|turn|status|phone|tel|email|code|personnel_number|salary)$/i;
9
- const FULL_WIDTH_FIELD_RE = /^(comment|descript|description|base|reason|purpose|content|note|notes|address|legal_address|fact_address|details|requisites|rekvizity)$/i;
8
+ const COMPACT_FIELD_RE = /^(time|date|doc_date|valid_from|until|num|number|doc_num|doc_number|order_number|in_num|doc_n|num_d|invoice_n|sum|amount|total|price|qty|count|nds|nds_rate|nds_sum|vat|vat_sum|inn|kpp|ogrn|okpo|okato|oktmo|bik|priority|order|turn|status|phone|tel|email|code|personnel_number|salary)$/i;
9
+ const FULL_WIDTH_FIELD_RE = /^(comment|descript|description|base|reason|purpose|content|note|notes|address|legal_address|fact_address|actual_address|postal_address|details|requisites|rekvizity)$/i;
10
+
11
+ const WORK_FIELD_TYPE_MAP = Object.freeze({
12
+ string: 'String',
13
+ text: 'Text',
14
+ number: 'Number',
15
+ money: 'Number',
16
+ integer: 'Number',
17
+ int: 'Number',
18
+ boolean: 'Boolean',
19
+ bool: 'Boolean',
20
+ date: 'Date',
21
+ datetime: 'DateTime',
22
+ timestamp: 'DateTime',
23
+ time: 'DateTime',
24
+ select: 'Select',
25
+ enum: 'Select',
26
+ radio: 'Radio',
27
+ table: 'Table',
28
+ array: 'Table',
29
+ link: 'Link',
30
+ ref: 'Link',
31
+ struct: 'Struct',
32
+ structure: 'Struct',
33
+ file: 'File',
34
+ });
35
+
36
+ function normalizeEditorType(f) {
37
+ if (f?.table === true)
38
+ return 'Table';
39
+ if (EDITOR_FIELD_TYPES.includes(f?.type))
40
+ return f.type;
41
+ const raw = String(f?.type || '').trim();
42
+ if (raw.startsWith('/'))
43
+ return 'Link';
44
+ return WORK_FIELD_TYPE_MAP[raw.toLowerCase()] || 'String';
45
+ }
10
46
 
11
47
  /** Умная дефолтная ширина поля в 12-колоночной сетке (как в классическом ODANT). */
12
48
  export function defaultFieldSpan(field) {
@@ -37,7 +73,8 @@ function cleanField(f, seen) {
37
73
  if (!id || seen.has(id))
38
74
  return null;
39
75
  seen.add(id);
40
- const type = EDITOR_FIELD_TYPES.includes(f.type) ? f.type : 'String';
76
+ const rawType = String(f.type || '').trim().toLowerCase();
77
+ const type = normalizeEditorType(f);
41
78
  const field = {
42
79
  id,
43
80
  label: String(f.label || id).trim(),
@@ -45,12 +82,19 @@ function cleanField(f, seen) {
45
82
  required: f.required === true,
46
83
  placeholder: String(f.placeholder || ''),
47
84
  };
85
+ if (rawType === 'money' || f.formatMoney === true)
86
+ field.formatMoney = true;
87
+ if (f.width !== undefined)
88
+ field.width = f.width;
48
89
  if (f.span || f.colSpan)
49
90
  field.span = defaultFieldSpan(f);
50
91
  if (f.disabled === true)
51
92
  field.disabled = true;
52
- if (typeof f.catalog === 'string' && f.catalog.trim())
53
- field.catalog = f.catalog.trim();
93
+ const cat = typeof f.catalog === 'string' && f.catalog.trim()
94
+ ? f.catalog.trim()
95
+ : (typeof (f.targetPath || f.target) === 'string' && (f.targetPath || f.target).trim() ? (f.targetPath || f.target).trim() : (typeof f.type === 'string' && f.type.startsWith('/') ? f.type : ''));
96
+ if (cat)
97
+ field.catalog = cat;
54
98
  if (f.analytic === true)
55
99
  field.analytic = true;
56
100
  const rawList = f.list !== undefined ? f.list : ((type !== 'Select' && type !== 'Radio') ? (f.items ?? f.options) : undefined);
@@ -60,9 +104,9 @@ function cleanField(f, seen) {
60
104
  field.allowOther = Boolean(f.allowOther);
61
105
  }
62
106
  if (type === 'Select' || type === 'Radio') {
63
- const rawOpts = Array.isArray(f.options) ? f.options : (Array.isArray(f.items) ? f.items : (Array.isArray(f.list) ? f.list : []));
107
+ const rawOpts = Array.isArray(f.options) ? f.options : (Array.isArray(f.values) ? f.values : (Array.isArray(f.items) ? f.items : (Array.isArray(f.list) ? f.list : [])));
64
108
  field.options = rawOpts
65
- .map(o => o && typeof o === 'object' ? o : { value: String(o ?? ''), label: String(o ?? '') })
109
+ .map(o => o && typeof o === 'object' ? { value: o.value ?? o.id ?? '', label: o.label ?? o.value ?? o.id ?? '', desc: o.desc || '' } : { value: String(o ?? ''), label: String(o ?? '') })
66
110
  .filter(o => o && String(o.value ?? '').trim() !== '')
67
111
  .map(o => ({
68
112
  value: String(o.value).trim(),
@@ -86,9 +130,10 @@ function cleanField(f, seen) {
86
130
  const childSeen = new Set();
87
131
  field.children = rawChildren.map(c => cleanField(c, childSeen)).filter(Boolean);
88
132
  }
89
- if (type === 'Table' && Array.isArray(f.columns)) {
133
+ const rawCols = type === 'Table' ? (Array.isArray(f.columns) ? f.columns : (Array.isArray(f.fields) ? f.fields : null)) : null;
134
+ if (rawCols) {
90
135
  const colSeen = new Set();
91
- field.columns = f.columns.map(c => {
136
+ field.columns = rawCols.map(c => {
92
137
  const clean = cleanField(c, colSeen);
93
138
  if (!clean)
94
139
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.103",
3
+ "version": "1.0.105",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/sources/client.js CHANGED
@@ -843,6 +843,30 @@ class WebSocketEvents {
843
843
  }
844
844
  WORK.chatEvents.dispatchEvent(new CustomEvent('task.moved', { detail: data }));
845
845
  } break;
846
+ case 'node.deleted': {
847
+ WORK.chatEvents ??= new EventTarget();
848
+ const delPath = String(data.path || '').replace(/\/+$/, '');
849
+ const parentPath = String(data.parentPath || '/').replace(/\/+$/, '') || '/';
850
+ if (delPath) {
851
+ for (const [k, item] of Object.entries(CORE.$item.ITEMS || {})) {
852
+ const ip = String(item?.short || item?.path || k).replace(/\/+$/, '');
853
+ if (ip === delPath || ip.startsWith(delPath + '/')) {
854
+ try { item.fire?.('node.deleted', data); } catch { /* ignore */ }
855
+ delete CORE.$item.ITEMS[k];
856
+ }
857
+ }
858
+ const parentItem = CORE.$item.ITEMS[parentPath] || (parentPath === '/' ? CORE.$item.ITEMS[''] : null);
859
+ if (parentItem) {
860
+ const LISTS = parentItem.constructor.LISTS || CORE.$item.LISTS;
861
+ for (const key of LISTS) {
862
+ delete parentItem[key];
863
+ Reactor.invalidate(parentItem, key);
864
+ }
865
+ parentItem.fire?.('changed');
866
+ }
867
+ }
868
+ WORK.chatEvents.dispatchEvent(new CustomEvent('node.deleted', { detail: data }));
869
+ } break;
846
870
  case 'chat:message':
847
871
  case 'chat:read': {
848
872
  WORK.chatEvents ??= new EventTarget();
@@ -285,8 +285,8 @@ function partyOf(body, out, objs) {
285
285
  };
286
286
  }
287
287
 
288
- /** Реквизиты проекта/организации: название и значения из class.js корня `$project` (ИНН, КПП, адрес, банк …). */
289
- const ORG_FIELDS = ['full_name', 'inn', 'kpp', 'ogrn', 'okpo', 'okato', 'address', 'phone', 'email', 'director', 'chief_accountant', 'bank', 'bik', 'account', 'corr'];
288
+ /** Реквизиты проекта/организации: название и значения из class.js корня `$project` (ИНН, КПП, адрес, счета, подписанты …). */
289
+ const ORG_FIELDS = ['full_name', 'inn', 'kpp', 'ogrn', 'okpo', 'okato', 'address', 'actual_address', 'phone', 'email', 'director_title', 'director', 'chief_accountant', 'bank', 'bik', 'account', 'corr'];
290
290
 
291
291
  function orgOf(db, op = null) {
292
292
  const bp = (op?.cid && classBasePath(db, op.cid)) || (op?.unit && classBasePath(db, op.unit)) || '';
@@ -295,6 +295,30 @@ function orgOf(db, op = null) {
295
295
  const org = { name: root?.label ?? '' };
296
296
  for (const k of ORG_FIELDS)
297
297
  org[k] = own[k] == null ? '' : String(own[k]);
298
+ const accounts = Array.isArray(own.bank_accounts)
299
+ ? own.bank_accounts
300
+ .filter(r => r && typeof r === 'object' && (r.bank || r.bik || r.account || r.corr || r.name))
301
+ .map(r => ({
302
+ name: String(r.name ?? ''),
303
+ bank: String(r.bank ?? ''),
304
+ bik: String(r.bik ?? ''),
305
+ account: String(r.account ?? r.num ?? ''),
306
+ corr: String(r.corr ?? ''),
307
+ is_default: Boolean(r.is_default),
308
+ }))
309
+ : [];
310
+ org.bank_accounts = accounts;
311
+ const opAcct = String(op?.body?.acct ?? op?.body?.org_account ?? '').trim();
312
+ const chosen = (opAcct && accounts.find(a => a.account === opAcct))
313
+ || accounts.find(a => a.is_default)
314
+ || accounts[0]
315
+ || null;
316
+ if (chosen) {
317
+ org.bank = chosen.bank || org.bank;
318
+ org.bik = chosen.bik || org.bik;
319
+ org.account = chosen.account || org.account;
320
+ org.corr = chosen.corr || org.corr;
321
+ }
298
322
  return org;
299
323
  }
300
324
 
@@ -420,7 +444,7 @@ function buildStarterTemplateForSchema(schema) {
420
444
  ${scalarRows}
421
445
  </table>${tableBlocks}
422
446
  <div class="sign">
423
- <div>Руководитель {{org.director}}</div>
447
+ <div>{{coalesce(org.director_title, 'Руководитель')}} {{org.director}}</div>
424
448
  <div>Главный бухгалтер {{org.chief_accountant}}</div>
425
449
  </div>
426
450
  </body>
@@ -17,7 +17,17 @@ export function sameOrigin(req) {
17
17
  if (!origin)
18
18
  return true;
19
19
  try {
20
- return new URL(origin).host === String(req?.headers?.host || '').trim();
20
+ const strip = s => String(s || '').trim().toLowerCase().replace(/:(?:80|443)$/, '');
21
+ const oHost = strip(new URL(origin).host);
22
+ const hHost = strip(req?.headers?.host || req?.headers?.[':authority'] || '');
23
+ if (hHost && oHost === hHost)
24
+ return true;
25
+ const fwd = strip(String(req?.headers?.['x-forwarded-host'] || '').split(',')[0]);
26
+ const addr = String(req?.socket?.remoteAddress || req?.connection?.remoteAddress || '').trim();
27
+ const isLoop = addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
28
+ if (fwd && (isLoop || req?.headers?.['x-forwarded-proto']) && oHost === fwd)
29
+ return true;
30
+ return false;
21
31
  }
22
32
  catch {
23
33
  return false;
@@ -104,6 +114,23 @@ export function broadcastUserSettings(uid, settings) {
104
114
  }
105
115
  }
106
116
 
117
+ /** Разослать активным сессиям событие удаления узла/класса дерева. */
118
+ export function broadcastNodeDeleted(nodePath, parentPath = '/') {
119
+ const clean = String(nodePath || '').replace(/\/+$/, '');
120
+ if (!clean || clean === '/')
121
+ return;
122
+ const parentClean = String(parentPath || '/').replace(/\/+$/, '') || '/';
123
+ const raw = JSON.stringify({ type: 'node.deleted', path: clean, parentPath: parentClean });
124
+ for (const session of allSessions()) {
125
+ if (!session?.uid)
126
+ continue;
127
+ for (const sock of Object.values(session.sockets || {})) {
128
+ if (sock?.ws?.readyState === 1)
129
+ sock.ws.send(raw);
130
+ }
131
+ }
132
+ }
133
+
107
134
  export function onWebSocketConnect(ws, request) {
108
135
  // Настоящий Chrome пользователя через расширение MV3: авторизуется токеном wmcp. (без cookies)
109
136
  if (String(request?.url || '').split('?')[0] === '/~chrome') {
@@ -297,7 +297,11 @@ export async function listAvailableChatModels() {
297
297
  const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
298
298
  const name = String(m.id || m.DATA?.label || m.label || m.path || '');
299
299
  const label = String(m.DATA?.label || m.label || m.id || m.path || '');
300
- const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
300
+ const proto = String(m.protocol || m.DATA?.protocol || '').toLowerCase();
301
+ const wfmt = String(m.weightFormat || m.DATA?.weightFormat || '').toLowerCase();
302
+ const isCompactOrPythonLocal = /(?:^|[-_\s])(4b|2b|1\.7b|0\.6b)(?:$|[-_\s])/i.test(name)
303
+ || (String(provider.id || '').toLowerCase() === 'local' && proto !== 'halogen' && wfmt !== 'gguf' && !/flash-next/i.test(name));
304
+ const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name) && !isCompactOrPythonLocal;
301
305
  out.push({
302
306
  path: m.path,
303
307
  label: provLabel ? `${label} (${provLabel})` : label,
@@ -310,12 +314,15 @@ export async function listAvailableChatModels() {
310
314
  return out;
311
315
  }
312
316
 
313
- /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
317
+ /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор и не Python-малютка). */
314
318
  export async function findFirstAvailableChatModel() {
315
319
  const list = await listAvailableChatModels();
316
320
  const def = list.find(m => m.active && m.default);
317
321
  if (def)
318
322
  return def.path;
323
+ const flash = list.find(m => m.active && /flash-next/i.test(m.path));
324
+ if (flash)
325
+ return flash.path;
319
326
  const primary = list.find(m => m.isPrimary);
320
327
  if (primary)
321
328
  return primary.path;
@@ -629,14 +636,26 @@ export async function createEnv({ place, contextPath, session, host, tz, locatio
629
636
  return [stable, volatile].filter(Boolean).join('\n\n');
630
637
  },
631
638
  async defaultModel() {
632
- const candidate = remapModelPath(config.model || DEFAULT_MODEL);
633
- const item = await WORK.get_item(candidate).catch(() => null);
639
+ if (config.model) {
640
+ const candidate = remapModelPath(config.model);
641
+ const item = await WORK.get_item(candidate).catch(() => null);
642
+ if (item) {
643
+ await item.init?.catch?.(() => {});
644
+ if (typeof item.streamChat === 'function')
645
+ return candidate;
646
+ }
647
+ }
648
+ const first = await findFirstAvailableChatModel();
649
+ if (first)
650
+ return first;
651
+ const fallback = remapModelPath(DEFAULT_MODEL);
652
+ const item = await WORK.get_item(fallback).catch(() => null);
634
653
  if (item) {
635
654
  await item.init?.catch?.(() => {});
636
655
  if (typeof item.streamChat === 'function')
637
- return candidate;
656
+ return fallback;
638
657
  }
639
- return (await findFirstAvailableChatModel()) || candidate;
658
+ return fallback;
640
659
  },
641
660
  /** Память изменена инструментом memory — пересобрать блок на следующем ходе. */
642
661
  resetMemory() {
@@ -193,11 +193,13 @@ export function resolveApprovalScope(tool, args, ctx) {
193
193
  }
194
194
  if (tool.name === 'shell')
195
195
  return classifyShellCommand(args?.command);
196
+ if (tool.risk === 'danger')
197
+ return { noAlways: true, key: tool.name, label: '', buttonLabel: '' };
196
198
  const title = tool.label || tool.name;
197
199
  return {
198
200
  key: tool.name,
199
201
  label: 'все вызовы «' + title + '» в этой задаче',
200
- buttonLabel: 'Разрешить в задаче',
202
+ buttonLabel: 'Больше не спрашивать в этой задаче',
201
203
  };
202
204
  }
203
205
 
@@ -262,7 +264,7 @@ export async function decide(tool, args, ctx) {
262
264
  if (hit)
263
265
  return { verdict: 'ask', noAlways: true, reason: 'изменение системы: ' + hit };
264
266
  if (tool.risk === 'danger')
265
- return { verdict: 'ask', reason: 'необратимое или внешнее действие', ...(scope?.noAlways ? { noAlways: true } : { scope }) };
267
+ return { verdict: 'ask', noAlways: true, reason: 'необратимое или внешнее действие' };
266
268
  if (allowedMatches(host, tool.name, scope))
267
269
  return { verdict: 'allow', autoAllowed: true, scopeKey: scope?.key || tool.name, scopeLabel: scope?.label || '' };
268
270
  if (mode === 'ask')
@@ -186,6 +186,13 @@ function isAllowedUpwardRead(normPath, tool, ctx) {
186
186
  return false;
187
187
  }
188
188
 
189
+ function parentPathOf(normPath) {
190
+ const segs = String(normPath || '').split('/').filter(Boolean);
191
+ return segs.length > 1 ? '/' + segs.slice(0, -1).join('/') : '/';
192
+ }
193
+
194
+ const DESTRUCTIVE_OR_MOVE_TOOLS = new Set(['delete_class', 'move_class', 'delete']);
195
+
189
196
  /**
190
197
  * Классифицировать выход за границы текущего места задачи.
191
198
  * @returns {Promise<{ targetPath: string, reason: string, needAdmin?: boolean, needBoss?: boolean } | null>}
@@ -207,10 +214,54 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
207
214
  };
208
215
  }
209
216
 
217
+ // 1б. Создание класса: дочерние элементы создаются внутри текущего контекста (включая филиалы $project в $project),
218
+ // а создание в вышестоящем родителе/домене переносится в ближайшую вышестоящую структуру.
219
+ if (tool.name === 'create_class') {
220
+ const parentNorm = normalizeWorkPath(absPath(args?.parent || '', ctx));
221
+ if (parentNorm
222
+ && !isOwnCabinetPath(parentNorm, ctx?.session)
223
+ && !isKernelOrTypifierPath(parentNorm)
224
+ && !isGlobalSystemBranch(parentNorm)
225
+ && parentNorm !== placePath
226
+ && !parentNorm.startsWith(placePath + '/')) {
227
+ if (placePath.startsWith(parentNorm + '/') || parentNorm === '/') {
228
+ const resolvedParent = await resolveTargetPlace(parentNorm);
229
+ const targetPath = resolvedParent?.path || '/';
230
+ return {
231
+ targetPath,
232
+ reason: `Создание структуры внутри «${parentNorm}» должно выполняться из вышестоящего узла («${targetPath}»).`,
233
+ needAdmin: targetPath === '/',
234
+ needBoss: true,
235
+ };
236
+ }
237
+ }
238
+ }
239
+
210
240
  const paths = extractToolWorkPaths(tool, args, ctx);
211
241
  if (!paths.length)
212
242
  return null;
213
243
 
244
+ const isDryRunClassOp = (tool.name === 'delete_class' || tool.name === 'move_class') && args?.dry_run === true;
245
+ if (DESTRUCTIVE_OR_MOVE_TOOLS.has(tool.name) && !isDryRunClassOp) {
246
+ for (const p of paths) {
247
+ if (isOwnCabinetPath(p, ctx?.session) || isKernelOrTypifierPath(p))
248
+ continue;
249
+ if (p === placePath || (p !== '/' && placePath.startsWith(p + '/'))) {
250
+ const up = parentPathOf(p);
251
+ const resolvedUp = await resolveTargetPlace(up);
252
+ const targetPath = resolvedUp?.path || '/';
253
+ return {
254
+ targetPath,
255
+ reason: p === placePath
256
+ ? `Удаление или перенос самого текущего узла «${p}» невозможны изнутри него — действие должно выполняться из вышестоящей структуры.`
257
+ : `Удаление или перенос вышестоящего узла «${p}» невозможны из дочернего контекста «${placePath}».`,
258
+ needAdmin: targetPath === '/',
259
+ needBoss: true,
260
+ };
261
+ }
262
+ }
263
+ }
264
+
214
265
  const placeCone = contextConeOf(placePath);
215
266
  const crossTargets = [];
216
267
 
@@ -236,11 +287,15 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
236
287
  continue;
237
288
  const segs = p.split('/').filter(Boolean);
238
289
  if (segs[0].toUpperCase() === 'NODES' && segs[1] && segs[1][0] !== '$') {
239
- return {
240
- targetPath: `/NODES/${segs[1]}`,
241
- reason: `Работа с узлом сети «${segs[1]}» (${p}) должна выполняться в контексте этого узла.`,
242
- needBoss: !tool.readonly,
243
- };
290
+ const nodeRoot = '/' + segs.slice(0, 2).join('/');
291
+ if (placePath !== nodeRoot && !placePath.startsWith(nodeRoot + '/')) {
292
+ return {
293
+ targetPath: nodeRoot,
294
+ reason: `Работа с узлом сети «${segs[1]}» (${p}) должна выполняться в контексте этого узла.`,
295
+ needBoss: !tool.readonly,
296
+ };
297
+ }
298
+ continue;
244
299
  }
245
300
  return {
246
301
  targetPath: '/',
@@ -277,6 +332,15 @@ export async function classifyOutOfScope(tool, args = {}, ctx = {}) {
277
332
  };
278
333
  }
279
334
  }
335
+
336
+ // 6. Изменение строго вышестоящего предка (кроме чтения вверх и редактирования самого текущего узла)
337
+ if (!tool.readonly && !isDryRunClassOp && p !== placePath && p !== '/' && placePath.startsWith(p + '/')) {
338
+ return {
339
+ targetPath: p,
340
+ reason: `Изменение вышестоящего узла «${p}» должно выполняться в его собственном контексте.`,
341
+ needBoss: ['create_class', 'update_class', 'move_class', 'delete_class', 'assign'].includes(tool.name),
342
+ };
343
+ }
280
344
  }
281
345
 
282
346
  if (!crossTargets.length)
@@ -373,6 +437,9 @@ export async function checkOutOfScopeForMove(tool, args = {}, ctx = {}) {
373
437
  if (!scope)
374
438
  return null;
375
439
  const resolved = await resolveTargetPlace(scope.targetPath);
440
+ const placeNorm = normalizeWorkPath(ctx?.contextPath || ctx?.place?.path || '/') || '/';
441
+ if (resolved.path === placeNorm)
442
+ return null;
376
443
  const access = await checkTargetMoveAccess(resolved.node, ctx?.session, {
377
444
  needAdmin: scope.needAdmin,
378
445
  needBoss: scope.needBoss,
@@ -17,7 +17,9 @@
17
17
  * События в UI (session.send): chat.start / chat.done (занятость), task.state { status },
18
18
  * task.delta { item, field, token } (стрим), { path } — файл изменился (перечитать).
19
19
  */
20
+ import fs from 'node:fs';
20
21
  import fsp from 'node:fs/promises';
22
+ import path from 'node:path';
21
23
  import { log } from './log.js';
22
24
  import { runLoop, maybeCompact } from './loop.js';
23
25
  import { createEnv, shouldEnforceAgentLicense } from './index.js';
@@ -125,6 +127,8 @@ export async function getBody(file) {
125
127
  /** Атомарная запись (tmp + rename), с коалесцированием частых сохранений.
126
128
  * На Windows при занятом целевом файле пишем напрямую без unlink, чтобы файл ни на мс не исчезал с диска. */
127
129
  async function save(s, session) {
130
+ if (s.missingOnDisk)
131
+ return;
128
132
  if (s.writing) {
129
133
  s.again = true;
130
134
  return s.writing;
@@ -135,14 +139,31 @@ async function save(s, session) {
135
139
  s.body.updated = Date.now();
136
140
  const text = JSON.stringify(s.body, null, 2);
137
141
  const dir = s.file.dir;
142
+ if (!dir || !fs.existsSync(path.dirname(dir))) {
143
+ s.missingOnDisk = true;
144
+ return;
145
+ }
138
146
  const tmp = dir + '.tmp';
139
147
  try {
140
148
  await WORK.fsp.writeFile(tmp, text, 'utf-8');
141
149
  await WORK.fsp.rename(tmp, dir);
142
150
  }
143
- catch {
144
- await WORK.fsp.writeFile(dir, text, 'utf-8');
145
- await WORK.fsp.unlink(tmp).catch(() => {});
151
+ catch (e) {
152
+ if (e?.code === 'ENOENT' || !fs.existsSync(path.dirname(dir))) {
153
+ s.missingOnDisk = true;
154
+ return;
155
+ }
156
+ try {
157
+ await WORK.fsp.writeFile(dir, text, 'utf-8');
158
+ await WORK.fsp.unlink(tmp).catch(() => {});
159
+ }
160
+ catch (e2) {
161
+ if (e2?.code === 'ENOENT') {
162
+ s.missingOnDisk = true;
163
+ return;
164
+ }
165
+ throw e2;
166
+ }
146
167
  }
147
168
  try {
148
169
  s.file.reset?.(undefined, { selfOnly: true });
@@ -156,7 +177,30 @@ async function save(s, session) {
156
177
  finally {
157
178
  s.writing = null;
158
179
  }
159
- session?.send?.({ path: s.file.short });
180
+ if (!s.missingOnDisk)
181
+ session?.send?.({ path: s.file.short });
182
+ }
183
+
184
+ /** Остановить и очистить в памяти активные задачи внутри удалённого узла. */
185
+ export function invalidateTasksUnder(nodePath) {
186
+ const norm = String(nodePath || '').replace(/\/+$/, '');
187
+ if (!norm || norm === '/')
188
+ return 0;
189
+ let count = 0;
190
+ for (const [k, s] of RUNS.entries()) {
191
+ const p = String(s?.file?.path || s?.body?.contextPath || '').replace(/\/+$/, '');
192
+ if (p === norm || p.startsWith(norm + '/')) {
193
+ count++;
194
+ s.missingOnDisk = true;
195
+ try { s.controller?.abort(); } catch { /* ignore */ }
196
+ for (const resolve of s.waiters?.values?.() || []) {
197
+ try { resolve({ accept: false, content: 'Узел удалён' }); } catch { /* ignore */ }
198
+ }
199
+ s.waiters?.clear?.();
200
+ RUNS.delete(k);
201
+ }
202
+ }
203
+ return count;
160
204
  }
161
205
 
162
206
  function send(s, session, event) {
@@ -617,13 +661,13 @@ function start(s, session, file, licenseOpts = {}) {
617
661
  body.items.push({ ...u, queued: undefined });
618
662
  }
619
663
  restart = rest.length > 0 && !aborted && body.status !== 'error';
620
- await save(s, session);
664
+ await save(s, session).catch(e => log.debug('task.finalSave', e));
621
665
  s.running = null;
622
666
  }
623
667
  }
624
668
  if (movedAway)
625
669
  return;
626
- if (restart) {
670
+ if (restart && !s.missingOnDisk) {
627
671
  start(s, session, file);
628
672
  return;
629
673
  }
@@ -1176,6 +1220,13 @@ export async function approve(file, params = {}) {
1176
1220
  await assertTaskOwner(file, params);
1177
1221
  const s = stateOf(file);
1178
1222
  const p = argsOf(params);
1223
+ if (file?.dir && !fs.existsSync(file.dir)) {
1224
+ for (const resolve of s.waiters.values()) {
1225
+ try { resolve({ accept: false, content: 'Задача или её узел уже удалены' }); } catch { /* ignore */ }
1226
+ }
1227
+ s.waiters.clear();
1228
+ return { ok: false, error: 'Задача или её узел уже удалены' };
1229
+ }
1179
1230
  const body = await getBody(file);
1180
1231
  const call = p.call || body.waiting?.call;
1181
1232
  const reply = {
@@ -1216,6 +1267,8 @@ export async function approve(file, params = {}) {
1216
1267
  export async function explainCall(file, params = {}) {
1217
1268
  await assertTaskOwner(file, params);
1218
1269
  const s = stateOf(file);
1270
+ if (file?.dir && !fs.existsSync(file.dir))
1271
+ return { ok: false, error: 'Задача или её узел уже удалены' };
1219
1272
  const p = argsOf(params);
1220
1273
  const body = await getBody(file);
1221
1274
  const callId = p.call || p.post?.call || body.waiting?.call;
@@ -831,7 +831,7 @@ export const moveClass = {
831
831
  if (isSystemTypifierPath(p))
832
832
  return { verdict: 'ask', noAlways: true, reason: 'перенос/переименование системного типизатора ' + p + ' затронет все классы и формы' };
833
833
  if (isGlobalModulePath(p))
834
- return { verdict: 'ask', reason: 'перенос/переименование общего модуля ' + p + ' затронет все организации' };
834
+ return { verdict: 'ask', noAlways: true, reason: 'перенос/переименование общего модуля ' + p + ' затронет все организации' };
835
835
  return null;
836
836
  },
837
837
  async run(args, ctx) {
@@ -1076,11 +1076,26 @@ export const deleteClass = {
1076
1076
  });
1077
1077
  }
1078
1078
 
1079
+ const taskPath = String(ctx?.task?.path || '').replace(/\/+$/, '');
1080
+ if (taskPath && (taskPath === p || taskPath.startsWith(p + '/'))) {
1081
+ throw new Error(`delete_class: нельзя удалить ${p} из задачи, расположенной внутри этого же узла — перенеси задачу в вышестоящую структуру`);
1082
+ }
1083
+
1079
1084
  if (fs.existsSync(itemRealDir))
1080
1085
  await fsp.rm(itemRealDir, { recursive: true, force: true });
1081
1086
  globalThis.WORK_RAG?.invalidate?.(itemRealDir);
1082
1087
  itemParent?.reset?.();
1083
1088
  await invalidateWorkCaches(p);
1089
+ try {
1090
+ const { invalidateTasksUnder } = await import('../../session.js');
1091
+ invalidateTasksUnder(p);
1092
+ }
1093
+ catch { /* ignore */ }
1094
+ try {
1095
+ const { broadcastNodeDeleted } = await import('../../../../host/websocket.js');
1096
+ broadcastNodeDeleted(p, itemParent?.path || '/');
1097
+ }
1098
+ catch { /* ignore */ }
1084
1099
 
1085
1100
  return `удалён класс ${p} (${itemType}); удалено подклассов: ${subCids.length}`;
1086
1101
  },