evolclaw 2.8.1 → 2.8.3

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,514 @@
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
+ // Include ALL declared baseagents (not just defaultName) so that
109
+ // AgentLoader creates runners for each, enabling /agent switching.
110
+ const baseagentBlock = {};
111
+ const KNOWN_BASEAGENTS = ['claude', 'codex', 'gemini', 'hermes'];
112
+ for (const ba of KNOWN_BASEAGENTS) {
113
+ if (agents[ba] !== undefined)
114
+ baseagentBlock[ba] = agents[ba];
115
+ }
116
+ if (Object.keys(baseagentBlock).length === 0) {
117
+ baseagentBlock[defaultName] = agents[defaultName] || {};
118
+ }
119
+ const cfg = {
120
+ name: '[default]',
121
+ enabled: true,
122
+ agents: baseagentBlock,
123
+ channels: globalConfig.channels || {},
124
+ projects: { defaultPath: globalConfig.projects?.defaultPath || process.cwd() },
125
+ chatmode: globalConfig.chatmode,
126
+ };
127
+ return new EvolAgent(null, cfg, { isDefault: true });
128
+ }
129
+ detectAndFlagConflicts() {
130
+ const seen = new Map();
131
+ const record = (agentName, channelsBlock) => {
132
+ for (const [type, raw] of Object.entries(channelsBlock || {})) {
133
+ if (type === 'defaultChannel')
134
+ continue;
135
+ const instances = Array.isArray(raw) ? raw : [raw];
136
+ for (const inst of instances) {
137
+ if (!inst || typeof inst !== 'object')
138
+ continue;
139
+ const fp = extractFingerprint(type, inst);
140
+ if (!fp)
141
+ continue;
142
+ const instName = inst.name ?? type;
143
+ const entry = seen.get(fp) || [];
144
+ entry.push({ agent: agentName, instance: instName });
145
+ seen.set(fp, entry);
146
+ }
147
+ }
148
+ };
149
+ for (const agent of this.agents.values()) {
150
+ if (agent.status === 'error')
151
+ continue;
152
+ record(agent.name, agent.config.channels);
153
+ }
154
+ if (this.defaultAgent) {
155
+ record(this.defaultAgent.name, this.defaultAgent.config.channels);
156
+ }
157
+ for (const [_fp, occurrences] of seen) {
158
+ if (occurrences.length <= 1)
159
+ continue;
160
+ const msg = `Channel conflict: fingerprint claimed by ${occurrences.map(o => `${o.agent}(${o.instance})`).join(', ')}`;
161
+ const involvedNames = [...new Set(occurrences.map(o => o.agent))];
162
+ for (const name of involvedNames) {
163
+ if (name === '[default]')
164
+ continue;
165
+ const a = this.agents.get(name);
166
+ if (a && a.status !== 'error') {
167
+ a.status = 'error';
168
+ a.error = msg;
169
+ }
170
+ }
171
+ logger.error(`[EvolAgentRegistry] ${msg}`);
172
+ }
173
+ }
174
+ buildChannelIndex() {
175
+ for (const agent of this.agents.values()) {
176
+ if (agent.status === 'error' || agent.status === 'disabled')
177
+ continue;
178
+ for (const name of agent.channelInstanceNames()) {
179
+ this.channelIndex.set(name, agent.name);
180
+ }
181
+ }
182
+ if (this.defaultAgent) {
183
+ for (const name of this.defaultAgent.channelInstanceNames()) {
184
+ if (this.channelIndex.has(name))
185
+ continue;
186
+ this.channelIndex.set(name, '[default]');
187
+ }
188
+ }
189
+ }
190
+ resolveByChannel(channelName) {
191
+ const agentName = this.channelIndex.get(channelName);
192
+ if (!agentName)
193
+ return null;
194
+ if (agentName === '[default]')
195
+ return this.defaultAgent;
196
+ return this.agents.get(agentName) || null;
197
+ }
198
+ /**
199
+ * Check ownership of a channel via the agent that owns it.
200
+ * - For named EvolAgent: reads agent.config (memory; reflects agent.json).
201
+ * - For DefaultAgent or unknown channel: invokes `globalFallback`, which
202
+ * should consult the global config (evolclaw.json) via `config.ts:isOwner`.
203
+ */
204
+ isOwner(channelName, userId, globalFallback) {
205
+ const agent = this.resolveByChannel(channelName);
206
+ if (agent && !agent.isDefault)
207
+ return agent.isOwner(channelName, userId);
208
+ return globalFallback(channelName, userId);
209
+ }
210
+ /** Same routing logic as `isOwner`, applied to admin checks. */
211
+ isAdmin(channelName, userId, globalFallback) {
212
+ const agent = this.resolveByChannel(channelName);
213
+ if (agent && !agent.isDefault)
214
+ return agent.isAdmin(channelName, userId);
215
+ return globalFallback(channelName, userId);
216
+ }
217
+ /** Lookup current owner — agent first, then DefaultAgent (which mirrors evolclaw.json). */
218
+ getOwner(channelName) {
219
+ const agent = this.resolveByChannel(channelName);
220
+ if (!agent)
221
+ return undefined;
222
+ return agent.getOwner(channelName);
223
+ }
224
+ /**
225
+ * Persist owner. Routes to agent.json for named agents, or to evolclaw.json
226
+ * via the configured `globalWriter` for DefaultAgent. No-ops with a warning
227
+ * when the channel is unknown or no global writer is wired.
228
+ */
229
+ setChannelOwner(channelName, userId) {
230
+ const agent = this.resolveByChannel(channelName);
231
+ if (!agent) {
232
+ logger.warn(`[EvolAgentRegistry] setChannelOwner: channel "${channelName}" not found`);
233
+ return;
234
+ }
235
+ if (agent.isDefault) {
236
+ if (!this.globalWriter) {
237
+ logger.warn(`[EvolAgentRegistry] setChannelOwner: no globalWriter wired for default channel "${channelName}"`);
238
+ return;
239
+ }
240
+ this.globalWriter.setOwner(channelName, userId);
241
+ }
242
+ else {
243
+ agent.setOwner(channelName, userId);
244
+ }
245
+ }
246
+ /**
247
+ * Read showActivities mode. Falls back to `'all'` when the channel is
248
+ * unknown — matches the prior behavior of `config.ts:getChannelShowActivities`.
249
+ */
250
+ getShowActivities(channelName) {
251
+ const agent = this.resolveByChannel(channelName);
252
+ if (!agent)
253
+ return 'all';
254
+ return agent.getShowActivities(channelName);
255
+ }
256
+ /** Persist showActivities. Routes to agent.json or evolclaw.json. */
257
+ setShowActivities(channelName, mode) {
258
+ const agent = this.resolveByChannel(channelName);
259
+ if (!agent) {
260
+ logger.warn(`[EvolAgentRegistry] setShowActivities: channel "${channelName}" not found`);
261
+ return;
262
+ }
263
+ if (agent.isDefault) {
264
+ if (!this.globalWriter?.setShowActivities) {
265
+ logger.warn(`[EvolAgentRegistry] setShowActivities: no globalWriter wired for default channel "${channelName}"`);
266
+ return;
267
+ }
268
+ this.globalWriter.setShowActivities(channelName, mode);
269
+ }
270
+ else {
271
+ agent.setShowActivities(channelName, mode);
272
+ }
273
+ }
274
+ get(name) {
275
+ if (name === '[default]')
276
+ return this.defaultAgent;
277
+ return this.agents.get(name) || null;
278
+ }
279
+ list() {
280
+ const result = [];
281
+ for (const agent of this.agents.values()) {
282
+ result.push(this.toInfo(agent));
283
+ }
284
+ if (this.defaultAgent) {
285
+ result.push(this.toInfo(this.defaultAgent));
286
+ }
287
+ return result;
288
+ }
289
+ runnableAgents() {
290
+ return [...this.agents.values()].filter(a => a.status === 'stopped');
291
+ }
292
+ async reload(name, hooks) {
293
+ const oldAgent = this.agents.get(name);
294
+ if (!oldAgent)
295
+ throw new Error(`Agent "${name}" not found`);
296
+ if (!oldAgent.configPath)
297
+ throw new Error(`Cannot reload DefaultAgent`);
298
+ // 1. Re-read config from disk
299
+ const raw = JSON.parse(fs.readFileSync(oldAgent.configPath, 'utf-8'));
300
+ const validation = validateEvolAgentConfig(raw);
301
+ if (!validation.valid) {
302
+ throw new Error(`Invalid config after edit: ${validation.errors.join('; ')}`);
303
+ }
304
+ const newAgent = new EvolAgent(oldAgent.configPath, raw);
305
+ // Warn if projectPath changed — existing sessions retain old path (by design,
306
+ // to avoid breaking SDK conversation history at .claude/<encoded-path>/...)
307
+ if (oldAgent.projectPath !== newAgent.projectPath) {
308
+ logger.warn(`[EvolAgentRegistry] Agent "${name}" projectPath changed: ${oldAgent.projectPath} → ${newAgent.projectPath}. ` +
309
+ `Existing sessions retain the old path; only new sessions will use the new path. ` +
310
+ `To migrate, manually UPDATE sessions SET project_path=? WHERE id=? (warning: SDK conversation history may be lost).`);
311
+ }
312
+ // 2. Fingerprint conflict check (against all others except self)
313
+ const conflict = this.checkConflictForReload(newAgent, name);
314
+ if (conflict) {
315
+ throw new Error(`Channel conflict: ${conflict}`);
316
+ }
317
+ // 3. Compute channel diff
318
+ const oldChannels = new Set(oldAgent.channelInstanceNames());
319
+ const newChannels = new Set(newAgent.channelInstanceNames());
320
+ const toRemove = [...oldChannels].filter(c => !newChannels.has(c));
321
+ const toAdd = [...newChannels].filter(c => !oldChannels.has(c));
322
+ const kept = [...oldChannels].filter(c => newChannels.has(c));
323
+ // I6: detect kept-channel credential changes — treat as remove+add so
324
+ // the channel reconnects with new credentials (e.g. appSecret rotated).
325
+ const credentialsChanged = [];
326
+ const trulyKept = [];
327
+ for (const ch of kept) {
328
+ const oldCh = getChannelInstanceConfig(oldAgent, ch);
329
+ const newCh = getChannelInstanceConfig(newAgent, ch);
330
+ if (oldCh && newCh && channelConfigChanged(oldCh.config, newCh.config)) {
331
+ credentialsChanged.push(ch);
332
+ }
333
+ else {
334
+ trulyKept.push(ch);
335
+ }
336
+ }
337
+ toRemove.push(...credentialsChanged);
338
+ toAdd.push(...credentialsChanged);
339
+ // Track what was removed/added so we can roll back on failure
340
+ const removedSuccessfully = [];
341
+ const addedSuccessfully = [];
342
+ try {
343
+ // 4. Drain channels being removed
344
+ for (const ch of toRemove) {
345
+ await hooks.drainChannel(ch);
346
+ }
347
+ // 5. Disconnect removed channels
348
+ for (const ch of toRemove) {
349
+ await hooks.disconnectChannel(ch);
350
+ removedSuccessfully.push(ch);
351
+ }
352
+ // 6. Start new channels
353
+ for (const ch of toAdd) {
354
+ await hooks.startChannel(newAgent, ch);
355
+ addedSuccessfully.push(ch);
356
+ }
357
+ // 7. Transfer kept channel adapters from old to new (only truly unchanged ones)
358
+ for (const ch of trulyKept) {
359
+ const adapter = oldAgent.channels.get(ch);
360
+ if (adapter)
361
+ newAgent.channels.set(ch, adapter);
362
+ }
363
+ // 8. Preserve runtime state
364
+ // I5: only set 'running' when oldAgent was running; preserve error/disabled
365
+ newAgent.activeSessions = oldAgent.activeSessions;
366
+ newAgent.lastActivity = oldAgent.lastActivity;
367
+ if (oldAgent.status === 'error' || oldAgent.status === 'disabled') {
368
+ newAgent.status = oldAgent.status;
369
+ newAgent.error = oldAgent.error;
370
+ }
371
+ else {
372
+ newAgent.status = 'running';
373
+ }
374
+ // 9. Swap in registry
375
+ this.agents.set(name, newAgent);
376
+ // 10. Rebuild channel index
377
+ this.channelIndex.clear();
378
+ this.buildChannelIndex();
379
+ }
380
+ catch (err) {
381
+ // C1: Rollback — restore original channels, keep oldAgent in registry
382
+ logger.error(`[Reload] Failed: ${err}. Attempting rollback for "${name}".`);
383
+ for (const ch of addedSuccessfully) {
384
+ try {
385
+ await hooks.disconnectChannel(ch);
386
+ }
387
+ catch (_) { /* best effort */ }
388
+ }
389
+ for (const ch of removedSuccessfully) {
390
+ try {
391
+ await hooks.startChannel(oldAgent, ch);
392
+ }
393
+ catch (_) { /* best effort */ }
394
+ }
395
+ // Don't swap registry — oldAgent stays in place
396
+ oldAgent.status = 'error';
397
+ oldAgent.error = `Reload failed (rollback attempted): ${err instanceof Error ? err.message : String(err)}`;
398
+ throw err;
399
+ }
400
+ }
401
+ checkConflictForReload(newAgent, excludeName) {
402
+ const newFingerprints = new Map(); // fp → instanceName
403
+ for (const [type, raw] of Object.entries(newAgent.config.channels || {})) {
404
+ if (type === 'defaultChannel')
405
+ continue;
406
+ const instances = Array.isArray(raw) ? raw : [raw];
407
+ for (const inst of instances) {
408
+ if (!inst || typeof inst !== 'object')
409
+ continue;
410
+ const fp = extractFingerprint(type, inst);
411
+ if (!fp)
412
+ continue;
413
+ const instName = inst.name ?? type;
414
+ newFingerprints.set(fp, instName);
415
+ }
416
+ }
417
+ // Check against all other agents (excluding self)
418
+ for (const [agentName, agent] of this.agents) {
419
+ if (agentName === excludeName)
420
+ continue;
421
+ if (agent.status === 'error' || agent.status === 'disabled')
422
+ continue;
423
+ for (const [type, raw] of Object.entries(agent.config.channels || {})) {
424
+ if (type === 'defaultChannel')
425
+ continue;
426
+ const instances = Array.isArray(raw) ? raw : [raw];
427
+ for (const inst of instances) {
428
+ if (!inst || typeof inst !== 'object')
429
+ continue;
430
+ const fp = extractFingerprint(type, inst);
431
+ if (!fp)
432
+ continue;
433
+ if (newFingerprints.has(fp)) {
434
+ return `${fp} conflicts with agent "${agentName}"`;
435
+ }
436
+ }
437
+ }
438
+ }
439
+ // Check against DefaultAgent
440
+ if (this.defaultAgent) {
441
+ for (const [type, raw] of Object.entries(this.defaultAgent.config.channels || {})) {
442
+ if (type === 'defaultChannel')
443
+ continue;
444
+ const instances = Array.isArray(raw) ? raw : [raw];
445
+ for (const inst of instances) {
446
+ if (!inst || typeof inst !== 'object')
447
+ continue;
448
+ const fp = extractFingerprint(type, inst);
449
+ if (!fp)
450
+ continue;
451
+ if (newFingerprints.has(fp)) {
452
+ return `${fp} conflicts with DefaultAgent`;
453
+ }
454
+ }
455
+ }
456
+ }
457
+ return null;
458
+ }
459
+ toInfo(agent) {
460
+ let baseagent = 'claude';
461
+ let model;
462
+ let effort;
463
+ try {
464
+ baseagent = agent.baseagent;
465
+ model = agent.model;
466
+ effort = agent.effort;
467
+ }
468
+ catch { /* invalid config */ }
469
+ return {
470
+ name: agent.name,
471
+ status: agent.status,
472
+ channels: agent.channelInstanceNames(),
473
+ projectPath: agent.config.projects?.defaultPath ?? '',
474
+ baseagent,
475
+ model,
476
+ effort,
477
+ lastActivity: agent.lastActivity,
478
+ activeSessions: agent.activeSessions,
479
+ error: agent.error,
480
+ isDefault: agent.isDefault,
481
+ };
482
+ }
483
+ }
484
+ /**
485
+ * Locate the raw config of a channel instance by name within an agent config.
486
+ * Returns `{ type, config }` or null if not found.
487
+ *
488
+ * Matches against the effective channel name (with agent prefix for EvolAgents),
489
+ * mirroring `EvolAgent.findChannelInstance`. Only used by `reload()` to detect
490
+ * kept-channel credential changes.
491
+ */
492
+ function getChannelInstanceConfig(agent, channelName) {
493
+ for (const [type, raw] of Object.entries(agent.config?.channels || {})) {
494
+ if (type === 'defaultChannel')
495
+ continue;
496
+ const instances = Array.isArray(raw) ? raw : [raw];
497
+ for (const inst of instances) {
498
+ if (!inst || typeof inst !== 'object')
499
+ continue;
500
+ const effName = agent.effectiveChannelName(type, inst.name);
501
+ if (effName === channelName)
502
+ return { type, config: inst };
503
+ }
504
+ }
505
+ return null;
506
+ }
507
+ /**
508
+ * Compare two channel-instance configs by serialized JSON. Channel configs
509
+ * are plain JSON-shaped objects (no functions/Buffers), so this is a sound
510
+ * structural compare for "did anything in this channel block change".
511
+ */
512
+ function channelConfigChanged(oldConfig, newConfig) {
513
+ return JSON.stringify(oldConfig) !== JSON.stringify(newConfig);
514
+ }