evolclaw 2.8.1 → 2.8.2

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,503 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { EvolAgent, validateEvolAgentConfig } from './evolagent.js';
4
+ import { logger } from '../utils/logger.js';
5
+ // ── Channel Fingerprint ────────────────────────────────────────────────────
6
+ // 为每个 channel 实例提取一个全局唯一标识,用于冲突检测和路由索引。
7
+ // 格式:{type}:{primaryKey}
8
+ const PRIMARY_KEY_MAP = {
9
+ feishu: 'appId',
10
+ aun: 'aid',
11
+ wechat: 'token',
12
+ wecom: 'botId',
13
+ dingtalk: 'clientId',
14
+ qqbot: 'appId',
15
+ };
16
+ export function extractFingerprint(channelType, instance) {
17
+ const keyField = PRIMARY_KEY_MAP[channelType];
18
+ if (!keyField)
19
+ return null;
20
+ const value = instance[keyField];
21
+ if (!value || typeof value !== 'string')
22
+ return null;
23
+ return `${channelType}:${value}`;
24
+ }
25
+ export function detectDuplicates(config) {
26
+ const seen = new Map();
27
+ const channels = config.channels || {};
28
+ for (const [type, raw] of Object.entries(channels)) {
29
+ if (type === 'defaultChannel')
30
+ continue;
31
+ const instances = Array.isArray(raw) ? raw : [raw];
32
+ for (const inst of instances) {
33
+ if (!inst || typeof inst !== 'object')
34
+ continue;
35
+ const fingerprint = extractFingerprint(type, inst);
36
+ if (!fingerprint)
37
+ continue;
38
+ const instName = inst.name ?? type;
39
+ const entry = seen.get(fingerprint);
40
+ if (entry) {
41
+ entry.instances.push(instName);
42
+ }
43
+ else {
44
+ seen.set(fingerprint, { channelType: type, instances: [instName] });
45
+ }
46
+ }
47
+ }
48
+ const duplicates = [];
49
+ for (const [fingerprint, entry] of seen) {
50
+ if (entry.instances.length > 1) {
51
+ duplicates.push({
52
+ fingerprint,
53
+ channelType: entry.channelType,
54
+ instances: entry.instances,
55
+ });
56
+ }
57
+ }
58
+ return duplicates;
59
+ }
60
+ export class EvolAgentRegistry {
61
+ agentsDir;
62
+ agents = new Map();
63
+ defaultAgent = null;
64
+ channelIndex = new Map();
65
+ globalWriter;
66
+ constructor(agentsDir, globalWriter) {
67
+ this.agentsDir = agentsDir;
68
+ this.globalWriter = globalWriter;
69
+ }
70
+ /** Late-binding setter for tests / index.ts wiring order. */
71
+ setGlobalWriter(writer) {
72
+ this.globalWriter = writer;
73
+ }
74
+ loadAll(globalConfig) {
75
+ this.agents.clear();
76
+ this.channelIndex.clear();
77
+ const files = fs.existsSync(this.agentsDir)
78
+ ? fs.readdirSync(this.agentsDir).filter(f => f.endsWith('.json'))
79
+ : [];
80
+ for (const file of files) {
81
+ const fullPath = path.join(this.agentsDir, file);
82
+ try {
83
+ const raw = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
84
+ const validation = validateEvolAgentConfig(raw);
85
+ if (!validation.valid) {
86
+ const name = raw?.name || path.basename(file, '.json');
87
+ const errorAgent = new EvolAgent(fullPath, { ...raw, name });
88
+ errorAgent.status = 'error';
89
+ errorAgent.error = validation.errors.join('; ');
90
+ this.agents.set(name, errorAgent);
91
+ logger.warn(`[EvolAgentRegistry] ${file}: ${validation.errors.join('; ')}`);
92
+ continue;
93
+ }
94
+ const agent = new EvolAgent(fullPath, raw);
95
+ this.agents.set(agent.name, agent);
96
+ }
97
+ catch (e) {
98
+ logger.warn(`[EvolAgentRegistry] Failed to load ${file}: ${e}`);
99
+ }
100
+ }
101
+ this.defaultAgent = this.buildDefaultAgent(globalConfig);
102
+ this.detectAndFlagConflicts();
103
+ this.buildChannelIndex();
104
+ }
105
+ buildDefaultAgent(globalConfig) {
106
+ const agents = globalConfig.agents || {};
107
+ const defaultName = agents.defaultAgent || 'claude';
108
+ const cfg = {
109
+ name: '[default]',
110
+ enabled: true,
111
+ agents: { [defaultName]: agents[defaultName] || {} },
112
+ channels: globalConfig.channels || {},
113
+ projects: { defaultPath: globalConfig.projects?.defaultPath || process.cwd() },
114
+ chatmode: globalConfig.chatmode,
115
+ };
116
+ return new EvolAgent(null, cfg, { isDefault: true });
117
+ }
118
+ detectAndFlagConflicts() {
119
+ const seen = new Map();
120
+ const record = (agentName, channelsBlock) => {
121
+ for (const [type, raw] of Object.entries(channelsBlock || {})) {
122
+ if (type === 'defaultChannel')
123
+ continue;
124
+ const instances = Array.isArray(raw) ? raw : [raw];
125
+ for (const inst of instances) {
126
+ if (!inst || typeof inst !== 'object')
127
+ continue;
128
+ const fp = extractFingerprint(type, inst);
129
+ if (!fp)
130
+ continue;
131
+ const instName = inst.name ?? type;
132
+ const entry = seen.get(fp) || [];
133
+ entry.push({ agent: agentName, instance: instName });
134
+ seen.set(fp, entry);
135
+ }
136
+ }
137
+ };
138
+ for (const agent of this.agents.values()) {
139
+ if (agent.status === 'error')
140
+ continue;
141
+ record(agent.name, agent.config.channels);
142
+ }
143
+ if (this.defaultAgent) {
144
+ record(this.defaultAgent.name, this.defaultAgent.config.channels);
145
+ }
146
+ for (const [_fp, occurrences] of seen) {
147
+ if (occurrences.length <= 1)
148
+ continue;
149
+ const msg = `Channel conflict: fingerprint claimed by ${occurrences.map(o => `${o.agent}(${o.instance})`).join(', ')}`;
150
+ const involvedNames = [...new Set(occurrences.map(o => o.agent))];
151
+ for (const name of involvedNames) {
152
+ if (name === '[default]')
153
+ continue;
154
+ const a = this.agents.get(name);
155
+ if (a && a.status !== 'error') {
156
+ a.status = 'error';
157
+ a.error = msg;
158
+ }
159
+ }
160
+ logger.error(`[EvolAgentRegistry] ${msg}`);
161
+ }
162
+ }
163
+ buildChannelIndex() {
164
+ for (const agent of this.agents.values()) {
165
+ if (agent.status === 'error' || agent.status === 'disabled')
166
+ continue;
167
+ for (const name of agent.channelInstanceNames()) {
168
+ this.channelIndex.set(name, agent.name);
169
+ }
170
+ }
171
+ if (this.defaultAgent) {
172
+ for (const name of this.defaultAgent.channelInstanceNames()) {
173
+ if (this.channelIndex.has(name))
174
+ continue;
175
+ this.channelIndex.set(name, '[default]');
176
+ }
177
+ }
178
+ }
179
+ resolveByChannel(channelName) {
180
+ const agentName = this.channelIndex.get(channelName);
181
+ if (!agentName)
182
+ return null;
183
+ if (agentName === '[default]')
184
+ return this.defaultAgent;
185
+ return this.agents.get(agentName) || null;
186
+ }
187
+ /**
188
+ * Check ownership of a channel via the agent that owns it.
189
+ * - For named EvolAgent: reads agent.config (memory; reflects agent.json).
190
+ * - For DefaultAgent or unknown channel: invokes `globalFallback`, which
191
+ * should consult the global config (evolclaw.json) via `config.ts:isOwner`.
192
+ */
193
+ isOwner(channelName, userId, globalFallback) {
194
+ const agent = this.resolveByChannel(channelName);
195
+ if (agent && !agent.isDefault)
196
+ return agent.isOwner(channelName, userId);
197
+ return globalFallback(channelName, userId);
198
+ }
199
+ /** Same routing logic as `isOwner`, applied to admin checks. */
200
+ isAdmin(channelName, userId, globalFallback) {
201
+ const agent = this.resolveByChannel(channelName);
202
+ if (agent && !agent.isDefault)
203
+ return agent.isAdmin(channelName, userId);
204
+ return globalFallback(channelName, userId);
205
+ }
206
+ /** Lookup current owner — agent first, then DefaultAgent (which mirrors evolclaw.json). */
207
+ getOwner(channelName) {
208
+ const agent = this.resolveByChannel(channelName);
209
+ if (!agent)
210
+ return undefined;
211
+ return agent.getOwner(channelName);
212
+ }
213
+ /**
214
+ * Persist owner. Routes to agent.json for named agents, or to evolclaw.json
215
+ * via the configured `globalWriter` for DefaultAgent. No-ops with a warning
216
+ * when the channel is unknown or no global writer is wired.
217
+ */
218
+ setChannelOwner(channelName, userId) {
219
+ const agent = this.resolveByChannel(channelName);
220
+ if (!agent) {
221
+ logger.warn(`[EvolAgentRegistry] setChannelOwner: channel "${channelName}" not found`);
222
+ return;
223
+ }
224
+ if (agent.isDefault) {
225
+ if (!this.globalWriter) {
226
+ logger.warn(`[EvolAgentRegistry] setChannelOwner: no globalWriter wired for default channel "${channelName}"`);
227
+ return;
228
+ }
229
+ this.globalWriter.setOwner(channelName, userId);
230
+ }
231
+ else {
232
+ agent.setOwner(channelName, userId);
233
+ }
234
+ }
235
+ /**
236
+ * Read showActivities mode. Falls back to `'all'` when the channel is
237
+ * unknown — matches the prior behavior of `config.ts:getChannelShowActivities`.
238
+ */
239
+ getShowActivities(channelName) {
240
+ const agent = this.resolveByChannel(channelName);
241
+ if (!agent)
242
+ return 'all';
243
+ return agent.getShowActivities(channelName);
244
+ }
245
+ /** Persist showActivities. Routes to agent.json or evolclaw.json. */
246
+ setShowActivities(channelName, mode) {
247
+ const agent = this.resolveByChannel(channelName);
248
+ if (!agent) {
249
+ logger.warn(`[EvolAgentRegistry] setShowActivities: channel "${channelName}" not found`);
250
+ return;
251
+ }
252
+ if (agent.isDefault) {
253
+ if (!this.globalWriter?.setShowActivities) {
254
+ logger.warn(`[EvolAgentRegistry] setShowActivities: no globalWriter wired for default channel "${channelName}"`);
255
+ return;
256
+ }
257
+ this.globalWriter.setShowActivities(channelName, mode);
258
+ }
259
+ else {
260
+ agent.setShowActivities(channelName, mode);
261
+ }
262
+ }
263
+ get(name) {
264
+ if (name === '[default]')
265
+ return this.defaultAgent;
266
+ return this.agents.get(name) || null;
267
+ }
268
+ list() {
269
+ const result = [];
270
+ for (const agent of this.agents.values()) {
271
+ result.push(this.toInfo(agent));
272
+ }
273
+ if (this.defaultAgent) {
274
+ result.push(this.toInfo(this.defaultAgent));
275
+ }
276
+ return result;
277
+ }
278
+ runnableAgents() {
279
+ return [...this.agents.values()].filter(a => a.status === 'stopped');
280
+ }
281
+ async reload(name, hooks) {
282
+ const oldAgent = this.agents.get(name);
283
+ if (!oldAgent)
284
+ throw new Error(`Agent "${name}" not found`);
285
+ if (!oldAgent.configPath)
286
+ throw new Error(`Cannot reload DefaultAgent`);
287
+ // 1. Re-read config from disk
288
+ const raw = JSON.parse(fs.readFileSync(oldAgent.configPath, 'utf-8'));
289
+ const validation = validateEvolAgentConfig(raw);
290
+ if (!validation.valid) {
291
+ throw new Error(`Invalid config after edit: ${validation.errors.join('; ')}`);
292
+ }
293
+ const newAgent = new EvolAgent(oldAgent.configPath, raw);
294
+ // Warn if projectPath changed — existing sessions retain old path (by design,
295
+ // to avoid breaking SDK conversation history at .claude/<encoded-path>/...)
296
+ if (oldAgent.projectPath !== newAgent.projectPath) {
297
+ logger.warn(`[EvolAgentRegistry] Agent "${name}" projectPath changed: ${oldAgent.projectPath} → ${newAgent.projectPath}. ` +
298
+ `Existing sessions retain the old path; only new sessions will use the new path. ` +
299
+ `To migrate, manually UPDATE sessions SET project_path=? WHERE id=? (warning: SDK conversation history may be lost).`);
300
+ }
301
+ // 2. Fingerprint conflict check (against all others except self)
302
+ const conflict = this.checkConflictForReload(newAgent, name);
303
+ if (conflict) {
304
+ throw new Error(`Channel conflict: ${conflict}`);
305
+ }
306
+ // 3. Compute channel diff
307
+ const oldChannels = new Set(oldAgent.channelInstanceNames());
308
+ const newChannels = new Set(newAgent.channelInstanceNames());
309
+ const toRemove = [...oldChannels].filter(c => !newChannels.has(c));
310
+ const toAdd = [...newChannels].filter(c => !oldChannels.has(c));
311
+ const kept = [...oldChannels].filter(c => newChannels.has(c));
312
+ // I6: detect kept-channel credential changes — treat as remove+add so
313
+ // the channel reconnects with new credentials (e.g. appSecret rotated).
314
+ const credentialsChanged = [];
315
+ const trulyKept = [];
316
+ for (const ch of kept) {
317
+ const oldCh = getChannelInstanceConfig(oldAgent, ch);
318
+ const newCh = getChannelInstanceConfig(newAgent, ch);
319
+ if (oldCh && newCh && channelConfigChanged(oldCh.config, newCh.config)) {
320
+ credentialsChanged.push(ch);
321
+ }
322
+ else {
323
+ trulyKept.push(ch);
324
+ }
325
+ }
326
+ toRemove.push(...credentialsChanged);
327
+ toAdd.push(...credentialsChanged);
328
+ // Track what was removed/added so we can roll back on failure
329
+ const removedSuccessfully = [];
330
+ const addedSuccessfully = [];
331
+ try {
332
+ // 4. Drain channels being removed
333
+ for (const ch of toRemove) {
334
+ await hooks.drainChannel(ch);
335
+ }
336
+ // 5. Disconnect removed channels
337
+ for (const ch of toRemove) {
338
+ await hooks.disconnectChannel(ch);
339
+ removedSuccessfully.push(ch);
340
+ }
341
+ // 6. Start new channels
342
+ for (const ch of toAdd) {
343
+ await hooks.startChannel(newAgent, ch);
344
+ addedSuccessfully.push(ch);
345
+ }
346
+ // 7. Transfer kept channel adapters from old to new (only truly unchanged ones)
347
+ for (const ch of trulyKept) {
348
+ const adapter = oldAgent.channels.get(ch);
349
+ if (adapter)
350
+ newAgent.channels.set(ch, adapter);
351
+ }
352
+ // 8. Preserve runtime state
353
+ // I5: only set 'running' when oldAgent was running; preserve error/disabled
354
+ newAgent.activeSessions = oldAgent.activeSessions;
355
+ newAgent.lastActivity = oldAgent.lastActivity;
356
+ if (oldAgent.status === 'error' || oldAgent.status === 'disabled') {
357
+ newAgent.status = oldAgent.status;
358
+ newAgent.error = oldAgent.error;
359
+ }
360
+ else {
361
+ newAgent.status = 'running';
362
+ }
363
+ // 9. Swap in registry
364
+ this.agents.set(name, newAgent);
365
+ // 10. Rebuild channel index
366
+ this.channelIndex.clear();
367
+ this.buildChannelIndex();
368
+ }
369
+ catch (err) {
370
+ // C1: Rollback — restore original channels, keep oldAgent in registry
371
+ logger.error(`[Reload] Failed: ${err}. Attempting rollback for "${name}".`);
372
+ for (const ch of addedSuccessfully) {
373
+ try {
374
+ await hooks.disconnectChannel(ch);
375
+ }
376
+ catch (_) { /* best effort */ }
377
+ }
378
+ for (const ch of removedSuccessfully) {
379
+ try {
380
+ await hooks.startChannel(oldAgent, ch);
381
+ }
382
+ catch (_) { /* best effort */ }
383
+ }
384
+ // Don't swap registry — oldAgent stays in place
385
+ oldAgent.status = 'error';
386
+ oldAgent.error = `Reload failed (rollback attempted): ${err instanceof Error ? err.message : String(err)}`;
387
+ throw err;
388
+ }
389
+ }
390
+ checkConflictForReload(newAgent, excludeName) {
391
+ const newFingerprints = new Map(); // fp → instanceName
392
+ for (const [type, raw] of Object.entries(newAgent.config.channels || {})) {
393
+ if (type === 'defaultChannel')
394
+ continue;
395
+ const instances = Array.isArray(raw) ? raw : [raw];
396
+ for (const inst of instances) {
397
+ if (!inst || typeof inst !== 'object')
398
+ continue;
399
+ const fp = extractFingerprint(type, inst);
400
+ if (!fp)
401
+ continue;
402
+ const instName = inst.name ?? type;
403
+ newFingerprints.set(fp, instName);
404
+ }
405
+ }
406
+ // Check against all other agents (excluding self)
407
+ for (const [agentName, agent] of this.agents) {
408
+ if (agentName === excludeName)
409
+ continue;
410
+ if (agent.status === 'error' || agent.status === 'disabled')
411
+ continue;
412
+ for (const [type, raw] of Object.entries(agent.config.channels || {})) {
413
+ if (type === 'defaultChannel')
414
+ continue;
415
+ const instances = Array.isArray(raw) ? raw : [raw];
416
+ for (const inst of instances) {
417
+ if (!inst || typeof inst !== 'object')
418
+ continue;
419
+ const fp = extractFingerprint(type, inst);
420
+ if (!fp)
421
+ continue;
422
+ if (newFingerprints.has(fp)) {
423
+ return `${fp} conflicts with agent "${agentName}"`;
424
+ }
425
+ }
426
+ }
427
+ }
428
+ // Check against DefaultAgent
429
+ if (this.defaultAgent) {
430
+ for (const [type, raw] of Object.entries(this.defaultAgent.config.channels || {})) {
431
+ if (type === 'defaultChannel')
432
+ continue;
433
+ const instances = Array.isArray(raw) ? raw : [raw];
434
+ for (const inst of instances) {
435
+ if (!inst || typeof inst !== 'object')
436
+ continue;
437
+ const fp = extractFingerprint(type, inst);
438
+ if (!fp)
439
+ continue;
440
+ if (newFingerprints.has(fp)) {
441
+ return `${fp} conflicts with DefaultAgent`;
442
+ }
443
+ }
444
+ }
445
+ }
446
+ return null;
447
+ }
448
+ toInfo(agent) {
449
+ let baseagent = 'claude';
450
+ let model;
451
+ let effort;
452
+ try {
453
+ baseagent = agent.baseagent;
454
+ model = agent.model;
455
+ effort = agent.effort;
456
+ }
457
+ catch { /* invalid config */ }
458
+ return {
459
+ name: agent.name,
460
+ status: agent.status,
461
+ channels: agent.channelInstanceNames(),
462
+ projectPath: agent.config.projects?.defaultPath ?? '',
463
+ baseagent,
464
+ model,
465
+ effort,
466
+ lastActivity: agent.lastActivity,
467
+ activeSessions: agent.activeSessions,
468
+ error: agent.error,
469
+ isDefault: agent.isDefault,
470
+ };
471
+ }
472
+ }
473
+ /**
474
+ * Locate the raw config of a channel instance by name within an agent config.
475
+ * Returns `{ type, config }` or null if not found.
476
+ *
477
+ * Matches against the effective channel name (with agent prefix for EvolAgents),
478
+ * mirroring `EvolAgent.findChannelInstance`. Only used by `reload()` to detect
479
+ * kept-channel credential changes.
480
+ */
481
+ function getChannelInstanceConfig(agent, channelName) {
482
+ for (const [type, raw] of Object.entries(agent.config?.channels || {})) {
483
+ if (type === 'defaultChannel')
484
+ continue;
485
+ const instances = Array.isArray(raw) ? raw : [raw];
486
+ for (const inst of instances) {
487
+ if (!inst || typeof inst !== 'object')
488
+ continue;
489
+ const effName = agent.effectiveChannelName(type, inst.name);
490
+ if (effName === channelName)
491
+ return { type, config: inst };
492
+ }
493
+ }
494
+ return null;
495
+ }
496
+ /**
497
+ * Compare two channel-instance configs by serialized JSON. Channel configs
498
+ * are plain JSON-shaped objects (no functions/Buffers), so this is a sound
499
+ * structural compare for "did anything in this channel block change".
500
+ */
501
+ function channelConfigChanged(oldConfig, newConfig) {
502
+ return JSON.stringify(oldConfig) !== JSON.stringify(newConfig);
503
+ }