evolclaw 3.1.2 → 3.1.4

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +2 -6
  3. package/assets/.env.template +4 -0
  4. package/assets/config.json.template +6 -0
  5. package/assets/wechat-group-qr.jpeg +0 -0
  6. package/dist/agents/claude-runner.js +1 -1
  7. package/dist/agents/codex-runner.js +75 -19
  8. package/dist/agents/gemini-runner.js +0 -2
  9. package/dist/agents/kit-renderer.js +85 -22
  10. package/dist/aun/aid/agentmd.js +67 -74
  11. package/dist/aun/aid/client.js +22 -7
  12. package/dist/aun/aid/identity.js +314 -28
  13. package/dist/aun/aid/index.js +2 -2
  14. package/dist/aun/rpc/connection.js +8 -10
  15. package/dist/channels/aun.js +53 -41
  16. package/dist/cli/agent.js +28 -28
  17. package/dist/cli/bench.js +8 -14
  18. package/dist/cli/help.js +23 -0
  19. package/dist/cli/index.js +398 -73
  20. package/dist/cli/init-channel.js +2 -3
  21. package/dist/cli/init.js +13 -6
  22. package/dist/cli/link-rules.js +2 -1
  23. package/dist/cli/net-check.js +10 -11
  24. package/dist/core/command-handler.js +621 -541
  25. package/dist/core/evolagent.js +31 -0
  26. package/dist/core/message/im-renderer.js +10 -0
  27. package/dist/core/message/message-bridge.js +123 -24
  28. package/dist/core/message/message-processor.js +61 -31
  29. package/dist/core/relation/peer-identity.js +64 -21
  30. package/dist/core/session/session-manager.js +191 -44
  31. package/dist/core/trigger/manager.js +37 -0
  32. package/dist/index.js +4 -1
  33. package/dist/paths.js +87 -16
  34. package/dist/utils/npm-ops.js +18 -11
  35. package/kits/eck_manifest.json +9 -9
  36. package/kits/rules/02-navigation.md +1 -0
  37. package/kits/rules/05-venue.md +2 -2
  38. package/kits/rules/06-channel.md +2 -18
  39. package/kits/templates/system-fragments/baseagent.md +8 -2
  40. package/kits/templates/system-fragments/channel.md +20 -8
  41. package/kits/templates/system-fragments/identity.md +5 -6
  42. package/kits/templates/system-fragments/relation.md +10 -5
  43. package/kits/templates/system-fragments/session.md +20 -0
  44. package/kits/templates/system-fragments/venue.md +5 -3
  45. package/package.json +4 -2
  46. package/dist/net-check.js +0 -640
  47. package/dist/watch-msg.js +0 -544
  48. package/kits/templates/system-fragments/runtime.md +0 -19
@@ -1,5 +1,7 @@
1
1
  import { DEFAULT_PERMISSION_MODE } from '../types.js';
2
2
  import { hasModelSwitcher, hasPermissionController } from '../agents/claude-runner.js';
3
+ import { getCodexEfforts } from '../agents/codex-runner.js';
4
+ import { resolveAnthropicConfig, resolveOpenaiConfig } from '../agents/resolve.js';
3
5
  import { renderCommandCardAsText } from './interaction-router.js';
4
6
  import { buildEnvelope, sendInteractionPayload } from './message/message-processor.js';
5
7
  import { resolvePaths, getPackageRoot } from '../paths.js';
@@ -11,22 +13,48 @@ import os from 'os';
11
13
  import { parseTriggerSet, parseTriggerUpdate } from './trigger/parser.js';
12
14
  import { calcNextFireAt } from './trigger/scheduler.js';
13
15
  import { checkLatestVersion, getLocalVersion, isLinkedInstall, compareVersions } from '../utils/npm-ops.js';
14
- const allEfforts = ['low', 'medium', 'high', 'max'];
15
- const nonMaxEfforts = allEfforts.filter(e => e !== 'max');
16
+ const allEfforts = ['low', 'medium', 'high', 'xhigh', 'max'];
17
+ const nonMaxEfforts = allEfforts.filter(e => e !== 'max' && e !== 'xhigh');
16
18
  function getAvailableEfforts(agent, model) {
17
19
  if (agent.name === 'claude') {
18
- if (model.includes('opus'))
19
- return allEfforts;
20
- return nonMaxEfforts;
20
+ return allEfforts;
21
21
  }
22
22
  if (agent.name === 'codex') {
23
- return nonMaxEfforts;
23
+ return getCodexEfforts(model);
24
24
  }
25
25
  return [];
26
26
  }
27
27
  function formatModelUsage(_agent, _model) {
28
28
  return '用法: /model <模型>';
29
29
  }
30
+ function getModelListSource(owning, agent) {
31
+ const codexConfig = owning?.config?.baseagents?.codex;
32
+ const claudeConfig = owning?.config?.baseagents?.claude;
33
+ if (agent.name === 'codex') {
34
+ let resolved = {};
35
+ try {
36
+ resolved = resolveOpenaiConfig({ agents: { codex: codexConfig } }, codexConfig);
37
+ }
38
+ catch { }
39
+ return {
40
+ apiBaseUrl: resolved.baseUrl,
41
+ apiKey: resolved.apiKey,
42
+ fallbackModels: agent.listModels?.() || [],
43
+ owner: 'openai',
44
+ };
45
+ }
46
+ let resolved = {};
47
+ try {
48
+ resolved = resolveAnthropicConfig({ agents: { claude: claudeConfig } }, claudeConfig);
49
+ }
50
+ catch { }
51
+ return {
52
+ apiBaseUrl: resolved.baseUrl,
53
+ apiKey: resolved.apiKey,
54
+ fallbackModels: ['claude-opus-4-7', 'claude-opus-4-6', 'claude-sonnet-4-6'],
55
+ owner: 'anthropic',
56
+ };
57
+ }
30
58
  /**
31
59
  * 写入用户级 ~/.claude/settings.json(与 Claude CLI 行为一致)
32
60
  */
@@ -100,16 +128,16 @@ function formatIdleTime(ms) {
100
128
  return '刚刚';
101
129
  }
102
130
  // 支持的命令列表
103
- const commands = ['/new', '/pwd', '/plist', '/project', '/bind', '/help', '/evolhelp', '/status', '/restart', '/model', '/setmodel', '/effort', '/agent', '/slist', '/session', '/rename', '/stop', '/clear', '/compact', '/repair', '/safe', '/fork', '/del', '/perm', '/file', '/check', '/rewind', '/activity', '/chatmode', '/dispatch', '/ask', '/resume', '/aid', '/rpc', '/storage', '/trigger', '/upgrade'];
131
+ const commands = ['/new', '/pwd', '/help', '/evolhelp', '/status', '/restart', '/model', '/setmodel', '/effort', '/baseagent', '/slist', '/session', '/rename', '/stop', '/clear', '/compact', '/repair', '/safe', '/fork', '/del', '/perm', '/file', '/check', '/rewind', '/activity', '/chatmode', '/dispatch', '/ask', '/resume', '/aid', '/rpc', '/storage', '/agent', '/trigger', '/upgrade'];
104
132
  // 命令别名映射
105
133
  const aliases = {
106
- '/p': '/project',
107
134
  '/s': '/session',
108
135
  '/name': '/rename',
109
- '/rw': '/rewind'
136
+ '/rw': '/rewind',
137
+ '/base': '/baseagent',
110
138
  };
111
139
  // 命令快速路径前缀(所有命令都不进入消息队列)
112
- const quickCommandPrefixes = ['/new', '/pwd', '/plist', '/project', '/bind', '/help', '/evolhelp', '/status', '/restart', '/model', '/setmodel', '/effort', '/agent', '/slist', '/session', '/rename', '/repair', '/fork', '/stop', '/clear', '/compact', '/safe', '/del', '/perm', '/file', '/check', '/p ', '/s ', '/name', '/rewind', '/rw', '/rw ', '/activity', '/chatmode', '/dispatch', '/ask', '/resume', '/aid', '/rpc', '/storage', '/trigger', '/upgrade'];
140
+ const quickCommandPrefixes = ['/new', '/pwd', '/help', '/evolhelp', '/status', '/restart', '/model', '/setmodel', '/effort', '/baseagent', '/slist', '/session', '/rename', '/repair', '/fork', '/stop', '/clear', '/compact', '/safe', '/del', '/perm', '/file', '/check', '/s ', '/name', '/rewind', '/rw', '/rw ', '/activity', '/chatmode', '/dispatch', '/ask', '/resume', '/base ', '/aid', '/rpc', '/storage', '/agent', '/trigger', '/upgrade'];
113
141
  export class CommandHandler {
114
142
  sessionManager;
115
143
  messageCache;
@@ -382,8 +410,9 @@ export class CommandHandler {
382
410
  return { session };
383
411
  }
384
412
  const ct = chatType === 'group' ? 'group' : chatType === 'private' ? 'private' : undefined;
413
+ const channelType = this.resolveChannelType(channel);
385
414
  const session = await this.sessionManager.getActiveSession(channel, channelId)
386
- ?? await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel), undefined, undefined, undefined, undefined, ct);
415
+ ?? await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel), undefined, undefined, undefined, undefined, ct, undefined, undefined, channelType);
387
416
  // 如果 session 已存在但 chatType 跟传入的不一致,更新
388
417
  if (ct && session.chatType !== ct) {
389
418
  await this.sessionManager.updateSession(session.id, { chatType: ct });
@@ -465,16 +494,6 @@ export class CommandHandler {
465
494
  }
466
495
  ];
467
496
  }
468
- if (isAdmin) {
469
- items.push({
470
- group: '项目管理',
471
- commands: [
472
- { cmd: '/pwd', label: '显示当前项目路径', desc: '查看当前会话绑定的项目目录' },
473
- { cmd: '/p', label: '列出或切换项目', desc: '切换到其他已配置的项目', next: { type: 'select', dynamic: true } },
474
- ...(isOwner ? [{ cmd: '/bind', label: '绑定新项目目录', desc: '将当前会话绑定到指定项目路径', next: { type: 'text' } }] : []),
475
- ]
476
- });
477
- }
478
497
  items.push({
479
498
  group: '会话管理',
480
499
  commands: [
@@ -493,7 +512,7 @@ export class CommandHandler {
493
512
  items.push({
494
513
  group: 'Agent 与模型',
495
514
  commands: [
496
- { cmd: '/agent', label: '切换 Agent 后端', desc: '切换当前会话使用的 AI 后端', next: { type: 'select', dynamic: true } },
515
+ { cmd: '/baseagent', label: '切换 Agent 后端', desc: '切换当前会话使用的 AI 后端', next: { type: 'select', dynamic: true } },
497
516
  { cmd: '/model', label: '切换模型', desc: '切换当前 Agent 使用的模型版本', next: { type: 'select', dynamic: true } },
498
517
  { cmd: '/effort', label: '切换推理强度', desc: '调整模型推理深度,影响响应速度与质量', next: { type: 'select', items: [
499
518
  { value: 'low', label: 'Low' },
@@ -542,7 +561,7 @@ export class CommandHandler {
542
561
  { value: 'none', label: '不显示', desc: '关闭所有中间输出' },
543
562
  ] } },
544
563
  ...(isAdmin ? [
545
- { cmd: '/restart', label: '重启/重连', desc: '重启服务或重连指定渠道', next: { type: 'select', dynamic: true } },
564
+ { cmd: '/restart', label: '重启服务', desc: '重启整个 EvolClaw 服务进程' },
546
565
  ] : []),
547
566
  ...(isOwner ? [
548
567
  { cmd: '/file', label: '发送项目内文件', desc: '将项目目录内的文件发送给用户' },
@@ -570,22 +589,32 @@ export class CommandHandler {
570
589
  /** 动态子菜单:根据 cmd 路径返回选项列表(供 menu.query + cmd 使用) */
571
590
  async getSubMenuItems(cmd, channel, channelId, userId) {
572
591
  const session = await this.sessionManager.getActiveSession(channel, channelId);
573
- if (cmd === '/s' || cmd === '/del') {
592
+ if (cmd === '/s' || cmd === '/session' || cmd === '/del') {
574
593
  const sessions = await this.sessionManager.listSessions(channel, channelId);
575
594
  const active = cmd === '/del' ? await this.sessionManager.getActiveSession(channel, channelId) : null;
595
+ const currentSession = session;
576
596
  const items = sessions
577
597
  .filter(s => !active || s.id !== active.id)
578
598
  .map(s => {
579
- const shortId = s.agentSessionId ? s.agentSessionId.substring(0, 8) : '';
580
- const time = s.updatedAt ? formatIdleTime(Date.now() - s.updatedAt) : '';
581
- const parts = [shortId, time].filter(Boolean).join(' · ');
582
- return {
599
+ const item = {
583
600
  value: s.name || s.id.slice(0, 8),
584
601
  label: s.name || s.id.slice(0, 8),
585
- desc: parts || undefined,
602
+ selected: currentSession ? s.id === currentSession.id : false,
586
603
  };
604
+ if (s.agentSessionId) {
605
+ item.agentSessionId = s.agentSessionId;
606
+ const fileInfo = this.sessionManager.getSessionFileInfo(s.projectPath, s.agentSessionId, s.agentId);
607
+ if (fileInfo.turns)
608
+ item.turns = fileInfo.turns;
609
+ const firstMsg = this.sessionManager.readSessionFirstMessage(s.projectPath, s.agentSessionId, s.agentId);
610
+ if (firstMsg)
611
+ item.preview = firstMsg.length > 80 ? firstMsg.slice(0, 80) + '…' : firstMsg;
612
+ }
613
+ if (s.updatedAt)
614
+ item.lastActive = s.updatedAt;
615
+ return item;
587
616
  });
588
- if (cmd === '/s') {
617
+ if (cmd === '/s' || cmd === '/session') {
589
618
  items.push({ value: 'cli', label: '查看 CLI 会话', desc: '列出未导入的 CLI 本地会话' });
590
619
  }
591
620
  return items;
@@ -594,107 +623,474 @@ export class CommandHandler {
594
623
  // Use agent-scoped project list: agent-owned channels see their agent.json's
595
624
  // projects.list; default channel sees agent config's projects.list
596
625
  const list = this.getEffectiveProjects(channel);
597
- return Object.entries(list).map(([name, path]) => ({ value: name, label: name, desc: path }));
626
+ const currentPath = session?.projectPath;
627
+ return Object.entries(list).map(([name, p]) => ({ value: name, label: name, desc: p, selected: currentPath === p }));
598
628
  }
599
- if (cmd === '/agent') {
600
- return this.getAvailableBaseagents(channel).map(name => ({ value: name, label: name }));
629
+ if (cmd === '/baseagent') {
630
+ const currentAgent = session?.agentId;
631
+ return this.getAvailableBaseagents(channel).map(name => ({ value: name, label: name, selected: name === currentAgent }));
601
632
  }
602
633
  if (cmd === '/model') {
603
634
  const agent = this.getAgent(channel, session?.agentId);
604
635
  if (hasModelSwitcher(agent) && agent.listModels) {
605
636
  const models = await agent.listModels() ?? [];
637
+ const currentModel = agent.getModel();
606
638
  if (models.length > 0)
607
- return models.map((m) => ({ value: m, label: m }));
639
+ return models.map((m) => ({ value: m, label: m, selected: m === currentModel }));
608
640
  }
609
641
  return null;
610
642
  }
611
- if (cmd === '/restart') {
612
- const isOwner = userId ? this.sessionManager.resolveIdentity(channel, userId).role === 'owner' : false;
613
- // 列出所有 channel type
614
- const visibleTypes = new Set();
615
- for (const [name] of this.adapters) {
616
- const t = this.channelTypeMap.get(name);
617
- if (t)
618
- visibleTypes.add(t);
643
+ // if (cmd === '/restart') {
644
+ // const isOwner = userId ? this.sessionManager.resolveIdentity(channel, userId).role === 'owner' : false;
645
+ // // 列出所有 channel type
646
+ // const visibleTypes = new Set<string>();
647
+ // for (const [name] of this.adapters) {
648
+ // const t = this.channelTypeMap.get(name);
649
+ // if (t) visibleTypes.add(t);
650
+ // }
651
+ // const channels = [...visibleTypes].map(type => ({ value: type, label: type, desc: '重连此类型所有渠道实例' }));
652
+ // if (isOwner) channels.unshift({ value: '', label: '重启服务', desc: '重启整个 EvolClaw 服务进程' });
653
+ // return channels;
654
+ // }
655
+ if (cmd === '/activity') {
656
+ const currentMode = this.agentRegistry?.getShowActivities?.(channel) ?? 'all';
657
+ return [
658
+ { value: 'all', label: '全部显示', selected: currentMode === 'all' },
659
+ { value: 'dm', label: '仅私聊显示', selected: currentMode === 'dm-only' },
660
+ { value: 'owner', label: '仅 owner 私聊显示', selected: currentMode === 'owner-dm-only' },
661
+ { value: 'none', label: '全部静默', selected: currentMode === 'none' },
662
+ ];
663
+ }
664
+ if (cmd === '/effort') {
665
+ const agent = this.getAgent(channel, session?.agentId);
666
+ const currentModel = hasModelSwitcher(agent) ? agent.getModel() : agent.name;
667
+ const efforts = getAvailableEfforts(agent, currentModel);
668
+ const currentEffort = agent.getEffort?.() || 'auto';
669
+ const allItems = [...efforts, 'auto'];
670
+ return allItems.map(e => ({ value: e, label: e === 'auto' ? 'auto (SDK默认)' : e, selected: e === currentEffort }));
671
+ }
672
+ if (cmd === '/chatmode') {
673
+ // 无活跃会话时,selected 跟随 evolagent.config.chatmode.private 默认值
674
+ let currentMode;
675
+ if (session?.sessionMode) {
676
+ currentMode = session.sessionMode;
619
677
  }
620
- const channels = [...visibleTypes].map(type => ({ value: type, label: type, desc: '重连此类型所有渠道实例' }));
621
- if (isOwner)
622
- channels.unshift({ value: '', label: '重启服务', desc: '重启整个 EvolClaw 服务进程' });
623
- return channels;
678
+ else {
679
+ const evolagent = this.agentRegistry?.resolveByChannel(channel);
680
+ currentMode = evolagent?.config?.chatmode?.private || 'interactive';
681
+ }
682
+ return [
683
+ { value: 'interactive', label: '交互模式', selected: currentMode === 'interactive' },
684
+ { value: 'proactive', label: '主动模式', selected: currentMode === 'proactive' },
685
+ ];
686
+ }
687
+ if (cmd === '/dispatch') {
688
+ const currentMode = session?.metadata?.dispatchMode ?? null;
689
+ return [
690
+ { value: 'mention', label: '@提及时响应', selected: currentMode === 'mention' },
691
+ { value: 'broadcast', label: '所有消息响应', selected: currentMode === 'broadcast' },
692
+ ];
693
+ }
694
+ if (cmd === '/perm') {
695
+ const currentMode = session?.metadata?.permissionMode ?? DEFAULT_PERMISSION_MODE;
696
+ const permAgent = this.getAgent(channel, session?.agentId);
697
+ const validModes = hasPermissionController(permAgent)
698
+ ? permAgent.listModes().filter(m => m.available).map(m => m.key)
699
+ : ['auto', 'bypass', 'plan', 'edit', 'request', 'noask'];
700
+ return validModes.map(m => ({ value: m, label: m, selected: m === currentMode }));
624
701
  }
625
702
  return null;
626
703
  }
627
- /** 菜单 exec 模式:查询状态或执行命令,返回结构化数据 */
628
- async execMenu(cmd, mode, channel, channelId, userId) {
704
+ // ── Menu Protocol exec ────────────────────────────────────────────────
705
+ //
706
+ // 三个入口对应 menu.query / menu.update / menu.action:
707
+ // execMenuQuery — 查询某项当前值(无会话时多数 fallback 到 evolagent config)
708
+ // execMenuUpdate — 写入新值(持久化到 session 或 evolagent config)
709
+ // execMenuAction — 触发动词(stop/restart/new/delete/compact/fork/switch/check/upgrade)
710
+ //
711
+ // 所有方法返回 { data } 或 { error, code? }。code 是结构化错误码(NO_ACTIVE_SESSION 等),
712
+ // 客户端可据此决定降级策略。message-bridge 把 code 透传到 menu.response。
713
+ async loadMenuContext(channel, channelId) {
629
714
  const session = await this.sessionManager.getActiveSession(channel, channelId);
630
- if (!session)
631
- return { error: '当前无活跃会话' };
632
- const trimmed = cmd.trim();
633
- const cmdBase = trimmed.split(' ')[0];
715
+ const evolagent = this.agentRegistry?.resolveByChannel(channel) ?? null;
716
+ return { session, evolagent };
717
+ }
718
+ requireSession(s) {
719
+ return s ? null : { error: '当前无活跃会话', code: 'NO_ACTIVE_SESSION' };
720
+ }
721
+ /** menu.query — 查询当前值。 */
722
+ async execMenuQuery(cmd, channel, channelId, userId) {
723
+ void userId;
724
+ const cmdBase = cmd.trim().split(' ')[0];
634
725
  if (!cmdBase)
635
- return { error: '缺少命令' };
636
- const arg = trimmed.slice(cmdBase.length).trim();
726
+ return { error: '缺少命令', code: 'MISSING_CMD' };
727
+ const { session, evolagent } = await this.loadMenuContext(channel, channelId);
728
+ if (cmdBase === '/pwd') {
729
+ const sessPath = session?.projectPath;
730
+ const fallbackPath = evolagent?.config?.projects?.defaultPath;
731
+ const path = sessPath ?? fallbackPath ?? null;
732
+ const name = path ? this.getProjectName(path) : null;
733
+ return { data: { name, path } };
734
+ }
735
+ if (cmdBase === '/session' || cmdBase === '/s') {
736
+ if (!session) {
737
+ return { data: { status: 'no-session' } };
738
+ }
739
+ const sessionKey = this.getQueueKey(session, channel, channelId);
740
+ const sessionAgent = this.getAgent(channel, session.agentId);
741
+ const isProcessing = this.messageQueue.isProcessing(sessionKey) || sessionAgent.hasActiveStream(sessionKey);
742
+ const queueLength = this.messageQueue.getQueueLength(sessionKey);
743
+ const health = await this.sessionManager.getHealthStatus(session.id);
744
+ let processingDuration;
745
+ if (isProcessing && session.processingState) {
746
+ const elapsed = Date.now() - parseInt(session.processingState, 10);
747
+ if (!isNaN(elapsed) && elapsed > 0)
748
+ processingDuration = Math.floor(elapsed / 1000);
749
+ }
750
+ let turns = 0;
751
+ if (session.agentSessionId) {
752
+ const fileInfo = this.sessionManager.getSessionFileInfo(session.projectPath, session.agentSessionId, session.agentId);
753
+ turns = fileInfo.turns;
754
+ }
755
+ const data = {
756
+ name: session.name || null,
757
+ agentSessionId: session.agentSessionId || null,
758
+ status: isProcessing ? 'processing' : 'idle',
759
+ createdAt: session.createdAt,
760
+ updatedAt: session.updatedAt,
761
+ };
762
+ if (processingDuration !== undefined)
763
+ data.processingDuration = processingDuration;
764
+ if (queueLength > 0)
765
+ data.queueLength = queueLength;
766
+ if (turns > 0)
767
+ data.turns = turns;
768
+ if (health.lastSuccessTime)
769
+ data.lastSuccess = health.lastSuccessTime;
770
+ if (health.consecutiveErrors)
771
+ data.consecutiveErrors = health.consecutiveErrors;
772
+ if (health.lastError)
773
+ data.lastError = { type: health.lastErrorType || 'unknown', message: health.lastError.substring(0, 100) };
774
+ return { data };
775
+ }
776
+ if (cmdBase === '/baseagent') {
777
+ const value = session?.agentId ?? evolagent?.config?.active_baseagent ?? null;
778
+ return { data: { baseagent: value } };
779
+ }
780
+ if (cmdBase === '/model') {
781
+ if (session) {
782
+ const agent = this.getAgent(channel, session.agentId);
783
+ if (hasModelSwitcher(agent))
784
+ return { data: { model: agent.getModel() ?? null } };
785
+ }
786
+ const ba = evolagent?.config?.active_baseagent;
787
+ const block = ba && evolagent ? evolagent.config.baseagents?.[ba] : undefined;
788
+ return { data: { model: block?.model ?? null } };
789
+ }
790
+ if (cmdBase === '/effort') {
791
+ if (session) {
792
+ const agent = this.getAgent(channel, session.agentId);
793
+ const e = agent.getEffort?.();
794
+ if (e !== undefined)
795
+ return { data: { effort: e } };
796
+ }
797
+ const ba = evolagent?.config?.active_baseagent;
798
+ const block = ba && evolagent ? evolagent.config.baseagents?.[ba] : undefined;
799
+ const fallbackField = ba === 'codex' ? (block?.effort ?? block?.reasoning) : block?.effort;
800
+ return { data: { effort: fallbackField ?? null } };
801
+ }
802
+ if (cmdBase === '/chatmode') {
803
+ const sessionMode = session?.sessionMode;
804
+ const fallback = evolagent?.config?.chatmode?.private;
805
+ return { data: { mode: sessionMode || fallback || 'interactive' } };
806
+ }
807
+ if (cmdBase === '/dispatch') {
808
+ const chatType = session?.chatType || 'private';
809
+ if (chatType !== 'group') {
810
+ return { error: 'dispatch 仅在群聊会话中有效', code: 'NOT_APPLICABLE' };
811
+ }
812
+ const sessionMode = session?.metadata?.dispatchMode;
813
+ const fallback = evolagent?.config?.dispatch;
814
+ return { data: { mode: sessionMode ?? fallback ?? null } };
815
+ }
637
816
  if (cmdBase === '/perm') {
817
+ const need = this.requireSession(session);
818
+ if (need)
819
+ return need;
638
820
  const currentMode = session.metadata?.permissionMode ?? DEFAULT_PERMISSION_MODE;
639
- if (mode === 'query') {
640
- return { data: { mode: currentMode } };
821
+ return { data: { mode: currentMode } };
822
+ }
823
+ if (cmdBase === '/activity') {
824
+ const currentMode = this.agentRegistry?.getShowActivities?.(channel) ?? 'all';
825
+ return { data: { mode: currentMode } };
826
+ }
827
+ if (cmdBase === '/system') {
828
+ const owningAgent = this.getOwningAgent(channel);
829
+ const data = {
830
+ agent: owningAgent?.name ?? 'DefaultAgent',
831
+ channel: this.resolveChannelType(channel),
832
+ pid: process.pid,
833
+ node: process.version,
834
+ uptime: Math.floor(process.uptime()),
835
+ };
836
+ try {
837
+ const pkgPath = path.join(getPackageRoot(), 'package.json');
838
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
839
+ if (pkg?.version)
840
+ data.version = pkg.version;
841
+ }
842
+ catch { }
843
+ const channels = owningAgent?.channelInstanceNames?.() ?? [];
844
+ if (channels.length)
845
+ data.channels = channels;
846
+ return { data };
847
+ }
848
+ return { error: `不支持 query: ${cmdBase}`, code: 'NOT_SUPPORTED' };
849
+ }
850
+ /** menu.update — 写入新值。 */
851
+ async execMenuUpdate(cmd, value, channel, channelId, userId) {
852
+ const cmdBase = cmd.trim().split(' ')[0];
853
+ if (!cmdBase)
854
+ return { error: '缺少命令', code: 'MISSING_CMD' };
855
+ const arg = value.trim();
856
+ if (!arg)
857
+ return { error: '缺少 value 参数', code: 'MISSING_VALUE' };
858
+ const { session, evolagent } = await this.loadMenuContext(channel, channelId);
859
+ const identity = this.sessionManager.resolveIdentity(channel, userId);
860
+ if (cmdBase === '/baseagent') {
861
+ const valid = this.getAvailableBaseagents(channel);
862
+ if (valid.length && !valid.includes(arg)) {
863
+ return { error: `无效 baseagent: ${arg},可选: ${valid.join(' / ')}`, code: 'INVALID_VALUE' };
864
+ }
865
+ // 当前会话切换走 slash 命令的完整逻辑(涉及 runner 状态、session.agentId 重新挂载等)
866
+ // 仅在 slash 命令成功后才持久化到 evolagent config,避免失败时配置已落盘
867
+ if (session && session.agentId !== arg) {
868
+ const result = await this._handleInternal(`/baseagent ${arg}`, channel, channelId, undefined, userId);
869
+ const payload = result;
870
+ if (payload?.kind === 'command.error') {
871
+ return { error: payload.text || '切换失败', code: 'EXEC_FAILED' };
872
+ }
873
+ }
874
+ // 持久化到 evolagent config(影响后续新会话)
875
+ if (evolagent)
876
+ evolagent.setActiveBaseagent(arg);
877
+ return { data: { baseagent: arg } };
878
+ }
879
+ if (cmdBase === '/model') {
880
+ const agent = this.getAgent(channel, session?.agentId);
881
+ if (hasModelSwitcher(agent)) {
882
+ const models = (await agent.listModels?.()) ?? [];
883
+ if (models.length && !models.includes(arg)) {
884
+ return { error: `无效模型: ${arg}`, code: 'INVALID_VALUE' };
885
+ }
886
+ agent.setModel(arg);
887
+ }
888
+ if (evolagent)
889
+ evolagent.setBaseagentModel(arg);
890
+ return { data: { model: arg } };
891
+ }
892
+ if (cmdBase === '/effort') {
893
+ const agent = this.getAgent(channel, session?.agentId);
894
+ const currentModel = hasModelSwitcher(agent) ? agent.getModel() : agent.name;
895
+ const validEfforts = getAvailableEfforts(agent, currentModel);
896
+ const allValid = [...validEfforts, 'auto'];
897
+ if (!allValid.includes(arg)) {
898
+ return { error: `无效推理强度: ${arg},可选: ${allValid.join(' / ')}`, code: 'INVALID_VALUE' };
899
+ }
900
+ if (typeof agent.setEffort === 'function') {
901
+ agent.setEffort(arg === 'auto' ? undefined : arg);
902
+ }
903
+ if (evolagent)
904
+ evolagent.setBaseagentEffort(arg === 'auto' ? undefined : arg);
905
+ return { data: { effort: arg } };
906
+ }
907
+ if (cmdBase === '/chatmode') {
908
+ if (arg !== 'interactive' && arg !== 'proactive') {
909
+ return { error: `无效模式: ${arg}`, code: 'INVALID_VALUE' };
910
+ }
911
+ if (session) {
912
+ const chatType = session.chatType || 'private';
913
+ if (chatType === 'group' && identity.role !== 'owner' && identity.role !== 'admin') {
914
+ return { error: '无权限:群聊中仅管理员可切换', code: 'NO_PERMISSION' };
915
+ }
916
+ await this.sessionManager.updateSession(session.id, { sessionMode: arg });
917
+ this.eventBus.publish({ type: 'session:chat-mode-changed', sessionId: session.id, mode: arg, timestamp: Date.now() });
641
918
  }
642
- // update
643
- if (!arg)
644
- return { error: '缺少目标模式' };
645
- const identity = this.sessionManager.resolveIdentity(channel, userId);
919
+ else {
920
+ if (evolagent)
921
+ evolagent.setChatmodePrivate(arg);
922
+ }
923
+ return { data: { mode: arg } };
924
+ }
925
+ if (cmdBase === '/dispatch') {
926
+ if (arg !== 'mention' && arg !== 'broadcast') {
927
+ return { error: `无效模式: ${arg}`, code: 'INVALID_VALUE' };
928
+ }
929
+ const chatType = session?.chatType;
930
+ if (!session || chatType !== 'group') {
931
+ return { error: 'dispatch 仅在群聊会话中有效', code: 'NOT_APPLICABLE' };
932
+ }
933
+ if (identity.role !== 'owner' && identity.role !== 'admin') {
934
+ return { error: '无权限:群聊中仅管理员可切换', code: 'NO_PERMISSION' };
935
+ }
936
+ const metadata = { ...(session.metadata || {}), dispatchMode: arg };
937
+ await this.sessionManager.updateSession(session.id, { metadata });
938
+ this.eventBus.publish({ type: 'session:dispatch-mode-changed', sessionId: session.id, mode: arg, timestamp: Date.now() });
939
+ return { data: { mode: arg } };
940
+ }
941
+ if (cmdBase === '/perm') {
942
+ const need = this.requireSession(session);
943
+ if (need)
944
+ return need;
646
945
  if (identity.role !== 'owner')
647
- return { error: '无权限' };
946
+ return { error: '无权限', code: 'NO_PERMISSION' };
648
947
  const permAgent = this.getAgent(channel, session.agentId);
649
948
  const validModes = hasPermissionController(permAgent)
650
949
  ? permAgent.listModes().filter(m => m.available).map(m => m.key)
651
950
  : ['auto', 'bypass', 'plan', 'edit', 'request', 'noask'];
652
951
  if (!validModes.includes(arg))
653
- return { error: `无效模式: ${arg}` };
952
+ return { error: `无效模式: ${arg}`, code: 'INVALID_VALUE' };
654
953
  const metadata = { ...(session.metadata || {}), permissionMode: arg };
655
954
  await this.sessionManager.updateSession(session.id, { metadata });
656
955
  return { data: { mode: arg } };
657
956
  }
658
- if (cmdBase === '/chatmode') {
659
- const currentMode = session.sessionMode || 'interactive';
660
- if (mode === 'query') {
661
- return { data: { mode: currentMode } };
662
- }
663
- // update
664
- if (!arg)
665
- return { error: '缺少目标模式' };
666
- if (arg !== 'interactive' && arg !== 'proactive')
667
- return { error: `无效模式: ${arg}` };
668
- const identity = this.sessionManager.resolveIdentity(channel, userId);
669
- const chatType = session.chatType || 'private';
670
- if (chatType === 'group' && identity.role !== 'owner' && identity.role !== 'admin') {
671
- return { error: '无权限:群聊中仅管理员可切换' };
672
- }
673
- await this.sessionManager.updateSession(session.id, { sessionMode: arg });
674
- this.eventBus.publish({ type: 'session:chat-mode-changed', sessionId: session.id, mode: arg, timestamp: Date.now() });
675
- return { data: { mode: arg } };
957
+ if (cmdBase === '/activity') {
958
+ const modeMap = { all: 'all', dm: 'dm-only', owner: 'owner-dm-only', none: 'none' };
959
+ const newMode = modeMap[arg];
960
+ if (!newMode)
961
+ return { error: `无效模式: ${arg},可选: all / dm / owner / none`, code: 'INVALID_VALUE' };
962
+ if (identity.role !== 'owner')
963
+ return { error: '中间输出模式切换仅限 owner', code: 'NO_PERMISSION' };
964
+ if (!this.agentRegistry?.setShowActivities)
965
+ return { error: '找不到通道所属 agent,无法持久化', code: 'EXEC_FAILED' };
966
+ this.agentRegistry.setShowActivities(channel, newMode);
967
+ return { data: { mode: newMode } };
676
968
  }
677
- if (cmdBase === '/dispatch') {
678
- const currentMode = session.metadata?.dispatchMode;
679
- if (mode === 'query') {
680
- return { data: { mode: currentMode ?? null } };
681
- }
682
- // update
683
- if (!arg)
684
- return { error: '缺少目标模式' };
685
- if (arg !== 'mention' && arg !== 'broadcast')
686
- return { error: `无效模式: ${arg}` };
687
- const identity = this.sessionManager.resolveIdentity(channel, userId);
688
- const chatType = session.chatType || 'private';
689
- if (chatType === 'group' && identity.role !== 'owner' && identity.role !== 'admin') {
690
- return { error: '无权限:群聊中仅管理员可切换' };
969
+ return { error: `不支持 update: ${cmdBase}`, code: 'NOT_SUPPORTED' };
970
+ }
971
+ /** menu.action 触发动词。 */
972
+ async execMenuAction(cmd, action, args, channel, channelId, userId) {
973
+ const cmdBase = cmd.trim().split(' ')[0];
974
+ if (!cmdBase)
975
+ return { error: '缺少命令', code: 'MISSING_CMD' };
976
+ if (!action)
977
+ return { error: '缺少 action', code: 'MISSING_VALUE' };
978
+ const { session } = await this.loadMenuContext(channel, channelId);
979
+ const identity = this.sessionManager.resolveIdentity(channel, userId);
980
+ // ── /session 系列 ──
981
+ if (cmdBase === '/session' || cmdBase === '/s') {
982
+ if (action === 'stop') {
983
+ if (!session)
984
+ return { error: '当前无活跃会话', code: 'NO_ACTIVE_SESSION' };
985
+ const sessionKey = this.getQueueKey(session, channel, channelId);
986
+ const sessionAgent = this.getAgent(channel, session.agentId);
987
+ const hasActive = sessionAgent.hasActiveStream(sessionKey);
988
+ const queueLength = this.messageQueue.getQueueLength(sessionKey);
989
+ if (queueLength === 0 && !hasActive) {
990
+ return { error: '当前没有正在处理的任务', code: 'NO_ACTIVE_TASK' };
991
+ }
992
+ await sessionAgent.interrupt(sessionKey);
993
+ this.eventBus.publish({
994
+ type: 'task:interrupted',
995
+ sessionId: sessionKey,
996
+ reason: 'stop',
997
+ agentName: this.agentRegistry?.resolveByChannel(channel)?.name ?? '<unknown>',
998
+ });
999
+ this.sessionManager.clearProcessing(sessionKey);
1000
+ return { data: { action: 'stop', success: true } };
1001
+ }
1002
+ if (action === 'new') {
1003
+ const name = (args?.name ?? '').toString().trim();
1004
+ return await this.delegateAsAction(action, name ? `/new ${name}` : '/new', channel, channelId, userId, { enrichSession: true });
1005
+ }
1006
+ if (action === 'delete') {
1007
+ const target = (args?.target ?? '').toString().trim();
1008
+ if (!target)
1009
+ return { error: '缺少 args.target', code: 'MISSING_VALUE' };
1010
+ return await this.delegateAsAction(action, `/del ${target}`, channel, channelId, userId);
1011
+ }
1012
+ if (action === 'switch') {
1013
+ const target = (args?.target ?? '').toString().trim();
1014
+ if (!target)
1015
+ return { error: '缺少 args.target', code: 'MISSING_VALUE' };
1016
+ return await this.delegateAsAction(action, `/s ${target}`, channel, channelId, userId, { enrichSession: true });
1017
+ }
1018
+ if (action === 'compact') {
1019
+ const need = this.requireSession(session);
1020
+ if (need)
1021
+ return need;
1022
+ return await this.delegateAsAction(action, '/compact', channel, channelId, userId);
1023
+ }
1024
+ if (action === 'fork') {
1025
+ const need = this.requireSession(session);
1026
+ if (need)
1027
+ return need;
1028
+ const name = (args?.name ?? '').toString().trim();
1029
+ return await this.delegateAsAction(action, name ? `/fork ${name}` : '/fork', channel, channelId, userId, { enrichSession: true });
1030
+ }
1031
+ return { error: `不支持的 session action: ${action}`, code: 'NOT_SUPPORTED' };
1032
+ }
1033
+ // ── /system 系列 ──
1034
+ if (cmdBase === '/system') {
1035
+ if (action === 'restart') {
1036
+ if (identity.role !== 'owner')
1037
+ return { error: '无权限:服务重启仅限 owner 使用', code: 'NO_PERMISSION' };
1038
+ const restartInfo = { channel, channelId, timestamp: Date.now() };
1039
+ fs.writeFileSync(path.join(resolvePaths().dataDir, 'restart-pending.json'), JSON.stringify(restartInfo));
1040
+ const { spawn } = await import('child_process');
1041
+ spawn('node', [path.join(getPackageRoot(), 'dist', 'cli', 'index.js'), 'restart-monitor'], {
1042
+ detached: true,
1043
+ stdio: 'ignore',
1044
+ env: { ...process.env, EVOLCLAW_HOME: resolvePaths().root }
1045
+ }).unref();
1046
+ this.eventBus.publish({ type: 'system:restart', channel, channelId });
1047
+ setTimeout(() => { process.kill(process.pid, 'SIGTERM'); }, 500);
1048
+ return { data: { action: 'restart', success: true } };
691
1049
  }
692
- const metadata = { ...(session.metadata || {}), dispatchMode: arg };
693
- await this.sessionManager.updateSession(session.id, { metadata });
694
- this.eventBus.publish({ type: 'session:dispatch-mode-changed', sessionId: session.id, mode: arg, timestamp: Date.now() });
695
- return { data: { mode: arg } };
1050
+ if (action === 'check') {
1051
+ return await this.delegateAsAction(action, '/check', channel, channelId, userId);
1052
+ }
1053
+ if (action === 'upgrade') {
1054
+ if (identity.role !== 'owner')
1055
+ return { error: '无权限:升级仅限 owner 使用', code: 'NO_PERMISSION' };
1056
+ return await this.delegateAsAction(action, '/upgrade', channel, channelId, userId);
1057
+ }
1058
+ return { error: `不支持的 system action: ${action}`, code: 'NOT_SUPPORTED' };
1059
+ }
1060
+ return { error: `不支持 action: ${cmdBase}`, code: 'NOT_SUPPORTED' };
1061
+ }
1062
+ /** 把 menu.action 委派给已有 slash 命令处理逻辑,把 OutboundPayload 包成结构化结果。 */
1063
+ async delegateAsAction(action, slashCmd, channel, channelId, userId, opts = {}) {
1064
+ try {
1065
+ const result = await this._handleInternal(slashCmd, channel, channelId, undefined, userId);
1066
+ if (result == null) {
1067
+ // null / undefined: 命令未识别或前置守卫拦截(如 idle 检查),视为失败
1068
+ return { error: '命令未执行(可能被前置守卫拦截)', code: 'EXEC_FAILED' };
1069
+ }
1070
+ if (typeof result !== 'object' || !('kind' in result)) {
1071
+ return { data: { action, success: true } };
1072
+ }
1073
+ const payload = result;
1074
+ if (payload.kind === 'command.error') {
1075
+ return { error: payload.text || '执行失败', code: 'EXEC_FAILED' };
1076
+ }
1077
+ const data = { action, success: true };
1078
+ if (payload.text)
1079
+ data.message = payload.text;
1080
+ // 对于切换/创建类动作,附加切换后的活跃 session 信息便于客户端继续操作
1081
+ if (opts.enrichSession) {
1082
+ const newSession = await this.sessionManager.getActiveSession(channel, channelId);
1083
+ if (newSession) {
1084
+ data.session = { id: newSession.id, name: newSession.name || null };
1085
+ if (newSession.agentSessionId)
1086
+ data.session.agentSessionId = newSession.agentSessionId;
1087
+ }
1088
+ }
1089
+ return { data };
1090
+ }
1091
+ catch (e) {
1092
+ return { error: e?.message || String(e), code: 'INTERNAL' };
696
1093
  }
697
- return { error: `不支持 exec 模式: ${cmdBase}` };
698
1094
  }
699
1095
  isCommand(content) {
700
1096
  return content === '/p' || content === '/s' || quickCommandPrefixes.some(cmd => content.startsWith(cmd));
@@ -731,26 +1127,13 @@ export class CommandHandler {
731
1127
  logger.info(`[CommandHandler] handle: channel=${channel} channelId=${channelId} cmd="${normalizedContent.split(' ')[0]}" user=${userId ?? 'n/a'} role=${identity?.role ?? 'n/a'}`);
732
1128
  // 话题内禁用部分命令
733
1129
  if (threadId) {
734
- const threadBlocked = ['/new', '/slist', '/plist', '/bind', '/s', '/session', '/project', '/p', '/fork', '/del', '/agent'];
1130
+ const threadBlocked = ['/new', '/slist', '/s', '/session', '/fork', '/del', '/baseagent'];
735
1131
  const isBlocked = threadBlocked.some(c => normalizedContent === c || normalizedContent.startsWith(c + ' '));
736
1132
  if (isBlocked) {
737
1133
  return { kind: 'command.error', text: '⚠️ 话题中不支持此命令' };
738
1134
  }
739
1135
  }
740
1136
  // Agent-owned 通道:禁止项目切换和 agent 切换
741
- const owningAgent = this.getOwningAgent(channel);
742
- if (owningAgent) {
743
- const isProjectCmd = normalizedContent === '/project' || normalizedContent.startsWith('/project ') ||
744
- normalizedContent === '/bind' || normalizedContent.startsWith('/bind ') ||
745
- normalizedContent === '/plist' ||
746
- normalizedContent === '/p' || normalizedContent.startsWith('/p ');
747
- if (isProjectCmd) {
748
- return { kind: 'command.error', text: `❌ 当前通道由 agent [${owningAgent.name}] 管理,项目已锁定为 ${owningAgent.projectPath}` };
749
- }
750
- if (normalizedContent.startsWith('/agent ')) {
751
- return { kind: 'command.error', text: `❌ 当前通道由 agent [${owningAgent.name}] 管理,baseagent 已锁定为 ${owningAgent.baseagent}` };
752
- }
753
- }
754
1137
  // 权限检查:区分用户级命令和管理级命令
755
1138
  const isOwner = identity.role === 'owner';
756
1139
  const isAdmin = identity.role === 'owner' || identity.role === 'admin';
@@ -759,7 +1142,7 @@ export class CommandHandler {
759
1142
  // guest 在群聊和私聊中均可访问的只读命令:纯查询形态(带参写操作由各 handler 内部守卫拦截)
760
1143
  const guestGroupCommands = [
761
1144
  '/status', '/help', '/evolhelp', '/check', '/chatmode', '/dispatch',
762
- '/model', '/setmodel', '/effort', '/agent', '/perm', '/activity', '/safe', '/stop',
1145
+ '/model', '/setmodel', '/effort', '/baseagent', '/perm', '/activity', '/safe', '/stop',
763
1146
  '/resume', '/trigger',
764
1147
  ];
765
1148
  const userCommands = activeChatType === 'group' && !isAdmin
@@ -779,12 +1162,12 @@ export class CommandHandler {
779
1162
  // 空闲检查:某些命令需要等待当前会话空闲
780
1163
  // 原则:仅对"写/破坏性"形态拦截,纯读/用法提示的无参形态始终放行
781
1164
  // - 始终需要 idle(无参即写):/new /clear /compact /repair /fork
782
- // - 仅带参时需要 idle(无参是列表/用法):/session /bind /project /agent /rewind
1165
+ // - 仅带参时需要 idle(无参是列表/用法):/session /baseagent /rewind
783
1166
  // - /chatmode:在 handler 内部自行做写操作的 idle 检查
784
1167
  // - /dispatch:在 handler 内部自行做写操作的 idle 检查
785
1168
  // - /safe:已禁用 no-op,不再要求 idle
786
1169
  const idleAlways = ['/new', '/clear', '/compact', '/repair', '/fork'];
787
- const idleWhenArg = ['/session', '/bind', '/project', '/agent', '/rewind'];
1170
+ const idleWhenArg = ['/session', '/baseagent', '/rewind'];
788
1171
  const needsIdle = idleAlways.some(cmd => normalizedContent === cmd || normalizedContent.startsWith(cmd + ' ')) ||
789
1172
  idleWhenArg.some(cmd => normalizedContent.startsWith(cmd + ' '));
790
1173
  if (needsIdle) {
@@ -856,10 +1239,8 @@ export class CommandHandler {
856
1239
  const lines = [
857
1240
  '可用命令:',
858
1241
  '',
859
- '📁 项目管理:',
1242
+ '📁 项目:',
860
1243
  ' /pwd - 显示当前项目路径',
861
- ' /p [name|path] - 列出或切换项目',
862
- ...(isOwner ? [' /bind <path> - 绑定新项目目录'] : []),
863
1244
  '',
864
1245
  '🔄 会话管理:',
865
1246
  ' /new [名称] - 创建新会话(清空历史请用此命令,可选命名)',
@@ -871,7 +1252,7 @@ export class CommandHandler {
871
1252
  ' /compact - 压缩会话上下文(减少 token 用量)',
872
1253
  '',
873
1254
  '🤖 Agent 与模型:',
874
- ' /agent [name] - 查看或切换 Agent 后端',
1255
+ ' /baseagent [name] - 查看或切换 Agent 后端(别名: /base)',
875
1256
  ' /model [model] - 查看或切换模型',
876
1257
  ' /effort [level] - 查看或切换推理强度',
877
1258
  '',
@@ -890,7 +1271,7 @@ export class CommandHandler {
890
1271
  ' /stop - 中断当前任务',
891
1272
  ' /check - 检查渠道状态',
892
1273
  ...(isAdmin ? [
893
- ' /restart <type> - 重连该类型所有渠道实例(服务级,admin+)',
1274
+ ' /restart - 重启服务(owner only)',
894
1275
  ] : []),
895
1276
  ...(isOwner ? [
896
1277
  ' /restart - 重启服务',
@@ -899,8 +1280,6 @@ export class CommandHandler {
899
1280
  '',
900
1281
  '🧰 工具:',
901
1282
  ' /file [channel] <path> - 发送项目内文件',
902
- ' /aid [list|show|new|delete|lookup|agentmd] - AID 身份管理',
903
- ' /storage [upload|download|ls|rm|quota] <aid> - 文件存储',
904
1283
  ] : []),
905
1284
  '',
906
1285
  '❓ 帮助:',
@@ -911,12 +1290,8 @@ export class CommandHandler {
911
1290
  // /evolhelp 命令:返回 JSON 格式的命令列表(供程序解析)
912
1291
  if (normalizedContent === '/evolhelp') {
913
1292
  const cmds = [];
914
- // 项目管理
915
- cmds.push({ command: '/pwd', description: '显示当前项目路径', category: '项目管理', roles: ['admin', 'owner'] });
916
- cmds.push({ command: '/p', aliases: ['/project', '/plist'], args: '[name|path]', description: '列出或切换项目', category: '项目管理', roles: ['admin', 'owner'] });
917
- if (isOwner) {
918
- cmds.push({ command: '/bind', args: '<path>', description: '绑定新项目目录', category: '项目管理', roles: ['owner'] });
919
- }
1293
+ // 项目
1294
+ cmds.push({ command: '/pwd', description: '显示当前项目路径', category: '项目', roles: ['admin', 'owner'] });
920
1295
  // 会话管理
921
1296
  cmds.push({ command: '/new', args: '[名称]', description: '创建新会话(清空历史请用此命令,可选命名)', category: '会话管理', roles: ['guest', 'admin', 'owner'] });
922
1297
  cmds.push({ command: '/s', aliases: ['/session', '/slist'], args: '[cli|名称|序号|uuid]', description: '列出或切换会话', category: '会话管理', roles: ['guest', 'admin', 'owner'] });
@@ -929,7 +1304,7 @@ export class CommandHandler {
929
1304
  }
930
1305
  // Agent 与模型
931
1306
  if (isAdmin) {
932
- cmds.push({ command: '/agent', args: '[name]', description: '查看或切换 Agent 后端', category: 'Agent 与模型', roles: ['admin', 'owner'] });
1307
+ cmds.push({ command: '/baseagent', aliases: ['/base'], args: '[name]', description: '查看或切换 Agent 后端', category: 'Agent 与模型', roles: ['admin', 'owner'] });
933
1308
  cmds.push({ command: '/model', args: '[model]', description: '查看或切换模型', category: 'Agent 与模型', roles: ['admin', 'owner'] });
934
1309
  cmds.push({ command: '/effort', args: '[level]', description: '查看或切换推理强度', category: 'Agent 与模型', roles: ['admin', 'owner'] });
935
1310
  }
@@ -944,13 +1319,10 @@ export class CommandHandler {
944
1319
  cmds.push({ command: '/check', description: '检查渠道状态', category: '运维', roles: ['guest', 'admin', 'owner'] });
945
1320
  if (isAdmin) {
946
1321
  cmds.push({ command: '/activity', args: '[all|dm|owner|none]', description: '查看/控制中间输出显示模式', category: '聊天设置', roles: ['admin', 'owner'] });
947
- cmds.push({ command: '/restart', args: '<channel>', description: '重连指定渠道', category: '运维', roles: ['admin', 'owner'] });
948
1322
  }
949
1323
  if (isOwner) {
950
1324
  cmds.push({ command: '/restart', description: '重启服务', category: '运维', roles: ['owner'] });
951
1325
  cmds.push({ command: '/file', args: '[channel] <path>', description: '发送项目内文件', category: '工具', roles: ['owner'] });
952
- cmds.push({ command: '/aid', args: '[list|show|new|delete|lookup|agentmd]', description: 'AID 身份管理', category: '工具', roles: ['owner'] });
953
- cmds.push({ command: '/storage', args: '[upload|download|ls|rm|quota] <aid>', description: '文件存储', category: '工具', roles: ['owner'] });
954
1326
  }
955
1327
  // 聊天设置
956
1328
  if (isAdmin) {
@@ -1178,9 +1550,9 @@ export class CommandHandler {
1178
1550
  return { kind: 'command.error', text: `❌ 读取会话记录失败: ${error instanceof Error ? error.message : '未知错误'}` };
1179
1551
  }
1180
1552
  }
1181
- // /agent 命令:查看或切换 Agent 后端
1182
- if (normalizedContent === '/agent' || normalizedContent.startsWith('/agent ')) {
1183
- const args = normalizedContent.slice(6).trim();
1553
+ // /baseagent 命令:查看或切换 Agent 后端
1554
+ if (normalizedContent === '/baseagent' || normalizedContent.startsWith('/baseagent ')) {
1555
+ const args = normalizedContent.slice(10).trim();
1184
1556
  // 切换(带参)需权限:群聊 owner only,私聊 admin+;无参查询对所有人放开
1185
1557
  if (args && (activeChatType === 'group' ? !isOwner : !isAdmin)) {
1186
1558
  return { kind: 'command.error', text: '❌ 无权限:此命令仅限管理员使用' };
@@ -1204,7 +1576,7 @@ export class CommandHandler {
1204
1576
  title: '🔌 切换 Agent',
1205
1577
  buttons: available.map(a => ({
1206
1578
  label: a === currentAgent ? `✓ ${a}` : a,
1207
- command: `/agent ${a}`,
1579
+ command: `/baseagent ${a}`,
1208
1580
  style: (a === currentAgent ? 'primary' : 'default'),
1209
1581
  disabled: a === currentAgent,
1210
1582
  })),
@@ -1220,7 +1592,7 @@ export class CommandHandler {
1220
1592
  const list = available.map(a => `${a === currentAgent ? ' ✓' : ' '} ${a}`).join('\n');
1221
1593
  const canSwitchAgent = activeChatType === 'group' ? isOwner : isAdmin;
1222
1594
  if (canSwitchAgent) {
1223
- return { kind: 'command.result', text: `当前 Agent: ${currentAgent}\n\n可用:\n${list}\n用法: /agent <name>` };
1595
+ return { kind: 'command.result', text: `当前 Agent: ${currentAgent}\n\n可用:\n${list}\n用法: /baseagent <name>` };
1224
1596
  }
1225
1597
  return { kind: 'command.result', text: `当前 Agent: ${currentAgent}` };
1226
1598
  }
@@ -1255,37 +1627,16 @@ export class CommandHandler {
1255
1627
  const currentModel = hasModelSwitcher(setmodelAgent) ? setmodelAgent.getModel() : setmodelAgent.name;
1256
1628
  const efforts = getAvailableEfforts(setmodelAgent, currentModel);
1257
1629
  const currentEffort = setmodelAgent.getEffort?.() || 'auto';
1258
- // 获取 API URL 用于请求 /models
1259
- let apiBaseUrl;
1260
- try {
1261
- const configBaseUrl = this.getOwningAgent(channel)?.config?.baseagents?.claude?.baseUrl;
1262
- const isPlaceholderUrl = configBaseUrl?.includes('api.anthropic.com');
1263
- if (configBaseUrl && !isPlaceholderUrl) {
1264
- apiBaseUrl = configBaseUrl;
1265
- }
1266
- else if (process.env.ANTHROPIC_BASE_URL) {
1267
- apiBaseUrl = process.env.ANTHROPIC_BASE_URL;
1268
- }
1269
- else {
1270
- const claudeSettingsPath = path.join(os.homedir(), '.claude', 'settings.json');
1271
- if (fs.existsSync(claudeSettingsPath)) {
1272
- const claudeSettings = JSON.parse(fs.readFileSync(claudeSettingsPath, 'utf-8'));
1273
- if (claudeSettings.env?.ANTHROPIC_BASE_URL) {
1274
- apiBaseUrl = claudeSettings.env.ANTHROPIC_BASE_URL;
1275
- }
1276
- }
1277
- }
1278
- }
1279
- catch { }
1630
+ const modelListSource = getModelListSource(this.getOwningAgent(channel), setmodelAgent);
1280
1631
  let modelListData = null;
1281
- if (apiBaseUrl) {
1632
+ if (modelListSource.apiBaseUrl) {
1282
1633
  try {
1283
- const modelsUrl = apiBaseUrl.replace(/\/+$/, '') + '/v1/models';
1634
+ const modelsUrl = modelListSource.apiBaseUrl.replace(/\/+$/, '') + '/v1/models';
1284
1635
  const controller = new AbortController();
1285
1636
  const timeout = setTimeout(() => controller.abort(), 5000);
1286
1637
  const resp = await fetch(modelsUrl, {
1287
1638
  signal: controller.signal,
1288
- headers: { 'Authorization': `Bearer ${this.getOwningAgent(channel)?.config?.baseagents?.claude?.apiKey || process.env.ANTHROPIC_AUTH_TOKEN || ''}` },
1639
+ headers: { 'Authorization': `Bearer ${modelListSource.apiKey || ''}` },
1289
1640
  });
1290
1641
  clearTimeout(timeout);
1291
1642
  if (resp.ok) {
@@ -1299,11 +1650,12 @@ export class CommandHandler {
1299
1650
  const now = Math.floor(Date.now() / 1000);
1300
1651
  modelListData = {
1301
1652
  object: 'list',
1302
- data: [
1303
- { id: 'claude-opus-4-7', object: 'model', created: now, owned_by: 'anthropic' },
1304
- { id: 'claude-opus-4-6', object: 'model', created: now, owned_by: 'anthropic' },
1305
- { id: 'claude-sonnet-4-6', object: 'model', created: now, owned_by: 'anthropic' },
1306
- ],
1653
+ data: modelListSource.fallbackModels.map(id => ({
1654
+ id,
1655
+ object: 'model',
1656
+ created: now,
1657
+ owned_by: modelListSource.owner,
1658
+ })),
1307
1659
  };
1308
1660
  }
1309
1661
  return { kind: 'command.result', text: JSON.stringify({
@@ -1510,54 +1862,12 @@ export class CommandHandler {
1510
1862
  return { kind: 'command.result', text: `${err}\n已更新运行时配置,但未持久化` };
1511
1863
  return { kind: 'command.result', text: `✓ 推理强度: ${newEffort}` };
1512
1864
  }
1513
- // /aid, /rpc, /storage — 转发到 CLI 执行
1514
- if (normalizedContent === '/aid' || normalizedContent.startsWith('/aid ') ||
1865
+ // /agent, /aid, /rpc, /storage — 仅限 ctl 调用,slash 输入拒绝
1866
+ if (normalizedContent === '/agent' || normalizedContent.startsWith('/agent ') ||
1867
+ normalizedContent === '/aid' || normalizedContent.startsWith('/aid ') ||
1515
1868
  normalizedContent === '/rpc' || normalizedContent.startsWith('/rpc ') ||
1516
1869
  normalizedContent === '/storage' || normalizedContent.startsWith('/storage ')) {
1517
- if (!isOwner)
1518
- return { kind: 'command.error', text: '❌ 无权限:此命令仅限 owner 使用' };
1519
- // 无参数时返回用法说明
1520
- if (normalizedContent === '/aid') {
1521
- return { kind: 'command.result', text: `用法:
1522
- /aid list 列出本地所有 AID
1523
- /aid show <aid> 查看 AID 详情
1524
- /aid new <aid> 创建新 AID
1525
- /aid delete <aid> 删除本地 AID
1526
- /aid lookup <aid> 远程探测 AID
1527
- /aid agentmd put <aid> 签名并上传 agent.md
1528
- /aid agentmd get <aid> 下载并验签 agent.md` };
1529
- }
1530
- if (normalizedContent === '/rpc') {
1531
- return { kind: 'command.result', text: `用法: /rpc --as <aid> --params <json>
1532
- 示例: /rpc --as myaid.agentid.pub --params {"method":"meta.ping","params":{}}` };
1533
- }
1534
- if (normalizedContent === '/storage') {
1535
- return { kind: 'command.result', text: `用法:
1536
- /storage upload <aid> <file> <path> [--public]
1537
- /storage download <aid> <url> [local-path]
1538
- /storage ls <aid> [prefix]
1539
- /storage rm <aid> <path>
1540
- /storage quota <aid>` };
1541
- }
1542
- const cliArgs = normalizedContent.slice(1); // strip leading /
1543
- try {
1544
- const { execFile } = await import('node:child_process');
1545
- const { promisify } = await import('node:util');
1546
- const execFileAsync = promisify(execFile);
1547
- const { stdout, stderr } = await execFileAsync('evolclaw', cliArgs.split(/\s+/), {
1548
- timeout: 30000,
1549
- encoding: 'utf-8',
1550
- env: { ...process.env, AUN_LOG_INI_DISABLE: '1' },
1551
- });
1552
- const output = (stdout || '').trim();
1553
- if (!output && stderr)
1554
- return { kind: 'command.result', text: `⚠ ${stderr.trim().slice(0, 500)}` };
1555
- return { kind: 'command.result', text: output || '(无输出)' };
1556
- }
1557
- catch (e) {
1558
- const msg = e.stderr?.trim() || e.stdout?.trim() || String(e.message || e);
1559
- return { kind: 'command.error', text: `❌ ${msg.slice(0, 500)}` };
1560
- }
1870
+ return { kind: 'command.error', text: '❌ 此命令仅限 ctl 调用,不支持 slash 输入' };
1561
1871
  }
1562
1872
  if (normalizedContent === '/activity' || normalizedContent.startsWith('/activity ')) {
1563
1873
  const activityArg = normalizedContent.slice(9).trim();
@@ -1876,19 +2186,14 @@ export class CommandHandler {
1876
2186
  // 尝试获取活跃会话(话题时直接查找话题 session)
1877
2187
  let session;
1878
2188
  if (threadId) {
1879
- session = await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel), threadId);
2189
+ session = await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel), threadId, undefined, undefined, undefined, chatType, undefined, undefined, this.resolveChannelType(channel));
1880
2190
  }
1881
2191
  else {
1882
2192
  session = await this.sessionManager.getActiveSession(channel, channelId);
1883
2193
  }
1884
- // 对于需要会话的命令,如果没有会话则使用默认项目创建临时会话
1885
- // 这样 /pwd、/status 等命令可以在没有活跃会话时返回默认项目信息
1886
- if (!session && (normalizedContent.startsWith('/new') ||
1887
- normalizedContent.startsWith('/bind') ||
1888
- normalizedContent.startsWith('/project') ||
1889
- normalizedContent === '/pwd' ||
1890
- normalizedContent === '/status')) {
1891
- session = await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel));
2194
+ // 如果没有会话,自动创建(所有后续命令都需要 session)
2195
+ if (!session) {
2196
+ session = await this.sessionManager.getOrCreateSession(channel, channelId, this.getEffectiveDefaultPath(channel), undefined, undefined, undefined, undefined, chatType, undefined, undefined, this.resolveChannelType(channel));
1892
2197
  }
1893
2198
  // /status 命令:显示会话状态
1894
2199
  if (normalizedContent === '/status') {
@@ -2079,44 +2384,8 @@ export class CommandHandler {
2079
2384
  }
2080
2385
  return { kind: 'command.result', text: lines.join('\n') };
2081
2386
  }
2082
- // /restart 命令:重启服务(owner only) / 重连指定渠道(admin+)
2083
- if (normalizedContent === '/restart' || normalizedContent.startsWith('/restart ')) {
2084
- const restartArg = normalizedContent.slice('/restart'.length).trim();
2085
- // /restart <type> — 重连指定类型的所有渠道(admin only)
2086
- if (restartArg) {
2087
- if (!isAdmin)
2088
- return { kind: 'command.error', text: '❌ 无权限:渠道重连仅限管理员使用' };
2089
- const type = restartArg;
2090
- // /restart 是服务级操作:重连该 type 下的所有实例(不分 agent)
2091
- const scopedNames = [];
2092
- for (const [name] of this.adapters) {
2093
- if (this.channelTypeMap.get(name) === type)
2094
- scopedNames.push(name);
2095
- }
2096
- if (scopedNames.length === 0) {
2097
- return { kind: 'command.error', text: `❌ 没有类型为 "${type}" 的渠道` };
2098
- }
2099
- const results = [];
2100
- for (const name of scopedNames) {
2101
- const ch = this.channelObjects.get(name);
2102
- if (!ch) {
2103
- results.push(`${name}: 未找到渠道对象`);
2104
- continue;
2105
- }
2106
- if (!ch.reconnect) {
2107
- results.push(`${name}: 不支持重连`);
2108
- continue;
2109
- }
2110
- try {
2111
- const result = await ch.reconnect();
2112
- results.push(`${name}: ${result}`);
2113
- }
2114
- catch (e) {
2115
- results.push(`${name}: 重连失败 - ${e?.message || e}`);
2116
- }
2117
- }
2118
- return { kind: 'command.result', text: `🔄 重连 ${type}:\n ${results.join('\n ')}` };
2119
- }
2387
+ // /restart 命令:重启服务(owner only)
2388
+ if (normalizedContent === '/restart') {
2120
2389
  // /restart(无参数)— 重启整个服务(owner only)
2121
2390
  if (!isOwner)
2122
2391
  return { kind: 'command.error', text: '❌ 无权限:服务重启仅限 owner 使用' };
@@ -2199,7 +2468,6 @@ export class CommandHandler {
2199
2468
  }
2200
2469
  // /pwd 命令:显示当前项目路径
2201
2470
  if (normalizedContent === '/pwd') {
2202
- // session 现在总是存在(上面已自动创建)
2203
2471
  if (!session) {
2204
2472
  return { kind: 'command.error', text: `❌ 无法创建会话,请检查配置` };
2205
2473
  }
@@ -2313,241 +2581,6 @@ export class CommandHandler {
2313
2581
  return { kind: 'command.error', text: `❌ 文件发送失败: ${error.message || error}` };
2314
2582
  }
2315
2583
  }
2316
- // /plist 命令:列出所有项目
2317
- if (normalizedContent === '/plist') {
2318
- if (!policy.canListProjects(session?.chatType || 'private', identity.role)) {
2319
- if (!session) {
2320
- return { kind: 'command.error', text: `❌ 当前群聊未绑定项目
2321
-
2322
- 请使用 /bind <项目路径> 绑定项目` };
2323
- }
2324
- const projectName = this.getProjectName(session.projectPath);
2325
- const isProcessing = !!session.processingState;
2326
- const status = isProcessing ? '[处理中]' : '[空闲]';
2327
- return { kind: 'command.result', text: `当前群聊绑定的项目:
2328
- ${projectName} (${session.projectPath}) - ${status}
2329
-
2330
- 提示:群聊不支持切换项目` };
2331
- }
2332
- // 收集项目信息并按最近活跃排序(唯一来源:agent config projects.list)
2333
- const entries = [];
2334
- for (const [name, projectPath] of Object.entries(this.projects)) {
2335
- // 跳过不存在的路径
2336
- if (!fs.existsSync(projectPath))
2337
- continue;
2338
- const isCurrent = session ? path.resolve(session.projectPath) === path.resolve(projectPath) : false;
2339
- const projectSession = await this.sessionManager.getSessionByProjectPath(channel, channelId, projectPath);
2340
- entries.push({
2341
- name, projectPath, projectSession, isCurrent,
2342
- updatedAt: projectSession?.updatedAt ?? 0,
2343
- });
2344
- }
2345
- // 当前活跃项目置顶,其余按 updatedAt 降序
2346
- entries.sort((a, b) => {
2347
- if (a.isCurrent !== b.isCurrent)
2348
- return a.isCurrent ? -1 : 1;
2349
- return b.updatedAt - a.updatedAt;
2350
- });
2351
- // 构建项目状态文本的辅助函数
2352
- const buildStatusText = (entry) => {
2353
- const { projectSession, isCurrent } = entry;
2354
- if (!projectSession)
2355
- return '无会话';
2356
- const parts = [];
2357
- if (isCurrent) {
2358
- parts.push('活跃');
2359
- }
2360
- else {
2361
- parts.push(formatIdleTime(Date.now() - projectSession.updatedAt));
2362
- }
2363
- const isProcessing = !!projectSession.processingState;
2364
- if (isProcessing) {
2365
- const qLen = this.messageQueue.getQueueLength(projectSession.id);
2366
- parts.push(qLen > 0 ? `[处理中,队列${qLen}条]` : '[处理中]');
2367
- }
2368
- const unread = this.messageCache.getCount(projectSession.id);
2369
- if (unread > 0) {
2370
- parts.push(`[${unread}条新消息]`);
2371
- }
2372
- else if (!isProcessing && !isCurrent) {
2373
- parts.push('[空闲]');
2374
- }
2375
- return parts.join(' ');
2376
- };
2377
- // 尝试发送 CommandCard 卡片(每个项目一个按钮,一键切换)
2378
- if (entries.length > 0) {
2379
- const bodyLines = entries.map(e => {
2380
- const status = buildStatusText(e);
2381
- const prefix = e.isCurrent ? '✓' : '•';
2382
- return `${prefix} **${e.name}** (${e.projectPath}) ${status}`;
2383
- });
2384
- const interaction = {
2385
- type: 'interaction',
2386
- id: `plist-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`,
2387
- channelId,
2388
- sessionId: activeSession?.id || '',
2389
- initiatorId: userId,
2390
- kind: {
2391
- kind: 'command-card',
2392
- title: '📂 项目列表',
2393
- body: bodyLines.join('\n'),
2394
- buttons: entries.map(e => ({
2395
- label: e.isCurrent ? `✓ ${e.name}` : e.name,
2396
- command: `/project ${e.name}`,
2397
- style: (e.isCurrent ? 'primary' : 'default'),
2398
- disabled: e.isCurrent,
2399
- })),
2400
- },
2401
- };
2402
- const replyCtx = activeSession ? this.getReplyContext(activeSession) : undefined;
2403
- const cardResult = await this.sendCommandCard({ channel, channelId, interaction, replyCtx, canWrite: isAdmin });
2404
- if (cardResult === null)
2405
- return null;
2406
- return { kind: 'command.result', text: cardResult };
2407
- }
2408
- // 降级:文本列表
2409
- const lines = ['可用项目:'];
2410
- for (const entry of entries) {
2411
- const prefix = entry.isCurrent ? ' ✓' : ' ';
2412
- lines.push(`${prefix} ${entry.name} (${entry.projectPath}) - ${buildStatusText(entry)}`);
2413
- }
2414
- lines.push('', '提示: 使用 /p <名称> 切换项目');
2415
- return { kind: 'command.result', text: lines.join('\n') };
2416
- }
2417
- // /project(无参数):直接复用 /plist 逻辑(含卡片交互)
2418
- if (normalizedContent === '/project') {
2419
- if (!policy.canSwitchProject(session?.chatType || 'private', identity.role)) {
2420
- // 群聊不能切换项目,交由 /plist 逻辑处理
2421
- }
2422
- const delegated = await this.handle('/plist', channel, channelId, undefined, userId, threadId);
2423
- return typeof delegated === 'string' ? { kind: 'command.result', text: delegated } : delegated;
2424
- }
2425
- // /project 命令:切换项目(支持名称或路径)
2426
- if (normalizedContent.startsWith('/project ')) {
2427
- if (!policy.canSwitchProject(session?.chatType || 'private', identity.role)) {
2428
- return { kind: 'command.error', text: `❌ 群聊不支持切换项目
2429
-
2430
- 群聊只能绑定一个项目。如需更换项目,请联系管理员重新配置。` };
2431
- }
2432
- let arg = normalizedContent.slice(9).trim();
2433
- if (!arg)
2434
- return { kind: 'command.result', text: '用法: /p <name|path> 或 /project <name|path>' };
2435
- // 检查确认标志
2436
- const hasConfirm = arg.endsWith(' --confirm');
2437
- if (hasConfirm) {
2438
- arg = arg.slice(0, -10).trim();
2439
- }
2440
- let projectPath;
2441
- let projectName;
2442
- if (arg.includes('/')) {
2443
- if (!path.isAbsolute(arg)) {
2444
- return { kind: 'command.error', text: '❌ 项目路径必须是绝对路径' };
2445
- }
2446
- if (!fs.existsSync(arg)) {
2447
- return { kind: 'command.error', text: `❌ 路径不存在: ${arg}` };
2448
- }
2449
- projectPath = arg;
2450
- projectName = path.basename(arg);
2451
- }
2452
- else {
2453
- projectPath = this.projects[arg];
2454
- if (!projectPath) {
2455
- return { kind: 'command.error', text: `❌ 项目 "${arg}" 不存在\n提示: 使用 /p 查看可用项目` };
2456
- }
2457
- projectName = arg;
2458
- }
2459
- if (session) {
2460
- const normalizedSessionPath = path.resolve(session.projectPath);
2461
- const normalizedProjectPath = path.resolve(projectPath);
2462
- if (normalizedSessionPath === normalizedProjectPath) {
2463
- return { kind: 'command.result', text: `当前已在项目: ${projectName}\n 路径: ${projectPath}` };
2464
- }
2465
- }
2466
- // 群聊切换项目需要确认
2467
- const isGroupChat = session?.chatType === 'group';
2468
- if (isGroupChat && !hasConfirm) {
2469
- return { kind: 'command.error', text: `⚠️ 群聊切换项目风险提示:
2470
-
2471
- 切换项目将影响所有群成员的对话上下文,可能导致:
2472
- • 当前项目的会话历史被切换
2473
- • 正在处理的任务被中断
2474
- • 其他成员的工作受到影响
2475
-
2476
- 确认切换请执行:
2477
- /p ${projectName} --confirm` };
2478
- }
2479
- const currentAgentId = activeSession?.agentId || this.primaryRunnerKey;
2480
- const newSession = await this.sessionManager.switchProject(channel, channelId, projectPath, currentAgentId);
2481
- this.eventBus.publish({
2482
- type: 'project:switched',
2483
- sessionId: newSession.id,
2484
- channel,
2485
- channelId,
2486
- projectPath,
2487
- timestamp: Date.now()
2488
- });
2489
- const cachedEvents = this.messageCache.getEvents(newSession.id);
2490
- const hasExistingSession = newSession.agentSessionId ? '(恢复已有会话)' : '(新建会话)';
2491
- const currentAgent = newSession.agentId || this.primaryRunnerKey;
2492
- let response = `✓ 已切换到项目: ${projectName}\n 路径: ${projectPath}\n Agent: ${currentAgent}\n ${hasExistingSession}`;
2493
- if (cachedEvents.length > 0 && sendMessage) {
2494
- for (const event of cachedEvents) {
2495
- if (event.type === 'completed') {
2496
- response += `\n\n后台任务完成`;
2497
- if (event.metadata?.duration) {
2498
- response += ` (耗时: ${Math.round(event.metadata.duration / 1000)}s)`;
2499
- }
2500
- }
2501
- else if (event.type === 'error') {
2502
- response += `\n\n后台任务失败: ${event.metadata?.errorType || '未知错误'}`;
2503
- }
2504
- }
2505
- await sendMessage(channelId, response);
2506
- for (const event of cachedEvents) {
2507
- await sendMessage(channelId, event.message);
2508
- }
2509
- this.messageCache.clearEvents(newSession.id);
2510
- return { kind: 'command.result', text: '' };
2511
- }
2512
- return { kind: 'command.result', text: response };
2513
- }
2514
- // /bind 命令:持久化项目到配置(不切换)(owner only)
2515
- if (normalizedContent === '/bind')
2516
- return { kind: 'command.result', text: '用法: /bind <路径>' };
2517
- if (normalizedContent.startsWith('/bind ')) {
2518
- if (!isOwner)
2519
- return { kind: 'command.error', text: '❌ 无权限:此命令仅限 owner 使用' };
2520
- const projectPath = normalizedContent.slice(6).trim();
2521
- if (!projectPath)
2522
- return { kind: 'command.result', text: '用法: /bind <路径>' };
2523
- if (!path.isAbsolute(projectPath)) {
2524
- return { kind: 'command.error', text: '❌ 项目路径必须是绝对路径' };
2525
- }
2526
- if (!fs.existsSync(projectPath)) {
2527
- if (this.getOwningAgent(channel)?.config?.projects?.autoCreate) {
2528
- fs.mkdirSync(projectPath, { recursive: true });
2529
- }
2530
- else {
2531
- return { kind: 'command.error', text: `❌ 路径不存在: ${projectPath}` };
2532
- }
2533
- }
2534
- // 生成项目名称(使用目录名)
2535
- const projectName = path.basename(projectPath);
2536
- // 检查在当前 scope 内是否已存在
2537
- const scopeProjects = this.getEffectiveProjects(channel);
2538
- const existing = scopeProjects[projectName];
2539
- if (existing) {
2540
- if (existing === projectPath) {
2541
- return { kind: 'command.result', text: `项目 "${projectName}" 已存在\n 路径: ${projectPath}\n\n使用 /p ${projectName} 切换到该项目` };
2542
- }
2543
- return { kind: 'command.error', text: `❌ 项目名称 "${projectName}" 已被占用\n 现有路径: ${existing}\n 新路径: ${projectPath}\n\n请重命名目录或手动编辑配置文件` };
2544
- }
2545
- // 写入:agent-owned channel → agent.json;default → agent config
2546
- const err = await this.addProjectInScope(channel, projectName, projectPath);
2547
- if (err)
2548
- return { kind: 'command.result', text: err };
2549
- return { kind: 'command.result', text: `✓ 已添加项目: ${projectName}\n 路径: ${projectPath}\n\n使用 /p ${projectName} 切换到该项目` };
2550
- }
2551
2584
  // /slist 命令:列出当前项目的会话
2552
2585
  // /slist — 仅 EvolClaw 会话
2553
2586
  // /slist cli — 仅 CLI 会话(未导入的)
@@ -2557,8 +2590,7 @@ export class CommandHandler {
2557
2590
 
2558
2591
  请先执行以下操作之一:
2559
2592
  1. 发送任意消息 - 自动创建新会话
2560
- 2. /new [名称] - 创建命名会话
2561
- 3. /p <项目> - 切换到指定项目` };
2593
+ 2. /new [名称] - 创建命名会话` };
2562
2594
  }
2563
2595
  const showCliOnly = normalizedContent === '/slist cli';
2564
2596
  // /slist cli — 仅显示 CLI 会话
@@ -3274,13 +3306,13 @@ export class CommandHandler {
3274
3306
  // ── Agent Ctl ──
3275
3307
  static CTL_COMMANDS = [
3276
3308
  '/help', '/status', '/check', '/pwd',
3277
- '/model', '/effort', '/perm', '/agent',
3278
- '/compact', '/file', '/send', '/restart', '/bind', '/aid', '/rpc', '/storage',
3279
- '/rename', '/name', '/evolagent', '/trigger',
3309
+ '/model', '/effort', '/perm', '/agent', '/baseagent',
3310
+ '/compact', '/file', '/send', '/restart', '/aid', '/rpc', '/storage',
3311
+ '/rename', '/name', '/trigger',
3280
3312
  '/chatmode', '/dispatch', '/activity',
3281
3313
  ];
3282
3314
  /** ctl 中仅允许查询形态的指令;写形态(带参)一律拒绝 */
3283
- static CTL_READONLY = new Set(['/agent']);
3315
+ static CTL_READONLY = new Set(['/baseagent']);
3284
3316
  /**
3285
3317
  * 从 session 恢复 ReplyContext,用于 ctl send 主动发送文本时的路由
3286
3318
  * - 群聊话题:metadata.replyContext.{threadId,peerId}
@@ -3334,47 +3366,45 @@ export class CommandHandler {
3334
3366
  }
3335
3367
  // 3. 从 session.metadata.peerId 获取 userId(用于权限判断)
3336
3368
  const userId = session.metadata?.peerId;
3337
- // 3.1 /evolagent: EvolAgent 管理(show identity / reload
3338
- if (cmd === '/evolagent' || cmd.startsWith('/evolagent ')) {
3339
- const arg = cmd.slice('/evolagent'.length).trim();
3369
+ // 3.1 /agent: EvolAgent 管理(转发到 CLI
3370
+ if (cmd === '/agent' || cmd.startsWith('/agent ')) {
3371
+ const arg = cmd.slice('/agent'.length).trim();
3372
+ // 无参数时返回用法
3340
3373
  if (!arg) {
3341
- const owning = this.getOwningAgent(session.channel);
3342
- if (owning) {
3343
- return { ok: true, result: `当前 EvolAgent: ${owning.name} (${owning.baseagent})` };
3344
- }
3345
- return { ok: true, result: '当前为 DefaultAgent 模式' };
3374
+ return { ok: true, result: `用法:\n /agent list 列出所有 agent\n /agent show [name] 查看 agent 详情\n /agent enable <name> 启用 agent\n /agent disable <name> 停用 agent\n /agent get <name> <key> 读取配置字段\n /agent set <name> <key> <val> 修改配置字段\n /agent rename <name> <newname> 修改名称\n /agent reload [name] 热重载配置` };
3375
+ }
3376
+ const parts = arg.split(/\s+/);
3377
+ const subCmd = parts[0];
3378
+ // ctl 禁止 new/delete(仅限 CLI 操作)
3379
+ if (subCmd === 'new' || subCmd === 'delete') {
3380
+ return { ok: false, error: `❌ /agent ${subCmd} 仅限 CLI 操作,请使用: evolclaw agent ${subCmd} ...` };
3381
+ }
3382
+ // 自我保护:不能 disable 自己所在的 agent
3383
+ const selfAgent = this.getOwningAgent(session.channel);
3384
+ const selfName = selfAgent?.name;
3385
+ if (selfName && subCmd === 'disable' && parts[1] === selfName) {
3386
+ return { ok: false, error: `❌ 不能 disable 自己所在的 agent: ${selfName}` };
3387
+ }
3388
+ // 转发到 CLI
3389
+ const cliArgs = ['agent', ...parts];
3390
+ try {
3391
+ const { execFile } = await import('node:child_process');
3392
+ const { promisify } = await import('node:util');
3393
+ const execFileAsync = promisify(execFile);
3394
+ const { stdout, stderr } = await execFileAsync('evolclaw', cliArgs, {
3395
+ timeout: 30000,
3396
+ encoding: 'utf-8',
3397
+ env: { ...process.env, AUN_LOG_INI_DISABLE: '1' },
3398
+ });
3399
+ const output = (stdout || '').trim();
3400
+ if (!output && stderr)
3401
+ return { ok: true, result: `⚠ ${stderr.trim().slice(0, 500)}` };
3402
+ return { ok: true, result: output || '(无输出)' };
3346
3403
  }
3347
- if (arg.startsWith('reload ') || arg === 'reload') {
3348
- const name = arg === 'reload' ? '' : arg.slice('reload '.length).trim();
3349
- if (!name)
3350
- return { ok: false, error: '用法: evolclaw ctl evolagent reload <name>' };
3351
- // I8: reload is a structural op, require admin or owner
3352
- if (!userId) {
3353
- return { ok: false, error: '权限不足:evolagent reload 仅 owner/admin 可用' };
3354
- }
3355
- const identity = this.sessionManager.resolveIdentity(session.channel, userId);
3356
- if (identity.role !== 'owner' && identity.role !== 'admin') {
3357
- return { ok: false, error: '权限不足:evolagent reload 仅 owner/admin 可用' };
3358
- }
3359
- if (!this.agentRegistry)
3360
- return { ok: false, error: 'EvolAgentRegistry not available' };
3361
- const a = this.agentRegistry.get(name);
3362
- if (!a)
3363
- return { ok: false, error: `Agent "${name}" not found` };
3364
- const hooks = globalThis.__evolclaw_reloadHooks;
3365
- if (!hooks)
3366
- return { ok: false, error: 'Reload hooks not initialized' };
3367
- if (!this.agentRegistry.reload)
3368
- return { ok: false, error: 'EvolAgentRegistry.reload not available' };
3369
- try {
3370
- await this.agentRegistry.reload(name, hooks);
3371
- return { ok: true, result: `Agent "${name}" reloaded` };
3372
- }
3373
- catch (e) {
3374
- return { ok: false, error: `Reload failed: ${e?.message || e}` };
3375
- }
3404
+ catch (e) {
3405
+ const msg = e.stderr?.trim() || e.stdout?.trim() || String(e.message || e);
3406
+ return { ok: false, error: msg.slice(0, 500) };
3376
3407
  }
3377
- return { ok: false, error: '用法: evolclaw ctl evolagent [reload <name>]' };
3378
3408
  }
3379
3409
  // 4. /send 文本消息:直接通过 adapter 主动发送,不走 handle()
3380
3410
  if (cmd.startsWith('/send ') || cmd === '/send') {
@@ -3417,6 +3447,56 @@ export class CommandHandler {
3417
3447
  }
3418
3448
  }
3419
3449
  }
3450
+ // 5.1 /aid, /rpc, /storage — ctl 专属,转发到 CLI 执行
3451
+ if (cmd === '/aid' || cmd.startsWith('/aid ') ||
3452
+ cmd === '/rpc' || cmd.startsWith('/rpc ') ||
3453
+ cmd === '/storage' || cmd.startsWith('/storage ')) {
3454
+ // 权限检查:仅 owner
3455
+ if (userId) {
3456
+ const identity = this.sessionManager.resolveIdentity(session.channel, userId);
3457
+ if (identity.role !== 'owner') {
3458
+ return { ok: false, error: '无权限:此命令仅限 owner 使用' };
3459
+ }
3460
+ }
3461
+ // 无参数时返回用法说明
3462
+ if (cmd === '/aid') {
3463
+ return { ok: true, result: `用法:\n /aid list 列出本地所有 AID\n /aid show <aid> 查看 AID 详情\n /aid new <aid> 创建新 AID\n /aid delete <aid> 删除本地 AID\n /aid lookup <aid> 远程探测 AID\n /aid agentmd put <aid> 签名并上传 agent.md\n /aid agentmd get <aid> 下载并验签 agent.md` };
3464
+ }
3465
+ if (cmd === '/rpc') {
3466
+ return { ok: true, result: `用法: /rpc --as <aid> --params <json>\n示例: /rpc --as myaid.agentid.pub --params {"method":"meta.ping","params":{}}` };
3467
+ }
3468
+ if (cmd === '/storage') {
3469
+ return { ok: true, result: `用法:\n /storage upload <aid> <file> <path> [--public]\n /storage download <aid> <url> [local-path]\n /storage ls <aid> [prefix]\n /storage rm <aid> <path>\n /storage quota <aid>` };
3470
+ }
3471
+ // /aid 自我保护:不能删除当前 agent 所用的 AID
3472
+ if (cmd.startsWith('/aid delete ')) {
3473
+ const targetAid = cmd.slice('/aid delete '.length).trim();
3474
+ const selfAgent = this.getOwningAgent(session.channel);
3475
+ const selfAid = selfAgent?.config?.aid;
3476
+ if (selfAid && targetAid === selfAid) {
3477
+ return { ok: false, error: `❌ 不能删除当前 agent 所用的 AID: ${selfAid}` };
3478
+ }
3479
+ }
3480
+ const cliArgs = cmd.slice(1); // strip leading /
3481
+ try {
3482
+ const { execFile } = await import('node:child_process');
3483
+ const { promisify } = await import('node:util');
3484
+ const execFileAsync = promisify(execFile);
3485
+ const { stdout, stderr } = await execFileAsync('evolclaw', cliArgs.split(/\s+/), {
3486
+ timeout: 30000,
3487
+ encoding: 'utf-8',
3488
+ env: { ...process.env, AUN_LOG_INI_DISABLE: '1' },
3489
+ });
3490
+ const output = (stdout || '').trim();
3491
+ if (!output && stderr)
3492
+ return { ok: true, result: `⚠ ${stderr.trim().slice(0, 500)}` };
3493
+ return { ok: true, result: output || '(无输出)' };
3494
+ }
3495
+ catch (e) {
3496
+ const msg = e.stderr?.trim() || e.stdout?.trim() || String(e.message || e);
3497
+ return { ok: false, error: msg.slice(0, 500) };
3498
+ }
3499
+ }
3420
3500
  // 6. 调用现有 handle(),不传 sendMessage 回调(结果直接返回)
3421
3501
  try {
3422
3502
  const result = await this.handle(cmd, session.channel, session.channelId, undefined, // 不发送消息