cladogram 0.6.0-beta.5 → 0.6.0-beta.7

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.
@@ -810,11 +810,22 @@ body.clado-dock-resizing iframe {
810
810
  display: flex;
811
811
  flex-direction: column;
812
812
  gap: 3px;
813
- max-height: 220px;
813
+ max-height: 268px;
814
814
  overflow-y: auto;
815
815
  z-index: 45;
816
816
  }
817
817
  .clado-dock-popover[hidden] { display: none; }
818
+ .clado-pop-head {
819
+ font-size: 10.5px;
820
+ font-weight: 600;
821
+ color: var(--clado-ui-subtle);
822
+ padding: 3px 10px 4px;
823
+ display: flex;
824
+ align-items: center;
825
+ justify-content: space-between;
826
+ gap: 8px;
827
+ user-select: none;
828
+ }
818
829
  .clado-pop-item {
819
830
  appearance: none;
820
831
  border: 1px solid transparent;
@@ -831,11 +842,49 @@ body.clado-dock-resizing iframe {
831
842
  justify-content: space-between;
832
843
  gap: 8px;
833
844
  }
834
- .clado-pop-item:hover {
845
+ .clado-pop-item:hover,
846
+ .clado-pop-item.is-selected {
835
847
  background: var(--clado-ui-hover);
836
848
  border-color: var(--clado-ui-hover-border);
837
849
  color: var(--clado-ui-text);
838
850
  }
851
+ .clado-pop-item.is-selected {
852
+ background: var(--clado-ui-prism-bg);
853
+ border-color: var(--clado-ui-prism-border);
854
+ }
855
+ .clado-pop-main {
856
+ display: flex;
857
+ align-items: center;
858
+ gap: 7px;
859
+ min-width: 0;
860
+ flex: 1;
861
+ }
862
+ .clado-pop-label {
863
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
864
+ font-size: 12px;
865
+ overflow: hidden;
866
+ text-overflow: ellipsis;
867
+ white-space: nowrap;
868
+ }
869
+ .clado-pop-badge {
870
+ flex: none;
871
+ font-size: 10px;
872
+ font-weight: 600;
873
+ padding: 1px 6px;
874
+ border-radius: 999px;
875
+ background: var(--clado-ui-well);
876
+ border: 1px solid var(--clado-ui-well-border);
877
+ color: var(--clado-ui-muted);
878
+ }
879
+ .clado-pop-desc {
880
+ color: var(--clado-ui-subtle);
881
+ font-size: 11px;
882
+ max-width: 52%;
883
+ overflow: hidden;
884
+ text-overflow: ellipsis;
885
+ white-space: nowrap;
886
+ flex: none;
887
+ }
839
888
 
840
889
  /* ================= Unified 5-Tab Settings Center & Handoff Modal ================= */
841
890
  .clado-vnext-mask {
@@ -1334,3 +1383,94 @@ body.clado-dock-resizing iframe {
1334
1383
  border-color: var(--clado-ui-prism-border);
1335
1384
  color: var(--clado-ui-prism-text);
1336
1385
  }
1386
+
1387
+ /* Long-conversation history pagination banner */
1388
+ .clado-history-loader {
1389
+ align-self: center;
1390
+ appearance: none;
1391
+ border: 1px dashed var(--clado-ui-well-border);
1392
+ background: var(--clado-ui-well);
1393
+ color: var(--clado-ui-muted);
1394
+ border-radius: 999px;
1395
+ padding: 5px 12px;
1396
+ font: inherit;
1397
+ font-size: 11px;
1398
+ cursor: pointer;
1399
+ transition: all 140ms ease;
1400
+ }
1401
+ .clado-history-loader:hover:not(:disabled) {
1402
+ border-color: var(--clado-ui-prism-border);
1403
+ color: var(--clado-ui-text);
1404
+ background: var(--clado-ui-hover);
1405
+ }
1406
+ .clado-history-loader:disabled {
1407
+ opacity: 0.72;
1408
+ cursor: wait;
1409
+ }
1410
+ .clado-msg-user.is-peer {
1411
+ border-style: dashed;
1412
+ border-color: var(--clado-ui-prism-border);
1413
+ }
1414
+
1415
+ /* Automations & Event Bus Settings UI */
1416
+ .clado-auto-card {
1417
+ display: flex;
1418
+ flex-direction: column;
1419
+ gap: 8px;
1420
+ }
1421
+ .clado-auto-meta {
1422
+ display: flex;
1423
+ flex-wrap: wrap;
1424
+ align-items: center;
1425
+ gap: 6px;
1426
+ font-size: 11px;
1427
+ color: var(--clado-ui-muted);
1428
+ }
1429
+ .clado-auto-prompt {
1430
+ font-size: 11.5px;
1431
+ color: var(--clado-ui-text-soft);
1432
+ background: rgba(148, 163, 184, 0.08);
1433
+ border: 1px solid var(--clado-ui-edge);
1434
+ border-radius: 10px;
1435
+ padding: 7px 10px;
1436
+ line-height: 1.5;
1437
+ white-space: pre-wrap;
1438
+ word-break: break-word;
1439
+ }
1440
+ .clado-auto-events-grid {
1441
+ display: grid;
1442
+ grid-template-columns: repeat(auto-fill, minmax(195px, 1fr));
1443
+ gap: 6px;
1444
+ max-height: 184px;
1445
+ overflow-y: auto;
1446
+ padding: 2px;
1447
+ }
1448
+ .clado-auto-ev-group {
1449
+ border: 1px solid var(--clado-ui-edge);
1450
+ border-radius: 11px;
1451
+ padding: 7px 9px;
1452
+ background: rgba(148, 163, 184, 0.04);
1453
+ display: flex;
1454
+ flex-direction: column;
1455
+ gap: 4px;
1456
+ }
1457
+ .clado-auto-ev-title {
1458
+ font-size: 10.5px;
1459
+ font-weight: 620;
1460
+ color: var(--clado-ui-subtle);
1461
+ margin-bottom: 2px;
1462
+ }
1463
+ .clado-auto-ev-opt {
1464
+ display: flex;
1465
+ align-items: flex-start;
1466
+ gap: 6px;
1467
+ font-size: 11px;
1468
+ color: var(--clado-ui-text);
1469
+ cursor: pointer;
1470
+ line-height: 1.35;
1471
+ }
1472
+ .clado-auto-ev-opt code {
1473
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
1474
+ font-size: 10.5px;
1475
+ color: var(--clado-ui-prism-text);
1476
+ }
@@ -80,8 +80,10 @@ CLI 的 `--dry-run` 只预览安装,`--force` 仅在确认允许替换现有
80
80
  | `clado_nodes` | `read/query/create/insert/update/rename/move/delete`;定位用 `file/node`;新增用 `title/parent/content/index`;移动用 `parent/index/targetFile` |
81
81
  | `clado_links` | `list/connect/disconnect`;源 `file/node`,目标 `targetFile/targetNode`;优先用 `sourcePoint` 或行内 `position:{mode:"replace",anchor}` 从内容行连出 |
82
82
  | `clado_batch` | `operations` 中顺序执行1–100个项目操作,类型如 `document.copy/node.insert/link.connect/template.pull`;最终校验后保存 |
83
+ | `clado_sessions` | `list/read/open/send`;同源跨主会话协同,支持 `sinceMinutes` 筛选近期活跃会话、拉起角色或发送协作消息(内置 Progress Guard 防空转熔断) |
84
+ | `clado_automations` | `list/events_catalog/save/delete/pause/resume/run_now`;管理工作区周期定时唤醒(支持 `onlyIfActive` 无活跃零消耗跳过)与 6 大类系统事件订阅 |
83
85
 
84
- 节点 `node/parent/targetNode` 使用读取返回的**标题数组**,如 `["OrderService#createOrder(UUID)","检查权限(新增)"]`。不用内部ID或手拼点号路径。新增根卡片时省略 `parent`;同级节点 `index` 从 **0** 开始,省略则追加在同级末尾。
86
+ 所有写工具均支持可选 `idempotencyKey`(5 分钟防重缓存);多方并发修改同一画布的**不同卡片**时,服务端会自动执行卡片级 Rebase(返回 `rebased: true`),而并发覆写同一张卡片仍严格返回 `409`;写入同时会自动在画布上广播「外部 MCP」卡片占用态呼吸。节点 `node/parent/targetNode` 使用读取返回的**标题数组**,如 `["OrderService#createOrder(UUID)","检查权限(新增)"]`。不用内部ID或手拼点号路径。新增根卡片时省略 `parent`;同级节点 `index` 从 **0** 开始,省略则追加在同级末尾。
85
87
 
86
88
  `query` 的 `relation` 支持 `parent/children/ancestors/descendants/siblings/upstream/downstream`。可给 `depth` 控制深度、`offset/limit` 分页、`includeContent` 控制是否带正文。包含层级和调用关系分别查询。
87
89
 
@@ -0,0 +1,454 @@
1
+ /**
2
+ * Clado Unified System Event Bus & Workspace Automation / Scheduler Engine
3
+ *
4
+ * 负责统一收敛 6 大类系统事件,提供中立的平台调度原语:
5
+ * 1. 周期定时唤醒,内置 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
+ function automationsPath(stateDir) {
86
+ return join(stateDir, 'automations.json');
87
+ }
88
+
89
+ export function readAutomationsState(stateDir) {
90
+ const file = automationsPath(stateDir);
91
+ if (!existsSync(file)) return { paused: false, rules: [] };
92
+ try {
93
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
94
+ return {
95
+ paused: Boolean(raw?.paused),
96
+ rules: Array.isArray(raw?.rules) ? raw.rules : [],
97
+ };
98
+ } catch {
99
+ return { paused: false, rules: [] };
100
+ }
101
+ }
102
+
103
+ export function writeAutomationsState(stateDir, data) {
104
+ if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true });
105
+ const payload = {
106
+ paused: Boolean(data?.paused),
107
+ rules: Array.isArray(data?.rules) ? data.rules : [],
108
+ };
109
+ writeFileSync(automationsPath(stateDir), JSON.stringify(payload, null, 2) + '\n', 'utf8');
110
+ return payload;
111
+ }
112
+
113
+ export function normalizeAutomationRule(input = {}, existing = null) {
114
+ const id = String(input.id || existing?.id || ('auto_' + randomUUID().replace(/-/g, '').slice(0, 10)))
115
+ .trim()
116
+ .replace(/[^a-zA-Z0-9_-]/g, '');
117
+ if (!id) throw new Error('自动化规则 ID 不能为空。');
118
+
119
+ const name = String(input.name || existing?.name || '自定义唤醒规则').trim().slice(0, 80);
120
+ const triggerIn = input.trigger && typeof input.trigger === 'object' ? input.trigger : (existing?.trigger || {});
121
+ const type = triggerIn.type === 'event' ? 'event' : 'schedule';
122
+ const intervalMinutes = Math.max(1, Math.min(1440, Math.round(Number(triggerIn.intervalMinutes ?? 10) || 10)));
123
+ const activeWindowMinutes = Math.max(1, Math.min(1440, Math.round(Number(triggerIn.activeWindowMinutes ?? 20) || 20)));
124
+ const idleMinutes = Math.max(1, Math.min(240, Math.round(Number(triggerIn.idleMinutes ?? 15) || 15)));
125
+ const onlyIfActive = triggerIn.onlyIfActive !== false;
126
+ const eventTypes = type === 'schedule'
127
+ ? ['schedule.tick']
128
+ : [...new Set(
129
+ (Array.isArray(triggerIn.eventTypes) ? triggerIn.eventTypes : [])
130
+ .map(s => String(s || '').trim())
131
+ .filter(s => s === '*' || ALL_SYSTEM_EVENT_TYPES.has(s))
132
+ )];
133
+ if (type === 'event' && !eventTypes.length) {
134
+ throw new Error('事件订阅规则至少需要选择一个系统事件类型。');
135
+ }
136
+
137
+ const fIn = triggerIn.filter && typeof triggerIn.filter === 'object' ? triggerIn.filter : {};
138
+ const filter = {
139
+ ...(fIn.file ? { file: String(fIn.file).trim() } : {}),
140
+ ...(fIn.card ? { card: String(fIn.card).trim() } : {}),
141
+ ...(fIn.tag ? { tag: String(fIn.tag).trim() } : {}),
142
+ ...(fIn.roleId ? { roleId: String(fIn.roleId).trim() } : {}),
143
+ };
144
+
145
+ const targetIn = input.target && typeof input.target === 'object' ? input.target : (existing?.target || {});
146
+ const roleId = String(targetIn.roleId || 'archivist').trim();
147
+ const sessionId = String(targetIn.sessionId || '').trim();
148
+ const prompt = String(targetIn.prompt || '').trim();
149
+ if (!prompt) throw new Error('请填写唤醒该角色时要执行的任务指令。');
150
+
151
+ const debounceMs = Math.max(0, Math.min(120000, Math.round(Number(input.debounceMs ?? existing?.debounceMs ?? 4000) || 4000)));
152
+
153
+ return {
154
+ id,
155
+ name,
156
+ enabled: input.enabled !== undefined ? Boolean(input.enabled) : (existing ? Boolean(existing.enabled) : true),
157
+ trigger: {
158
+ type,
159
+ intervalMinutes,
160
+ onlyIfActive,
161
+ activeWindowMinutes,
162
+ idleMinutes,
163
+ eventTypes,
164
+ filter,
165
+ },
166
+ target: { roleId, sessionId, prompt },
167
+ debounceMs,
168
+ lastRunAt: existing?.lastRunAt || '',
169
+ lastCheckedAt: existing?.lastCheckedAt || '',
170
+ lastSkipReason: existing?.lastSkipReason || '',
171
+ runCount: existing?.runCount || 0,
172
+ skipCount: existing?.skipCount || 0,
173
+ createdAt: existing?.createdAt || new Date().toISOString(),
174
+ updatedAt: new Date().toISOString(),
175
+ };
176
+ }
177
+
178
+ export function saveAutomationRule(stateDir, input) {
179
+ const cur = readAutomationsState(stateDir);
180
+ const idx = input?.id ? cur.rules.findIndex(r => r.id === input.id) : -1;
181
+ const nextRule = normalizeAutomationRule(input, idx >= 0 ? cur.rules[idx] : null);
182
+ if (idx >= 0) cur.rules[idx] = nextRule;
183
+ else cur.rules.push(nextRule);
184
+ writeAutomationsState(stateDir, cur);
185
+ return { rule: nextRule, state: cur };
186
+ }
187
+
188
+ export function deleteAutomationRule(stateDir, ruleId) {
189
+ const cur = readAutomationsState(stateDir);
190
+ const before = cur.rules.length;
191
+ cur.rules = cur.rules.filter(r => r.id !== ruleId);
192
+ writeAutomationsState(stateDir, cur);
193
+ return { deleted: cur.rules.length < before, state: cur };
194
+ }
195
+
196
+ export function setAutomationsPaused(stateDir, paused) {
197
+ const cur = readAutomationsState(stateDir);
198
+ cur.paused = Boolean(paused);
199
+ writeAutomationsState(stateDir, cur);
200
+ return cur;
201
+ }
202
+
203
+ function matchesRuleFilter(rule, payload = {}) {
204
+ const f = rule.trigger?.filter || {};
205
+ if (f.file) {
206
+ const pFile = String(payload.file || '').trim();
207
+ if (!pFile || !pFile.includes(f.file)) return false;
208
+ }
209
+ if (f.card) {
210
+ const pCard = String(payload.card || '').trim();
211
+ const pCards = Array.isArray(payload.cards) ? payload.cards.map(c => String(c || '')) : [];
212
+ const hit = (pCard && pCard.includes(f.card)) || pCards.some(c => c.includes(f.card));
213
+ if (!hit) return false;
214
+ }
215
+ if (f.tag) {
216
+ const tags = [
217
+ ...(Array.isArray(payload.addedTags) ? payload.addedTags : []),
218
+ ...(Array.isArray(payload.removedTags) ? payload.removedTags : []),
219
+ ...(payload.tag ? [String(payload.tag)] : []),
220
+ ];
221
+ if (!tags.some(t => String(t).includes(f.tag))) return false;
222
+ }
223
+ if (f.roleId) {
224
+ const pRole = String(payload.originRoleId || payload.roleId || '').trim();
225
+ if (pRole !== f.roleId) return false;
226
+ }
227
+ return true;
228
+ }
229
+
230
+ function isSelfTriggered(rule, payload = {}) {
231
+ if (payload.automationRuleId && payload.automationRuleId === rule.id) return true;
232
+ if (rule.target?.sessionId && payload.originSessionId && payload.originSessionId === rule.target.sessionId) return true;
233
+ if (rule.target?.roleId && payload.originRoleId && payload.originRoleId === rule.target.roleId) return true;
234
+ return false;
235
+ }
236
+
237
+ export function createAutomationEngine({
238
+ resolveStateDir,
239
+ listSessionsForStateDir,
240
+ onTrigger,
241
+ events,
242
+ tickIntervalMs = 30000,
243
+ autoStartTimer = true,
244
+ } = {}) {
245
+ const knownWorkspaces = new Set();
246
+ const debounceBuckets = new Map(); // `${ws}::${ruleId}` -> { timer, events: [] }
247
+ const activeRuns = new Set(); // `${ws}::${ruleId}`
248
+ const lastActivityByWs = new Map(); // ws -> { ts, idleFiredForTs }
249
+
250
+ function registerWorkspace(workspace) {
251
+ if (workspace) knownWorkspaces.add(workspace);
252
+ }
253
+
254
+ function updateRuleStats(stateDir, ruleId, patch) {
255
+ const state = readAutomationsState(stateDir);
256
+ const r = state.rules.find(x => x.id === ruleId);
257
+ if (!r) return null;
258
+ Object.assign(r, patch);
259
+ writeAutomationsState(stateDir, state);
260
+ return r;
261
+ }
262
+
263
+ async function executeRule(workspace, rule, triggerMeta = {}) {
264
+ const key = `${workspace}::${rule.id}`;
265
+ if (activeRuns.has(key)) return { ok: false, skipped: true, reason: '规则正在执行中,已合并防重入。' };
266
+ const stateDir = resolveStateDir?.(workspace);
267
+ if (!stateDir) return { ok: false, skipped: true, reason: '工作区未就绪。' };
268
+
269
+ activeRuns.add(key);
270
+ const nowIso = new Date().toISOString();
271
+ try {
272
+ updateRuleStats(stateDir, rule.id, {
273
+ lastRunAt: nowIso,
274
+ lastCheckedAt: nowIso,
275
+ lastSkipReason: '',
276
+ runCount: (rule.runCount || 0) + 1,
277
+ });
278
+ events?.emit(workspace, 'automation.triggered', {
279
+ ruleId: rule.id,
280
+ ruleName: rule.name,
281
+ roleId: rule.target.roleId,
282
+ reason: triggerMeta.reason || 'event',
283
+ ts: Date.now(),
284
+ });
285
+ if (typeof onTrigger === 'function') {
286
+ await onTrigger({ workspace, stateDir, rule, triggerMeta });
287
+ }
288
+ return { ok: true, ruleId: rule.id, triggeredAt: nowIso };
289
+ } finally {
290
+ activeRuns.delete(key);
291
+ }
292
+ }
293
+
294
+ function notifyEvent(workspace, eventType, payload = {}) {
295
+ if (!workspace || !eventType) return;
296
+ registerWorkspace(workspace);
297
+ const stateDir = resolveStateDir?.(workspace);
298
+ if (!stateDir) return;
299
+
300
+ if (eventType !== 'schedule.tick' && eventType !== 'workspace.idle' && !payload.automationRuleId) {
301
+ lastActivityByWs.set(workspace, { ts: Date.now(), idleFiredForTs: 0 });
302
+ }
303
+
304
+ const state = readAutomationsState(stateDir);
305
+ if (state.paused || !state.rules.length) return;
306
+
307
+ for (const rule of state.rules) {
308
+ if (!rule.enabled || rule.trigger?.type !== 'event') continue;
309
+ const types = rule.trigger.eventTypes || [];
310
+ if (!types.includes('*') && !types.includes(eventType)) continue;
311
+ if (isSelfTriggered(rule, payload)) continue;
312
+ if (!matchesRuleFilter(rule, payload)) continue;
313
+
314
+ const bKey = `${workspace}::${rule.id}`;
315
+ let bucket = debounceBuckets.get(bKey);
316
+ if (!bucket) {
317
+ bucket = { timer: null, events: [] };
318
+ debounceBuckets.set(bKey, bucket);
319
+ }
320
+ bucket.events.push({ type: eventType, payload, ts: Date.now() });
321
+ if (bucket.events.length > 20) bucket.events.shift();
322
+
323
+ if (bucket.timer) clearTimeout(bucket.timer);
324
+ const delay = Math.max(0, Number(rule.debounceMs) || 0);
325
+ const flush = () => {
326
+ const current = debounceBuckets.get(bKey);
327
+ debounceBuckets.delete(bKey);
328
+ if (!current || !current.events.length) return;
329
+ const latestState = readAutomationsState(stateDir);
330
+ const latestRule = latestState.rules.find(r => r.id === rule.id);
331
+ if (latestState.paused || !latestRule || !latestRule.enabled) return;
332
+ executeRule(workspace, latestRule, {
333
+ reason: 'event',
334
+ events: current.events,
335
+ }).catch(() => {});
336
+ };
337
+ if (delay <= 0) flush();
338
+ else {
339
+ bucket.timer = setTimeout(flush, delay);
340
+ bucket.timer.unref?.();
341
+ }
342
+ }
343
+ }
344
+
345
+ async function evaluateSchedules(nowMs = Date.now(), targetWorkspaces = null) {
346
+ const wsList = targetWorkspaces ? [...targetWorkspaces] : [...knownWorkspaces];
347
+ const results = [];
348
+ for (const ws of wsList) {
349
+ const stateDir = resolveStateDir?.(ws);
350
+ if (!stateDir) continue;
351
+ const state = readAutomationsState(stateDir);
352
+ if (state.paused) continue;
353
+
354
+ // 1. Check workspace.idle event triggers
355
+ const act = lastActivityByWs.get(ws);
356
+ if (act && act.ts && act.idleFiredForTs !== act.ts) {
357
+ const idleRules = state.rules.filter(r => r.enabled && r.trigger?.type === 'event' && (r.trigger.eventTypes || []).includes('workspace.idle'));
358
+ for (const ir of idleRules) {
359
+ const needMs = (ir.trigger.idleMinutes || 15) * 60_000;
360
+ if (nowMs - act.ts >= needMs) {
361
+ act.idleFiredForTs = act.ts;
362
+ notifyEvent(ws, 'workspace.idle', { idleMinutes: ir.trigger.idleMinutes || 15, lastActivityAt: new Date(act.ts).toISOString() });
363
+ }
364
+ }
365
+ }
366
+
367
+ // 2. Check periodic schedule rules
368
+ for (const rule of state.rules) {
369
+ if (!rule.enabled || rule.trigger?.type !== 'schedule') continue;
370
+ const intervalMs = Math.max(1, rule.trigger.intervalMinutes || 10) * 60_000;
371
+ const lastCheckMs = rule.lastCheckedAt ? Date.parse(rule.lastCheckedAt) : (rule.createdAt ? Date.parse(rule.createdAt) : 0);
372
+ if (lastCheckMs && (nowMs - lastCheckMs) < intervalMs) continue;
373
+
374
+ const nowIso = new Date(nowMs).toISOString();
375
+ if (rule.trigger.onlyIfActive !== false) {
376
+ const winMs = Math.max(1, rule.trigger.activeWindowMinutes || 20) * 60_000;
377
+ const lastRunMs = rule.lastRunAt ? Date.parse(rule.lastRunAt) : 0;
378
+ const cutoff = Math.max(lastRunMs, nowMs - winMs);
379
+ const allSessions = typeof listSessionsForStateDir === 'function' ? (listSessionsForStateDir(stateDir) || []) : [];
380
+ const recentActive = allSessions.filter(s => {
381
+ if (!s || s.archived) return false;
382
+ if (rule.target?.sessionId && s.id === rule.target.sessionId) return false;
383
+ if (rule.target?.roleId && s.roleId === rule.target.roleId) return false;
384
+ const uMs = s.updatedAt ? Date.parse(s.updatedAt) : 0;
385
+ const hasMsgs = (s.messageCount || (Array.isArray(s.messages) ? s.messages.length : 0)) > 0;
386
+ return hasMsgs && uMs > cutoff;
387
+ });
388
+ if (!recentActive.length) {
389
+ updateRuleStats(stateDir, rule.id, {
390
+ lastCheckedAt: nowIso,
391
+ lastSkipReason: '无新增活跃会话,已零消耗跳过',
392
+ skipCount: (rule.skipCount || 0) + 1,
393
+ });
394
+ results.push({ workspace: ws, ruleId: rule.id, skipped: true, reason: 'onlyIfActive' });
395
+ continue;
396
+ }
397
+ const r = await executeRule(ws, rule, {
398
+ reason: 'schedule',
399
+ activeWindowMinutes: rule.trigger.activeWindowMinutes || 20,
400
+ activeSessions: recentActive.map(s => ({ id: s.id, title: s.title, roleId: s.roleId, updatedAt: s.updatedAt })),
401
+ });
402
+ results.push({ workspace: ws, ...r });
403
+ } else {
404
+ const r = await executeRule(ws, rule, {
405
+ reason: 'schedule',
406
+ activeWindowMinutes: rule.trigger.activeWindowMinutes || 20,
407
+ });
408
+ results.push({ workspace: ws, ...r });
409
+ }
410
+ }
411
+ }
412
+ return results;
413
+ }
414
+
415
+ async function runRuleNow(workspace, ruleId) {
416
+ registerWorkspace(workspace);
417
+ const stateDir = resolveStateDir?.(workspace);
418
+ if (!stateDir) throw new Error('工作区未就绪。');
419
+ const state = readAutomationsState(stateDir);
420
+ const rule = state.rules.find(r => r.id === ruleId);
421
+ if (!rule) throw new Error('找不到对应的自动化规则。');
422
+ return await executeRule(workspace, rule, {
423
+ reason: 'manual',
424
+ activeWindowMinutes: rule.trigger?.activeWindowMinutes || 20,
425
+ });
426
+ }
427
+
428
+ let timer = null;
429
+ if (autoStartTimer && tickIntervalMs > 0) {
430
+ timer = setInterval(() => {
431
+ evaluateSchedules().catch(() => {});
432
+ }, tickIntervalMs);
433
+ timer.unref?.();
434
+ }
435
+
436
+ function dispose() {
437
+ if (timer) {
438
+ clearInterval(timer);
439
+ timer = null;
440
+ }
441
+ for (const bucket of debounceBuckets.values()) {
442
+ if (bucket.timer) clearTimeout(bucket.timer);
443
+ }
444
+ debounceBuckets.clear();
445
+ }
446
+
447
+ return {
448
+ registerWorkspace,
449
+ notifyEvent,
450
+ evaluateSchedules,
451
+ runRuleNow,
452
+ dispose,
453
+ };
454
+ }