odant-work 1.0.66 → 1.0.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/#system/package-manifest.json +23 -20
- package/$server/$folder/$class/$structure/handlers/pages/{form/data → data}/$handler/class.js +0 -1
- package/$server/$folder/$class/$structure/handlers/pages/{form/data → data}/$handler/data.js +49 -160
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +15 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +5 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +289 -0
- package/$server/$folder/$class/handlers/pages/storage/$handler/storage.js +21 -21
- package/$server/$folder/handlers/pages/form/$handler/form.js +25 -2
- package/$server/$folder/lib/explorer/explorer.js +14 -3
- package/package.json +1 -1
- package/sources/client/handler.js +8 -1
- package/sources/data/api.js +25 -5
- package/sources/modules/agent/index.js +11 -1
- package/sources/modules/agent/node-rules.js +171 -0
- package/sources/modules/agent/resources.js +1 -0
- package/sources/modules/agent/scheduler.js +75 -17
- package/sources/modules/agent/triggers.js +486 -198
- package/sources/modules/agent/twin-bus.js +163 -0
- package/sources/server/access/gateway.js +2 -1
- package/sources/server/chat-threads.js +60 -0
- package/sources/server/class/feed.js +23 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Серверное управление правилами проактивности ($structure/ai/triggers/*.md)
|
|
3
|
+
* и расписаниями узла (scheduler.js) для куратора BOSS.
|
|
4
|
+
*/
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import fsp from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { loadDocs } from './resources.js';
|
|
9
|
+
import { resetTriggerCache } from './triggers.js';
|
|
10
|
+
import { createSchedule, listSchedules, toggleSchedule, cancelSchedule } from './scheduler.js';
|
|
11
|
+
import { DEV_MODE } from '../../host/config.js';
|
|
12
|
+
import { audit } from '../../server/access/audit.js';
|
|
13
|
+
|
|
14
|
+
const ACCESS_DENIED = 'Доступ запрещён';
|
|
15
|
+
const SAFE_RULE_NAME_RE = /^[A-Za-z0-9\u0400-\u04FF_-]{1,64}$/;
|
|
16
|
+
|
|
17
|
+
async function assertBoss(storage, params = {}) {
|
|
18
|
+
if (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK)
|
|
19
|
+
return;
|
|
20
|
+
const ok = await storage._canViewLocalFeed?.(params);
|
|
21
|
+
if (!ok)
|
|
22
|
+
throw new Error(ACCESS_DENIED);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function ownTriggersDir(storage) {
|
|
26
|
+
const metaDir = storage?.meta_folder?.real_dir || storage?.meta_folder?.dir
|
|
27
|
+
|| (storage?.real_dir ? path.join(storage.real_dir, storage.type || '$class') : '');
|
|
28
|
+
if (!metaDir)
|
|
29
|
+
throw new Error('Не найдена метапапка узла');
|
|
30
|
+
return path.join(metaDir, 'ai', 'triggers');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function yamlScalar(v) {
|
|
34
|
+
if (typeof v === 'boolean' || typeof v === 'number')
|
|
35
|
+
return String(v);
|
|
36
|
+
const s = String(v ?? '');
|
|
37
|
+
if (!s)
|
|
38
|
+
return '""';
|
|
39
|
+
if (/[:#\n"'{}[\]]|^\s|\s$/.test(s))
|
|
40
|
+
return JSON.stringify(s);
|
|
41
|
+
return s;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function serializeTriggerMd({ name, on, class: cls, ext, when, template, approval, as, notify, cooldownSec, maxPerHour, enabled, body }) {
|
|
45
|
+
const lines = ['---'];
|
|
46
|
+
lines.push(`name: ${yamlScalar(name)}`);
|
|
47
|
+
lines.push(`on: ${yamlScalar(Array.isArray(on) ? on.join(', ') : (on || 'db:register'))}`);
|
|
48
|
+
if (cls) lines.push(`class: ${yamlScalar(cls)}`);
|
|
49
|
+
if (ext) lines.push(`ext: ${yamlScalar(ext)}`);
|
|
50
|
+
if (when) lines.push(`when: ${yamlScalar(when)}`);
|
|
51
|
+
if (template) lines.push(`template: ${yamlScalar(template)}`);
|
|
52
|
+
if (approval) lines.push(`approval: true`);
|
|
53
|
+
if (as) lines.push(`as: ${yamlScalar(as)}`);
|
|
54
|
+
const notifyList = Array.isArray(notify) ? notify : String(notify || 'BOSS').split(/[\s,]+/).filter(Boolean);
|
|
55
|
+
lines.push(`notify: [${notifyList.map(yamlScalar).join(', ')}]`);
|
|
56
|
+
if (Number(cooldownSec) > 0) lines.push(`cooldownSec: ${Math.round(Number(cooldownSec))}`);
|
|
57
|
+
lines.push(`maxPerHour: ${Math.max(1, Math.min(500, Number(maxPerHour) || 20))}`);
|
|
58
|
+
if (enabled === false) lines.push(`enabled: false`);
|
|
59
|
+
lines.push('---');
|
|
60
|
+
const text = String(body || '').trim();
|
|
61
|
+
if (text)
|
|
62
|
+
lines.push(text);
|
|
63
|
+
return lines.join('\n') + '\n';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function listNodeRules(storage, params = {}) {
|
|
67
|
+
await assertBoss(storage, params);
|
|
68
|
+
const docs = await loadDocs(storage, 'triggers');
|
|
69
|
+
const ownDir = ownTriggersDir(storage);
|
|
70
|
+
const ownNames = new Set(
|
|
71
|
+
fs.existsSync(ownDir)
|
|
72
|
+
? fs.readdirSync(ownDir).filter(f => f.endsWith('.md')).map(f => f.slice(0, -3))
|
|
73
|
+
: []
|
|
74
|
+
);
|
|
75
|
+
const triggers = [];
|
|
76
|
+
for (const doc of docs.values()) {
|
|
77
|
+
const m = doc.meta || {};
|
|
78
|
+
triggers.push({
|
|
79
|
+
name: doc.name,
|
|
80
|
+
on: m.on || 'save',
|
|
81
|
+
class: m.class || '',
|
|
82
|
+
ext: m.ext || '',
|
|
83
|
+
when: m.when || '',
|
|
84
|
+
template: m.template || '',
|
|
85
|
+
approval: Boolean(m.approval === true || m.approval === 'true'),
|
|
86
|
+
as: m.as || '',
|
|
87
|
+
notify: Array.isArray(m.notify) ? m.notify : String(m.notify || '').split(/[\s,]+/).filter(Boolean),
|
|
88
|
+
cooldownSec: Number(m.cooldownSec) || 0,
|
|
89
|
+
maxPerHour: Number(m.maxPerHour) || 20,
|
|
90
|
+
enabled: m.enabled !== false,
|
|
91
|
+
body: doc.body || '',
|
|
92
|
+
own: ownNames.has(doc.name),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const nodePath = storage?.path || '/';
|
|
96
|
+
const schedules = await listSchedules({ nodePath }).catch(() => []);
|
|
97
|
+
return { triggers, schedules };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function saveNodeRule(storage, params = {}) {
|
|
101
|
+
await assertBoss(storage, params);
|
|
102
|
+
const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
|
|
103
|
+
const name = String(post.name || '').trim().replace(/\.md$/i, '');
|
|
104
|
+
if (!SAFE_RULE_NAME_RE.test(name))
|
|
105
|
+
throw new Error('Недопустимое имя правила (допустимы буквы, цифры, _ и -)');
|
|
106
|
+
|
|
107
|
+
const dir = ownTriggersDir(storage);
|
|
108
|
+
const filePath = path.join(dir, `${name}.md`);
|
|
109
|
+
|
|
110
|
+
if (post.delete === true) {
|
|
111
|
+
if (fs.existsSync(filePath))
|
|
112
|
+
await fsp.rm(filePath, { force: true });
|
|
113
|
+
resetTriggerCache();
|
|
114
|
+
audit('agent_rule_delete', { name, point: storage.path, params });
|
|
115
|
+
return { ok: true, deleted: name };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const uid = storage.constructor?.resolveUid?.(params) || post.as || '';
|
|
119
|
+
const asUid = String(post.as || uid).trim();
|
|
120
|
+
if (!asUid)
|
|
121
|
+
throw new Error('Не указан исполнитель (as) для правила');
|
|
122
|
+
|
|
123
|
+
const md = serializeTriggerMd({
|
|
124
|
+
name,
|
|
125
|
+
on: post.on || 'db:register',
|
|
126
|
+
class: post.class || '',
|
|
127
|
+
ext: post.ext || '',
|
|
128
|
+
when: post.when || '',
|
|
129
|
+
template: post.template || '',
|
|
130
|
+
approval: Boolean(post.approval),
|
|
131
|
+
as: asUid,
|
|
132
|
+
notify: post.notify || ['BOSS'],
|
|
133
|
+
cooldownSec: post.cooldownSec || 0,
|
|
134
|
+
maxPerHour: post.maxPerHour || 20,
|
|
135
|
+
enabled: post.enabled !== false,
|
|
136
|
+
body: post.body || '',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
140
|
+
await fsp.writeFile(filePath, md, 'utf8');
|
|
141
|
+
storage?.meta_folder?.reset?.();
|
|
142
|
+
storage?.reset?.();
|
|
143
|
+
resetTriggerCache();
|
|
144
|
+
audit('agent_rule_save', { name, point: storage.path, params });
|
|
145
|
+
return { ok: true, name };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function saveNodeSchedule(storage, params = {}) {
|
|
149
|
+
await assertBoss(storage, params);
|
|
150
|
+
const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
|
|
151
|
+
const nodePath = storage?.path || '/';
|
|
152
|
+
const uid = storage.constructor?.resolveUid?.(params) || String(post.uid || '').trim();
|
|
153
|
+
if (!uid)
|
|
154
|
+
throw new Error('Не определён владелец расписания');
|
|
155
|
+
|
|
156
|
+
if (post.delete === true && post.id) {
|
|
157
|
+
await cancelSchedule({ uid, id: post.id });
|
|
158
|
+
return { ok: true, deleted: post.id };
|
|
159
|
+
}
|
|
160
|
+
if (post.toggle === true && post.id) {
|
|
161
|
+
return toggleSchedule({ id: post.id, enabled: post.enabled });
|
|
162
|
+
}
|
|
163
|
+
return createSchedule({
|
|
164
|
+
uid,
|
|
165
|
+
nodePath,
|
|
166
|
+
label: post.label || 'Задача по расписанию',
|
|
167
|
+
prompt: post.prompt,
|
|
168
|
+
rule: post.rule,
|
|
169
|
+
tz: post.tz,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
@@ -150,6 +150,7 @@ export async function loadDocs(place, sub) {
|
|
|
150
150
|
const folder = await safe(() => dir.get_item(sub));
|
|
151
151
|
if (!folder || Array.isArray(folder))
|
|
152
152
|
continue;
|
|
153
|
+
folder.reset?.();
|
|
153
154
|
const kids = (await safe(() => folder.children, [])) || [];
|
|
154
155
|
for (const f of kids) {
|
|
155
156
|
if (!/\.md$/i.test(f?.id || '') || /^readme\.md$/i.test(f.id))
|
|
@@ -16,7 +16,8 @@ registerSchema(`
|
|
|
16
16
|
CREATE TABLE IF NOT EXISTS agent_schedules(
|
|
17
17
|
id TEXT PRIMARY KEY,
|
|
18
18
|
uid TEXT NOT NULL,
|
|
19
|
-
task TEXT NOT NULL,
|
|
19
|
+
task TEXT NOT NULL DEFAULT '',
|
|
20
|
+
node_path TEXT NOT NULL DEFAULT '',
|
|
20
21
|
label TEXT,
|
|
21
22
|
prompt TEXT NOT NULL,
|
|
22
23
|
rule TEXT NOT NULL,
|
|
@@ -269,23 +270,34 @@ export function describeRule(rule) {
|
|
|
269
270
|
function row2obj(r) {
|
|
270
271
|
const rule = JSON.parse(r.rule);
|
|
271
272
|
return {
|
|
272
|
-
id: r.id, uid: r.uid, task: r.task
|
|
273
|
+
id: r.id, uid: r.uid, task: r.task || '', nodePath: r.node_path || '',
|
|
274
|
+
label: r.label, prompt: r.prompt, rule, when: describeRule(rule), tz: r.tz,
|
|
273
275
|
next: r.next ? new Date(r.next).toISOString() : null,
|
|
274
276
|
last: r.last ? new Date(r.last).toISOString() : null,
|
|
275
277
|
lastError: r.last_error || undefined, enabled: !!r.enabled,
|
|
276
278
|
};
|
|
277
279
|
}
|
|
278
280
|
|
|
281
|
+
let _colChecked = false;
|
|
279
282
|
async function db() {
|
|
280
283
|
const d = await indexDb();
|
|
281
284
|
if (!d)
|
|
282
285
|
throw new Error('расписание недоступно: нет локальной БД (node:sqlite)');
|
|
286
|
+
if (!_colChecked) {
|
|
287
|
+
_colChecked = true;
|
|
288
|
+
try {
|
|
289
|
+
const cols = d.prepare('PRAGMA table_info(agent_schedules)').all().map(c => c.name);
|
|
290
|
+
if (!cols.includes('node_path'))
|
|
291
|
+
d.exec("ALTER TABLE agent_schedules ADD COLUMN node_path TEXT NOT NULL DEFAULT ''");
|
|
292
|
+
}
|
|
293
|
+
catch { /* ignore */ }
|
|
294
|
+
}
|
|
283
295
|
return d;
|
|
284
296
|
}
|
|
285
297
|
|
|
286
|
-
export async function createSchedule({ uid, task, label, prompt, rule, tz }) {
|
|
287
|
-
if (!uid || !task)
|
|
288
|
-
throw new Error('расписание: нужны владелец и задача');
|
|
298
|
+
export async function createSchedule({ uid, task = '', nodePath = '', label, prompt, rule, tz }) {
|
|
299
|
+
if (!uid || (!task && !nodePath))
|
|
300
|
+
throw new Error('расписание: нужны владелец и задача или узел (nodePath)');
|
|
289
301
|
const text = String(prompt || '').trim();
|
|
290
302
|
if (!text || text.length > 4000)
|
|
291
303
|
throw new Error('prompt: 1–4000 символов');
|
|
@@ -298,19 +310,34 @@ export async function createSchedule({ uid, task, label, prompt, rule, tz }) {
|
|
|
298
310
|
if (!next)
|
|
299
311
|
throw new Error('время запуска уже прошло');
|
|
300
312
|
const id = randomUUID().slice(0, 8);
|
|
301
|
-
d.prepare('INSERT INTO agent_schedules(id, uid, task, label, prompt, rule, tz, next, enabled, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)')
|
|
302
|
-
.run(id, uid, task, String(label || text.split('\n')[0]).slice(0, 120), text, JSON.stringify(r), tz, next, Date.now());
|
|
313
|
+
d.prepare('INSERT INTO agent_schedules(id, uid, task, node_path, label, prompt, rule, tz, next, enabled, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)')
|
|
314
|
+
.run(id, uid, String(task || ''), String(nodePath || ''), String(label || text.split('\n')[0]).slice(0, 120), text, JSON.stringify(r), tz, next, Date.now());
|
|
303
315
|
return row2obj(d.prepare('SELECT * FROM agent_schedules WHERE id = ?').get(id));
|
|
304
316
|
}
|
|
305
317
|
|
|
306
|
-
export async function listSchedules({ uid, task } = {}) {
|
|
318
|
+
export async function listSchedules({ uid, task, nodePath } = {}) {
|
|
307
319
|
const d = await db();
|
|
320
|
+
if (nodePath) {
|
|
321
|
+
const rows = d.prepare('SELECT * FROM agent_schedules WHERE node_path = ? ORDER BY next').all(String(nodePath));
|
|
322
|
+
return rows.map(row2obj);
|
|
323
|
+
}
|
|
308
324
|
const rows = task
|
|
309
325
|
? d.prepare('SELECT * FROM agent_schedules WHERE uid = ? AND task = ? ORDER BY next').all(uid, task)
|
|
310
326
|
: d.prepare('SELECT * FROM agent_schedules WHERE uid = ? ORDER BY next').all(uid);
|
|
311
327
|
return rows.map(row2obj);
|
|
312
328
|
}
|
|
313
329
|
|
|
330
|
+
export async function toggleSchedule({ id, enabled }) {
|
|
331
|
+
const d = await db();
|
|
332
|
+
const row = d.prepare('SELECT * FROM agent_schedules WHERE id = ?').get(String(id));
|
|
333
|
+
if (!row)
|
|
334
|
+
throw new Error('расписание ' + id + ' не найдено');
|
|
335
|
+
const nextEnabled = enabled == null ? (row.enabled ? 0 : 1) : (enabled ? 1 : 0);
|
|
336
|
+
const next = nextEnabled ? nextRun(JSON.parse(row.rule), row.tz) : row.next;
|
|
337
|
+
d.prepare('UPDATE agent_schedules SET enabled = ?, next = ? WHERE id = ?').run(nextEnabled, next, String(id));
|
|
338
|
+
return row2obj(d.prepare('SELECT * FROM agent_schedules WHERE id = ?').get(String(id)));
|
|
339
|
+
}
|
|
340
|
+
|
|
314
341
|
export async function cancelSchedule({ uid, id }) {
|
|
315
342
|
const d = await db();
|
|
316
343
|
const res = d.prepare('DELETE FROM agent_schedules WHERE id = ? AND uid = ?').run(String(id), uid);
|
|
@@ -352,6 +379,46 @@ async function defaultRunner(r) {
|
|
|
352
379
|
user = user[0];
|
|
353
380
|
if (!user)
|
|
354
381
|
throw new Error('нет пользователя ' + r.uid);
|
|
382
|
+
const sendToUser = (msg) => {
|
|
383
|
+
const sessions = WORK?.constructor?.sessions || {};
|
|
384
|
+
for (const s of Object.values(sessions)) {
|
|
385
|
+
if (s?.uid === r.uid && typeof s.send === 'function') {
|
|
386
|
+
try { s.send(msg); } catch { /* ignore */ }
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
const session = { uid: r.uid, $user: user, principal: Object.freeze({ kind: 'user', id: r.uid }), scheduled: true, sockets: {}, send: sendToUser };
|
|
391
|
+
|
|
392
|
+
// Расписание уровня узла $structure (без привязки к файлу .task)
|
|
393
|
+
if (r.node_path && !r.task) {
|
|
394
|
+
let nodeItem = await WORK.get_item(r.node_path).catch(() => null);
|
|
395
|
+
if (Array.isArray(nodeItem))
|
|
396
|
+
nodeItem = nodeItem.at(-1);
|
|
397
|
+
if (!nodeItem)
|
|
398
|
+
throw new Error('нет узла ' + r.node_path);
|
|
399
|
+
const roles = await nodeItem.roles?.({ session }).catch(() => []);
|
|
400
|
+
if (!roles.length)
|
|
401
|
+
throw new Error('Доступ запрещён');
|
|
402
|
+
const stamp = new Date().toLocaleString('ru-RU', { timeZone: r.tz || undefined });
|
|
403
|
+
const { runOnce } = await import('./index.js');
|
|
404
|
+
const res = await runOnce({
|
|
405
|
+
place: nodeItem,
|
|
406
|
+
session,
|
|
407
|
+
prompt: '[по расписанию «' + r.label + '», ' + stamp + ']\n' + r.prompt,
|
|
408
|
+
mode: 'ask',
|
|
409
|
+
signal: AbortSignal.timeout(10 * 60_000),
|
|
410
|
+
});
|
|
411
|
+
const answer = String(res?.content || '').trim() || (res?.status === 'error' ? 'ошибка выполнения' : 'без результата');
|
|
412
|
+
const CHAT = await import('../../server/chat-threads.js');
|
|
413
|
+
await CHAT.sendMessage(nodeItem, {
|
|
414
|
+
uid: r.uid,
|
|
415
|
+
asTwin: true,
|
|
416
|
+
kind: 'text',
|
|
417
|
+
message: `[по расписанию «${r.label}»] ${answer}`,
|
|
418
|
+
}).catch(() => {});
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
|
|
355
422
|
let file = await WORK.get_item(r.task);
|
|
356
423
|
if (Array.isArray(file))
|
|
357
424
|
file = file.at(-1);
|
|
@@ -362,15 +429,6 @@ async function defaultRunner(r) {
|
|
|
362
429
|
}
|
|
363
430
|
// сессия владельца (внутренняя, без cookie): те же права, что при ручном сообщении;
|
|
364
431
|
// события стрима пробрасываем во все живые WS-сессии владельца, чтобы открытый чат сразу видел ответ
|
|
365
|
-
const sendToUser = (msg) => {
|
|
366
|
-
const sessions = WORK?.constructor?.sessions || {};
|
|
367
|
-
for (const s of Object.values(sessions)) {
|
|
368
|
-
if (s?.uid === r.uid && typeof s.send === 'function') {
|
|
369
|
-
try { s.send(msg); } catch { /* ignore */ }
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
};
|
|
373
|
-
const session = { uid: r.uid, $user: user, principal: Object.freeze({ kind: 'user', id: r.uid }), scheduled: true, sockets: {}, send: sendToUser };
|
|
374
432
|
await file.assertAccess({ session }, 'read');
|
|
375
433
|
const { getBody, idle } = await import('./session.js');
|
|
376
434
|
const beforeBody = await getBody(file).catch(() => null);
|