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