cladogram 0.6.0-beta.4 → 0.6.0-beta.6

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.
@@ -0,0 +1,474 @@
1
+ /**
2
+ * Clado Unified System Event Bus & Workspace Automation / Scheduler Engine
3
+ *
4
+ * 负责统一收敛 6 大类系统事件,并支持:
5
+ * 1. 定时周期唤醒(如「记忆记录专员」每 5/10 分钟扫描近 20 分钟活跃会话),内置 onlyIfActive 无活跃零消耗跳过;
6
+ * 2. 事件订阅触发(按事件类型、文件、卡片、Tag、来源角色过滤),内置防自触发、防抖合并与一键全局暂停。
7
+ */
8
+
9
+ import { randomUUID } from 'node:crypto';
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ export const SYSTEM_EVENT_CATALOG = [
14
+ {
15
+ category: 'session',
16
+ label: '会话生命周期',
17
+ events: [
18
+ { type: 'session.turn_completed', description: '某角色完成一轮对话' },
19
+ { type: 'session.turn_stopped', description: '某角色回合被手动停止' },
20
+ { type: 'session.turn_error', description: '某角色回合执行报错' },
21
+ { type: 'session.created', description: '新建主会话' },
22
+ { type: 'session.archived', description: '归档主会话' },
23
+ { type: 'session.message_received', description: '收到跨会话协作消息' },
24
+ { type: 'session.waiting_user', description: '弹出决策卡等待人类拍板' },
25
+ ],
26
+ },
27
+ {
28
+ category: 'canvas',
29
+ label: '画布与卡片变更',
30
+ events: [
31
+ { type: 'doc.created', description: '新建画布文档' },
32
+ { type: 'doc.updated', description: '画布文档更新' },
33
+ { type: 'doc.renamed', description: '画布文档重命名' },
34
+ { type: 'doc.deleted', description: '删除画布文档' },
35
+ { type: 'card.created', description: '画布新增卡片' },
36
+ { type: 'card.updated', description: '画布修改卡片' },
37
+ { type: 'card.deleted', description: '画布删除卡片' },
38
+ { type: 'card.moved', description: '画布移动卡片' },
39
+ { type: 'link.connected', description: '新增跨卡连线' },
40
+ { type: 'link.disconnected', description: '断开跨卡连线' },
41
+ { type: 'tag.changed', description: '语义 Tag 增删改' },
42
+ { type: 'diagnostics.changed', description: '画布拓扑诊断变化' },
43
+ ],
44
+ },
45
+ {
46
+ category: 'code',
47
+ label: '源码与 Git 变更',
48
+ events: [
49
+ { type: 'code.file_changed', description: '工作区源码文件被修改' },
50
+ { type: 'git.diff_changed', description: '工作区 Git Diff 变化' },
51
+ { type: 'git.branch_changed', description: 'Git 分支切换' },
52
+ ],
53
+ },
54
+ {
55
+ category: 'memory',
56
+ label: '记忆与上下文',
57
+ events: [
58
+ { type: 'memory.updated', description: '工作区记忆(AGENTS.md)更新' },
59
+ { type: 'context.compacted', description: '会话上下文完成压缩' },
60
+ ],
61
+ },
62
+ {
63
+ category: 'schedule',
64
+ label: '定时与活跃度',
65
+ events: [
66
+ { type: 'schedule.tick', description: '周期定时唤醒(支持 onlyIfActive 零消耗跳过)' },
67
+ { type: 'workspace.idle', description: '工作区静默空闲达到设定时长' },
68
+ ],
69
+ },
70
+ {
71
+ category: 'human',
72
+ label: '人类显式操作',
73
+ events: [
74
+ { type: 'human.selection_sent', description: '用户框选卡片/片段发给会话' },
75
+ { type: 'human.rollback', description: '用户回退画布快照' },
76
+ { type: 'human.canvas_switched', description: '用户切换当前查看的画布' },
77
+ ],
78
+ },
79
+ ];
80
+
81
+ export const ALL_SYSTEM_EVENT_TYPES = new Set(
82
+ SYSTEM_EVENT_CATALOG.flatMap(g => g.events.map(e => e.type))
83
+ );
84
+
85
+ export const MEMORY_SCRIBE_PRESET = {
86
+ id: 'auto_memory_scribe',
87
+ name: '记忆记录专员 · 定时沉淀工作区记忆',
88
+ enabled: true,
89
+ trigger: {
90
+ type: 'schedule',
91
+ intervalMinutes: 10,
92
+ onlyIfActive: true,
93
+ activeWindowMinutes: 20,
94
+ eventTypes: ['schedule.tick'],
95
+ filter: {},
96
+ },
97
+ target: {
98
+ roleId: 'archivist',
99
+ sessionId: '',
100
+ prompt: '请调用 clado_session_list(sinceMinutes: 20) 扫描工作区最近 20 分钟内活跃过的其他会话,按需用 clado_session_read 读取关键讨论、代码/画布变更与已确认决策,去重整理后增量更新到工作区根目录 AGENTS.md 记忆文件中。若无实质新共识则简短说明即可。',
101
+ },
102
+ debounceMs: 4000,
103
+ };
104
+
105
+ function automationsPath(stateDir) {
106
+ return join(stateDir, 'automations.json');
107
+ }
108
+
109
+ export function readAutomationsState(stateDir) {
110
+ const file = automationsPath(stateDir);
111
+ if (!existsSync(file)) return { paused: false, rules: [] };
112
+ try {
113
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
114
+ return {
115
+ paused: Boolean(raw?.paused),
116
+ rules: Array.isArray(raw?.rules) ? raw.rules : [],
117
+ };
118
+ } catch {
119
+ return { paused: false, rules: [] };
120
+ }
121
+ }
122
+
123
+ export function writeAutomationsState(stateDir, data) {
124
+ if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true });
125
+ const payload = {
126
+ paused: Boolean(data?.paused),
127
+ rules: Array.isArray(data?.rules) ? data.rules : [],
128
+ };
129
+ writeFileSync(automationsPath(stateDir), JSON.stringify(payload, null, 2) + '\n', 'utf8');
130
+ return payload;
131
+ }
132
+
133
+ export function normalizeAutomationRule(input = {}, existing = null) {
134
+ const id = String(input.id || existing?.id || ('auto_' + randomUUID().replace(/-/g, '').slice(0, 10)))
135
+ .trim()
136
+ .replace(/[^a-zA-Z0-9_-]/g, '');
137
+ if (!id) throw new Error('自动化规则 ID 不能为空。');
138
+
139
+ const name = String(input.name || existing?.name || '自定义唤醒规则').trim().slice(0, 80);
140
+ const triggerIn = input.trigger && typeof input.trigger === 'object' ? input.trigger : (existing?.trigger || {});
141
+ const type = triggerIn.type === 'event' ? 'event' : 'schedule';
142
+ const intervalMinutes = Math.max(1, Math.min(1440, Math.round(Number(triggerIn.intervalMinutes ?? 10) || 10)));
143
+ const activeWindowMinutes = Math.max(1, Math.min(1440, Math.round(Number(triggerIn.activeWindowMinutes ?? 20) || 20)));
144
+ const idleMinutes = Math.max(1, Math.min(240, Math.round(Number(triggerIn.idleMinutes ?? 15) || 15)));
145
+ const onlyIfActive = triggerIn.onlyIfActive !== false;
146
+ const eventTypes = type === 'schedule'
147
+ ? ['schedule.tick']
148
+ : [...new Set(
149
+ (Array.isArray(triggerIn.eventTypes) ? triggerIn.eventTypes : [])
150
+ .map(s => String(s || '').trim())
151
+ .filter(s => s === '*' || ALL_SYSTEM_EVENT_TYPES.has(s))
152
+ )];
153
+ if (type === 'event' && !eventTypes.length) {
154
+ throw new Error('事件订阅规则至少需要选择一个系统事件类型。');
155
+ }
156
+
157
+ const fIn = triggerIn.filter && typeof triggerIn.filter === 'object' ? triggerIn.filter : {};
158
+ const filter = {
159
+ ...(fIn.file ? { file: String(fIn.file).trim() } : {}),
160
+ ...(fIn.card ? { card: String(fIn.card).trim() } : {}),
161
+ ...(fIn.tag ? { tag: String(fIn.tag).trim() } : {}),
162
+ ...(fIn.roleId ? { roleId: String(fIn.roleId).trim() } : {}),
163
+ };
164
+
165
+ const targetIn = input.target && typeof input.target === 'object' ? input.target : (existing?.target || {});
166
+ const roleId = String(targetIn.roleId || 'archivist').trim();
167
+ const sessionId = String(targetIn.sessionId || '').trim();
168
+ const prompt = String(targetIn.prompt || '').trim();
169
+ if (!prompt) throw new Error('请填写唤醒该角色时要执行的任务指令。');
170
+
171
+ const debounceMs = Math.max(0, Math.min(120000, Math.round(Number(input.debounceMs ?? existing?.debounceMs ?? 4000) || 4000)));
172
+
173
+ return {
174
+ id,
175
+ name,
176
+ enabled: input.enabled !== undefined ? Boolean(input.enabled) : (existing ? Boolean(existing.enabled) : true),
177
+ trigger: {
178
+ type,
179
+ intervalMinutes,
180
+ onlyIfActive,
181
+ activeWindowMinutes,
182
+ idleMinutes,
183
+ eventTypes,
184
+ filter,
185
+ },
186
+ target: { roleId, sessionId, prompt },
187
+ debounceMs,
188
+ lastRunAt: existing?.lastRunAt || '',
189
+ lastCheckedAt: existing?.lastCheckedAt || '',
190
+ lastSkipReason: existing?.lastSkipReason || '',
191
+ runCount: existing?.runCount || 0,
192
+ skipCount: existing?.skipCount || 0,
193
+ createdAt: existing?.createdAt || new Date().toISOString(),
194
+ updatedAt: new Date().toISOString(),
195
+ };
196
+ }
197
+
198
+ export function saveAutomationRule(stateDir, input) {
199
+ const cur = readAutomationsState(stateDir);
200
+ const idx = input?.id ? cur.rules.findIndex(r => r.id === input.id) : -1;
201
+ const nextRule = normalizeAutomationRule(input, idx >= 0 ? cur.rules[idx] : null);
202
+ if (idx >= 0) cur.rules[idx] = nextRule;
203
+ else cur.rules.push(nextRule);
204
+ writeAutomationsState(stateDir, cur);
205
+ return { rule: nextRule, state: cur };
206
+ }
207
+
208
+ export function deleteAutomationRule(stateDir, ruleId) {
209
+ const cur = readAutomationsState(stateDir);
210
+ const before = cur.rules.length;
211
+ cur.rules = cur.rules.filter(r => r.id !== ruleId);
212
+ writeAutomationsState(stateDir, cur);
213
+ return { deleted: cur.rules.length < before, state: cur };
214
+ }
215
+
216
+ export function setAutomationsPaused(stateDir, paused) {
217
+ const cur = readAutomationsState(stateDir);
218
+ cur.paused = Boolean(paused);
219
+ writeAutomationsState(stateDir, cur);
220
+ return cur;
221
+ }
222
+
223
+ function matchesRuleFilter(rule, payload = {}) {
224
+ const f = rule.trigger?.filter || {};
225
+ if (f.file) {
226
+ const pFile = String(payload.file || '').trim();
227
+ if (!pFile || !pFile.includes(f.file)) return false;
228
+ }
229
+ if (f.card) {
230
+ const pCard = String(payload.card || '').trim();
231
+ const pCards = Array.isArray(payload.cards) ? payload.cards.map(c => String(c || '')) : [];
232
+ const hit = (pCard && pCard.includes(f.card)) || pCards.some(c => c.includes(f.card));
233
+ if (!hit) return false;
234
+ }
235
+ if (f.tag) {
236
+ const tags = [
237
+ ...(Array.isArray(payload.addedTags) ? payload.addedTags : []),
238
+ ...(Array.isArray(payload.removedTags) ? payload.removedTags : []),
239
+ ...(payload.tag ? [String(payload.tag)] : []),
240
+ ];
241
+ if (!tags.some(t => String(t).includes(f.tag))) return false;
242
+ }
243
+ if (f.roleId) {
244
+ const pRole = String(payload.originRoleId || payload.roleId || '').trim();
245
+ if (pRole !== f.roleId) return false;
246
+ }
247
+ return true;
248
+ }
249
+
250
+ function isSelfTriggered(rule, payload = {}) {
251
+ if (payload.automationRuleId && payload.automationRuleId === rule.id) return true;
252
+ if (rule.target?.sessionId && payload.originSessionId && payload.originSessionId === rule.target.sessionId) return true;
253
+ if (rule.target?.roleId && payload.originRoleId && payload.originRoleId === rule.target.roleId) return true;
254
+ return false;
255
+ }
256
+
257
+ export function createAutomationEngine({
258
+ resolveStateDir,
259
+ listSessionsForStateDir,
260
+ onTrigger,
261
+ events,
262
+ tickIntervalMs = 30000,
263
+ autoStartTimer = true,
264
+ } = {}) {
265
+ const knownWorkspaces = new Set();
266
+ const debounceBuckets = new Map(); // `${ws}::${ruleId}` -> { timer, events: [] }
267
+ const activeRuns = new Set(); // `${ws}::${ruleId}`
268
+ const lastActivityByWs = new Map(); // ws -> { ts, idleFiredForTs }
269
+
270
+ function registerWorkspace(workspace) {
271
+ if (workspace) knownWorkspaces.add(workspace);
272
+ }
273
+
274
+ function updateRuleStats(stateDir, ruleId, patch) {
275
+ const state = readAutomationsState(stateDir);
276
+ const r = state.rules.find(x => x.id === ruleId);
277
+ if (!r) return null;
278
+ Object.assign(r, patch);
279
+ writeAutomationsState(stateDir, state);
280
+ return r;
281
+ }
282
+
283
+ async function executeRule(workspace, rule, triggerMeta = {}) {
284
+ const key = `${workspace}::${rule.id}`;
285
+ if (activeRuns.has(key)) return { ok: false, skipped: true, reason: '规则正在执行中,已合并防重入。' };
286
+ const stateDir = resolveStateDir?.(workspace);
287
+ if (!stateDir) return { ok: false, skipped: true, reason: '工作区未就绪。' };
288
+
289
+ activeRuns.add(key);
290
+ const nowIso = new Date().toISOString();
291
+ try {
292
+ updateRuleStats(stateDir, rule.id, {
293
+ lastRunAt: nowIso,
294
+ lastCheckedAt: nowIso,
295
+ lastSkipReason: '',
296
+ runCount: (rule.runCount || 0) + 1,
297
+ });
298
+ events?.emit(workspace, 'automation.triggered', {
299
+ ruleId: rule.id,
300
+ ruleName: rule.name,
301
+ roleId: rule.target.roleId,
302
+ reason: triggerMeta.reason || 'event',
303
+ ts: Date.now(),
304
+ });
305
+ if (typeof onTrigger === 'function') {
306
+ await onTrigger({ workspace, stateDir, rule, triggerMeta });
307
+ }
308
+ return { ok: true, ruleId: rule.id, triggeredAt: nowIso };
309
+ } finally {
310
+ activeRuns.delete(key);
311
+ }
312
+ }
313
+
314
+ function notifyEvent(workspace, eventType, payload = {}) {
315
+ if (!workspace || !eventType) return;
316
+ registerWorkspace(workspace);
317
+ const stateDir = resolveStateDir?.(workspace);
318
+ if (!stateDir) return;
319
+
320
+ if (eventType !== 'schedule.tick' && eventType !== 'workspace.idle' && !payload.automationRuleId) {
321
+ lastActivityByWs.set(workspace, { ts: Date.now(), idleFiredForTs: 0 });
322
+ }
323
+
324
+ const state = readAutomationsState(stateDir);
325
+ if (state.paused || !state.rules.length) return;
326
+
327
+ for (const rule of state.rules) {
328
+ if (!rule.enabled || rule.trigger?.type !== 'event') continue;
329
+ const types = rule.trigger.eventTypes || [];
330
+ if (!types.includes('*') && !types.includes(eventType)) continue;
331
+ if (isSelfTriggered(rule, payload)) continue;
332
+ if (!matchesRuleFilter(rule, payload)) continue;
333
+
334
+ const bKey = `${workspace}::${rule.id}`;
335
+ let bucket = debounceBuckets.get(bKey);
336
+ if (!bucket) {
337
+ bucket = { timer: null, events: [] };
338
+ debounceBuckets.set(bKey, bucket);
339
+ }
340
+ bucket.events.push({ type: eventType, payload, ts: Date.now() });
341
+ if (bucket.events.length > 20) bucket.events.shift();
342
+
343
+ if (bucket.timer) clearTimeout(bucket.timer);
344
+ const delay = Math.max(0, Number(rule.debounceMs) || 0);
345
+ const flush = () => {
346
+ const current = debounceBuckets.get(bKey);
347
+ debounceBuckets.delete(bKey);
348
+ if (!current || !current.events.length) return;
349
+ const latestState = readAutomationsState(stateDir);
350
+ const latestRule = latestState.rules.find(r => r.id === rule.id);
351
+ if (latestState.paused || !latestRule || !latestRule.enabled) return;
352
+ executeRule(workspace, latestRule, {
353
+ reason: 'event',
354
+ events: current.events,
355
+ }).catch(() => {});
356
+ };
357
+ if (delay <= 0) flush();
358
+ else {
359
+ bucket.timer = setTimeout(flush, delay);
360
+ bucket.timer.unref?.();
361
+ }
362
+ }
363
+ }
364
+
365
+ async function evaluateSchedules(nowMs = Date.now(), targetWorkspaces = null) {
366
+ const wsList = targetWorkspaces ? [...targetWorkspaces] : [...knownWorkspaces];
367
+ const results = [];
368
+ for (const ws of wsList) {
369
+ const stateDir = resolveStateDir?.(ws);
370
+ if (!stateDir) continue;
371
+ const state = readAutomationsState(stateDir);
372
+ if (state.paused) continue;
373
+
374
+ // 1. Check workspace.idle event triggers
375
+ const act = lastActivityByWs.get(ws);
376
+ if (act && act.ts && act.idleFiredForTs !== act.ts) {
377
+ const idleRules = state.rules.filter(r => r.enabled && r.trigger?.type === 'event' && (r.trigger.eventTypes || []).includes('workspace.idle'));
378
+ for (const ir of idleRules) {
379
+ const needMs = (ir.trigger.idleMinutes || 15) * 60_000;
380
+ if (nowMs - act.ts >= needMs) {
381
+ act.idleFiredForTs = act.ts;
382
+ notifyEvent(ws, 'workspace.idle', { idleMinutes: ir.trigger.idleMinutes || 15, lastActivityAt: new Date(act.ts).toISOString() });
383
+ }
384
+ }
385
+ }
386
+
387
+ // 2. Check periodic schedule rules
388
+ for (const rule of state.rules) {
389
+ if (!rule.enabled || rule.trigger?.type !== 'schedule') continue;
390
+ const intervalMs = Math.max(1, rule.trigger.intervalMinutes || 10) * 60_000;
391
+ const lastCheckMs = rule.lastCheckedAt ? Date.parse(rule.lastCheckedAt) : (rule.createdAt ? Date.parse(rule.createdAt) : 0);
392
+ if (lastCheckMs && (nowMs - lastCheckMs) < intervalMs) continue;
393
+
394
+ const nowIso = new Date(nowMs).toISOString();
395
+ if (rule.trigger.onlyIfActive !== false) {
396
+ const winMs = Math.max(1, rule.trigger.activeWindowMinutes || 20) * 60_000;
397
+ const lastRunMs = rule.lastRunAt ? Date.parse(rule.lastRunAt) : 0;
398
+ const cutoff = Math.max(lastRunMs, nowMs - winMs);
399
+ const allSessions = typeof listSessionsForStateDir === 'function' ? (listSessionsForStateDir(stateDir) || []) : [];
400
+ const recentActive = allSessions.filter(s => {
401
+ if (!s || s.archived) return false;
402
+ if (rule.target?.sessionId && s.id === rule.target.sessionId) return false;
403
+ if (rule.target?.roleId && s.roleId === rule.target.roleId) return false;
404
+ const uMs = s.updatedAt ? Date.parse(s.updatedAt) : 0;
405
+ const hasMsgs = (s.messageCount || (Array.isArray(s.messages) ? s.messages.length : 0)) > 0;
406
+ return hasMsgs && uMs > cutoff;
407
+ });
408
+ if (!recentActive.length) {
409
+ updateRuleStats(stateDir, rule.id, {
410
+ lastCheckedAt: nowIso,
411
+ lastSkipReason: '无新增活跃会话,已零消耗跳过',
412
+ skipCount: (rule.skipCount || 0) + 1,
413
+ });
414
+ results.push({ workspace: ws, ruleId: rule.id, skipped: true, reason: 'onlyIfActive' });
415
+ continue;
416
+ }
417
+ const r = await executeRule(ws, rule, {
418
+ reason: 'schedule',
419
+ activeWindowMinutes: rule.trigger.activeWindowMinutes || 20,
420
+ activeSessions: recentActive.map(s => ({ id: s.id, title: s.title, roleId: s.roleId, updatedAt: s.updatedAt })),
421
+ });
422
+ results.push({ workspace: ws, ...r });
423
+ } else {
424
+ const r = await executeRule(ws, rule, {
425
+ reason: 'schedule',
426
+ activeWindowMinutes: rule.trigger.activeWindowMinutes || 20,
427
+ });
428
+ results.push({ workspace: ws, ...r });
429
+ }
430
+ }
431
+ }
432
+ return results;
433
+ }
434
+
435
+ async function runRuleNow(workspace, ruleId) {
436
+ registerWorkspace(workspace);
437
+ const stateDir = resolveStateDir?.(workspace);
438
+ if (!stateDir) throw new Error('工作区未就绪。');
439
+ const state = readAutomationsState(stateDir);
440
+ const rule = state.rules.find(r => r.id === ruleId);
441
+ if (!rule) throw new Error('找不到对应的自动化规则。');
442
+ return await executeRule(workspace, rule, {
443
+ reason: 'manual',
444
+ activeWindowMinutes: rule.trigger?.activeWindowMinutes || 20,
445
+ });
446
+ }
447
+
448
+ let timer = null;
449
+ if (autoStartTimer && tickIntervalMs > 0) {
450
+ timer = setInterval(() => {
451
+ evaluateSchedules().catch(() => {});
452
+ }, tickIntervalMs);
453
+ timer.unref?.();
454
+ }
455
+
456
+ function dispose() {
457
+ if (timer) {
458
+ clearInterval(timer);
459
+ timer = null;
460
+ }
461
+ for (const bucket of debounceBuckets.values()) {
462
+ if (bucket.timer) clearTimeout(bucket.timer);
463
+ }
464
+ debounceBuckets.clear();
465
+ }
466
+
467
+ return {
468
+ registerWorkspace,
469
+ notifyEvent,
470
+ evaluateSchedules,
471
+ runRuleNow,
472
+ dispose,
473
+ };
474
+ }
@@ -156,10 +156,17 @@ export function createCladoPiTools({
156
156
  events = null,
157
157
  emit = () => {},
158
158
  waitForUserAnswer = null,
159
+ sessionOps = null,
160
+ automationOps = null,
161
+ onCardChanges = null,
159
162
  }) {
160
163
  const runMcp = async (tool, input = {}) => {
161
164
  if (!workspaceService) throw new Error('Clado workspaceService 未就绪。');
162
- return workspaceService(tool, { workspace, ...input });
165
+ const res = await workspaceService(tool, { workspace, ...input });
166
+ if (res && typeof onCardChanges === 'function' && (Array.isArray(res.cardChanges) || ['create', 'update', 'delete', 'insert', 'rename', 'move', 'connect', 'disconnect'].includes(input.action))) {
167
+ try { onCardChanges(tool, res); } catch {}
168
+ }
169
+ return res;
163
170
  };
164
171
 
165
172
  const inspectGraphCheck = async file => {
@@ -629,5 +636,157 @@ export function createCladoPiTools({
629
636
  }
630
637
  },
631
638
  }),
639
+
640
+ ...(sessionOps ? [
641
+ defineTool({
642
+ name: 'clado_session_list',
643
+ label: '列出主会话',
644
+ description: '列出当前工作空间内所有主会话(角色、状态、最近活跃时间、消息数与摘要),支持传 sinceMinutes(如 20)只看最近 N 分钟内活跃的会话。',
645
+ promptSnippet: '列出工作区主会话(支持 sinceMinutes 过滤最近活跃会话)',
646
+ parameters: {
647
+ type: 'object',
648
+ properties: {
649
+ sinceMinutes: { type: 'number', description: '可选:仅返回最近 N 分钟内活跃过的会话(例如 20)' },
650
+ includeArchived: { type: 'boolean', description: '是否包含已归档会话,默认 false' },
651
+ },
652
+ },
653
+ async execute(_id, params = {}) {
654
+ try {
655
+ const list = await sessionOps.list({
656
+ sinceMinutes: Number(params.sinceMinutes) || 0,
657
+ includeArchived: Boolean(params.includeArchived),
658
+ });
659
+ return textResult({
660
+ currentSessionId: sessionOps.currentSessionId || '',
661
+ count: list.length,
662
+ sessions: list.map(s => ({
663
+ id: s.id,
664
+ title: s.title,
665
+ roleId: s.roleId,
666
+ phase: s.phase,
667
+ status: s.status,
668
+ updatedAt: s.updatedAt,
669
+ messageCount: s.messageCount ?? 0,
670
+ summaryBadge: s.summaryBadge || '',
671
+ lastMessagePreview: s.lastMessagePreview || '',
672
+ })),
673
+ });
674
+ } catch (err) {
675
+ return errorResult('clado_session_list', err);
676
+ }
677
+ },
678
+ }),
679
+
680
+ defineTool({
681
+ name: 'clado_session_read',
682
+ label: '读取会话记录',
683
+ description: '读取工作区中指定主会话的最近 N 轮对话摘要与工具调用记录,用于跨角色同步上下文或「记忆记录专员」扫描沉淀记忆。',
684
+ promptSnippet: '读取指定主会话的最近对话与工具记录',
685
+ parameters: {
686
+ type: 'object',
687
+ properties: {
688
+ sessionId: { type: 'string', description: '目标主会话 ID(可先通过 clado_session_list 获取)' },
689
+ limit: { type: 'number', description: '返回最近多少条消息,默认 12,最大 60' },
690
+ },
691
+ required: ['sessionId'],
692
+ },
693
+ async execute(_id, params = {}) {
694
+ try {
695
+ const transcript = await sessionOps.read({
696
+ sessionId: params.sessionId,
697
+ limit: Number(params.limit) || 12,
698
+ });
699
+ if (!transcript) return errorResult('clado_session_read', new Error(`找不到会话:${params.sessionId}`));
700
+ return textResult(transcript);
701
+ } catch (err) {
702
+ return errorResult('clado_session_read', err);
703
+ }
704
+ },
705
+ }),
706
+
707
+ defineTool({
708
+ name: 'clado_session_open',
709
+ label: '拉起主会话',
710
+ description: '按指定角色 ID 拉起一个新的平等主会话,或复用该角色最近活跃的主会话,供后续通过 clado_session_send 协作交流。',
711
+ promptSnippet: '按角色拉起或复用另一个主会话',
712
+ parameters: {
713
+ type: 'object',
714
+ properties: {
715
+ roleId: { type: 'string', description: '目标角色 ID(如 architect / developer / tester / archivist 或自定义角色 ID)' },
716
+ title: { type: 'string', description: '可选:自定义会话标题' },
717
+ reuseLatest: { type: 'boolean', description: '是否优先复用该角色最近会话(默认 true;设 false 强制新建)' },
718
+ },
719
+ required: ['roleId'],
720
+ },
721
+ async execute(_id, params = {}) {
722
+ try {
723
+ const res = await sessionOps.open({
724
+ roleId: params.roleId,
725
+ title: params.title || '',
726
+ reuseLatest: params.reuseLatest !== false,
727
+ });
728
+ return textResult(res);
729
+ } catch (err) {
730
+ return errorResult('clado_session_open', err);
731
+ }
732
+ },
733
+ }),
734
+
735
+ defineTool({
736
+ name: 'clado_session_send',
737
+ label: '跨会话发消息',
738
+ description: '向工作区中的另一个主会话注入协作消息。若对方空闲则自动唤醒运行;若对方正在运行则以中途插话(steer)方式平滑送达。支持 wait:true 等待对方本轮答复摘要,内置无进展防打转熔断。',
739
+ promptSnippet: '向另一个主会话发送协作消息(唤醒或插话)',
740
+ parameters: {
741
+ type: 'object',
742
+ properties: {
743
+ targetSessionId: { type: 'string', description: '目标主会话 ID(与 targetRoleId 二选一)' },
744
+ targetRoleId: { type: 'string', description: '目标角色 ID(若未传 targetSessionId,则自动定位/拉起该角色主会话)' },
745
+ message: { type: 'string', description: '要发送给对方的清晰协作消息、任务或问题' },
746
+ wait: { type: 'boolean', description: '是否同步等待对方本轮执行完成并返回答复摘要(默认 false,异步唤醒不阻塞)' },
747
+ },
748
+ required: ['message'],
749
+ },
750
+ async execute(_id, params = {}) {
751
+ try {
752
+ const res = await sessionOps.send({
753
+ targetSessionId: params.targetSessionId || '',
754
+ targetRoleId: params.targetRoleId || '',
755
+ message: params.message,
756
+ wait: Boolean(params.wait),
757
+ });
758
+ return textResult(res);
759
+ } catch (err) {
760
+ return errorResult('clado_session_send', err);
761
+ }
762
+ },
763
+ }),
764
+ ] : []),
765
+
766
+ ...(automationOps ? [
767
+ defineTool({
768
+ name: 'clado_automations',
769
+ label: '定时与事件订阅',
770
+ description: '管理当前工作区的定时唤醒任务(如「记忆记录专员」每 10 分钟扫描近 20 分钟活跃会话,支持 onlyIfActive 零消耗跳过)与系统事件订阅触发规则(会话/卡片/Tag/代码/记忆变更)。',
771
+ promptSnippet: '查看或管理工作区定时唤醒与事件订阅规则',
772
+ parameters: {
773
+ type: 'object',
774
+ properties: {
775
+ action: { type: 'string', enum: ['list', 'save', 'delete', 'pause', 'resume', 'run_now', 'events_catalog'], description: '操作类型' },
776
+ ruleId: { type: 'string', description: 'delete / run_now 时的规则 ID' },
777
+ rule: { type: 'object', description: 'save 时的规则配置对象' },
778
+ },
779
+ required: ['action'],
780
+ },
781
+ async execute(_id, params = {}) {
782
+ try {
783
+ const res = await automationOps.handle(params);
784
+ return textResult(res);
785
+ } catch (err) {
786
+ return errorResult('clado_automations', err);
787
+ }
788
+ },
789
+ }),
790
+ ] : []),
632
791
  ];
633
792
  }