cladogram 0.5.5-beta.7 → 0.5.5-beta.9

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.
@@ -17,7 +17,14 @@ import {
17
17
  import {
18
18
  buildDispatchPrompt, createRunRecord, discoverExecutors, listRunRecords, publicExecutorList, updateRunRecord,
19
19
  } from '../agent/executors.js';
20
- import { resolveProviderCredentials } from '../agent/providers/index.js';
20
+ import {
21
+ PROVIDER_PRESETS,
22
+ fetchProviderModels,
23
+ getProviderPreset,
24
+ listConfiguredModels,
25
+ maskApiKey,
26
+ resolveProviderCredentials,
27
+ } from '../agent/providers/index.js';
21
28
  import {
22
29
  archiveSessionRecord,
23
30
  BUILTIN_PERSONAS,
@@ -32,12 +39,22 @@ import {
32
39
  saveSessionRecord,
33
40
  } from '../agent/sessions.js';
34
41
  import { runVerticalAgent } from '../agent/runtime.js';
42
+ import {
43
+ deleteMcpServer,
44
+ importMcpJson,
45
+ listMcpServers,
46
+ saveMcpServer,
47
+ testMcpServer,
48
+ toggleMcpServer,
49
+ } from '../agent/mcp-client.js';
50
+ import { deleteSkill, listSkills, readSkill, saveSkill } from '../agent/skills.js';
51
+ import { deleteCommand, expandSlashCommand, listCommands, saveCommand } from '../agent/commands.js';
35
52
 
36
53
  const idleMs = 15 * 60_000;
37
54
  const turnMs = 5 * 60_000;
38
55
  const MAX_PEER_HOPS = 8;
39
56
  const sessionId = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
40
- const personaSchema = z.enum(['architect', 'coder', 'qa', 'auditor', 'custom']);
57
+ const personaSchema = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/);
41
58
  const execModeSchema = z.enum(['plan', 'act']);
42
59
  const canvasObjectItemSchema = z.strictObject({
43
60
  id: z.string().min(1).max(120),
@@ -192,6 +209,7 @@ export function createAgentHandler({
192
209
  args = [],
193
210
  resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
194
211
  resolveSettings = null,
212
+ saveSettings = null,
195
213
  resolveRuntimeInfo = null,
196
214
  workspaceService = null,
197
215
  events = null,
@@ -205,6 +223,40 @@ export function createAgentHandler({
205
223
  return { ...launch, ...base };
206
224
  };
207
225
 
226
+ function buildLlmState(settings = {}) {
227
+ const creds = resolveProviderCredentials(settings);
228
+ const profiles = {};
229
+ for (const preset of PROVIDER_PRESETS) {
230
+ const raw = settings.providers?.[preset.id] || {};
231
+ const isLegacyMatch = !settings.providers && (settings.providerId || 'openai') === preset.id;
232
+ const key = raw.apiKey ?? (isLegacyMatch ? settings.apiKey : '');
233
+ profiles[preset.id] = {
234
+ label: raw.label || preset.label,
235
+ protocol: raw.protocol || preset.protocol,
236
+ baseUrl: raw.baseUrl || (isLegacyMatch ? settings.baseUrl : '') || preset.defaultBaseUrl,
237
+ model: raw.model || (isLegacyMatch ? settings.model : '') || preset.defaultModel,
238
+ models: Array.isArray(raw.models) && raw.models.length ? raw.models : preset.models,
239
+ hasApiKey: Boolean(String(key || '').trim()),
240
+ maskedKey: maskApiKey(key),
241
+ requiresKey: preset.requiresKey !== false,
242
+ };
243
+ }
244
+ return {
245
+ configured: creds.configured,
246
+ providerId: creds.providerId,
247
+ providerLabel: creds.providerLabel,
248
+ protocol: creds.provider,
249
+ baseUrl: creds.baseUrl,
250
+ model: creds.model,
251
+ hasApiKey: creds.hasApiKey,
252
+ presets: PROVIDER_PRESETS,
253
+ profiles,
254
+ quickModels: listConfiguredModels(settings),
255
+ acpCommand: settings.command || 'zcode-acp-server',
256
+ acpArgs: Array.isArray(settings.args) ? settings.args : [],
257
+ };
258
+ }
259
+
208
260
  function runningSessionIds(targetWorkspace) {
209
261
  const set = new Set();
210
262
  for (const s of sessions.values()) {
@@ -280,24 +332,26 @@ export function createAgentHandler({
280
332
  settings,
281
333
  pluginDescriptors: rtInfo.pluginDescriptors || [],
282
334
  });
283
- const creds = resolveProviderCredentials(settings);
284
- const builtinConfigured = Boolean(creds.apiKey);
285
- const configuredMode = settings.mode || 'auto';
286
- const activeEngine = configuredMode === 'builtin'
287
- ? 'builtin'
288
- : configuredMode === 'acp'
289
- ? 'acp'
290
- : (builtinConfigured ? 'builtin' : 'acp');
335
+ const llm = buildLlmState(settings);
336
+ const builtinConfigured = Boolean(llm.configured);
337
+ // Clado 产品定位为原生 Agent 优先:只要挂载了工作区设置(resolveSettings),主引擎默认恒为 builtin,
338
+ // 仅当显式强制设为 acp(或纯 ACP 单元测试未提供 resolveSettings)时才退回 acp。
339
+ const activeEngine = !resolveSettings
340
+ ? (builtinConfigured ? 'builtin' : 'acp')
341
+ : (settings.mode === 'acp' ? 'acp' : 'builtin');
291
342
  return {
292
343
  settings,
344
+ llm,
293
345
  debugConfig: debugBundle.config,
294
346
  hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
295
347
  rtInfo,
296
348
  executors,
297
349
  builtinConfigured,
298
350
  activeEngine,
299
- provider: creds.provider,
300
- model: creds.model,
351
+ provider: llm.protocol,
352
+ providerId: llm.providerId,
353
+ providerLabel: llm.providerLabel,
354
+ model: llm.model,
301
355
  defaultPersona: settings.persona || 'architect',
302
356
  };
303
357
  }
@@ -313,6 +367,7 @@ export function createAgentHandler({
313
367
  title: defaults.title || saved?.title || '',
314
368
  persona,
315
369
  pal: saved?.pal || paletteForPersona(persona),
370
+ engine: (defaults.engine || saved?.engine) === 'acp' ? 'acp' : 'builtin',
316
371
  mode: defaults.mode || saved?.mode || 'design',
317
372
  execMode: defaults.execMode || saved?.execMode || 'act',
318
373
  liveStatus: saved?.liveStatus || '',
@@ -376,7 +431,7 @@ export function createAgentHandler({
376
431
  const incoming = peerSession.incomingPeerMessages.splice(0);
377
432
  const result = await runVerticalAgent({
378
433
  workspace: targetWorkspace,
379
- rootWorkspace: workspace,
434
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
380
435
  documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
381
436
  stateDir: meta.rtInfo.stateDir,
382
437
  workspaceService,
@@ -611,11 +666,25 @@ export function createAgentHandler({
611
666
  };
612
667
  }
613
668
 
614
- function handleMeta(req, res, targetWorkspace = workspace) {
669
+ function handleMeta(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
615
670
  const host = req.headers.host || '';
616
671
  if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
617
672
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
618
673
  const meta = resolveMeta(targetWorkspace);
674
+ const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
675
+ const pluginMcp = Array.isArray(meta.rtInfo.pluginMcp) ? meta.rtInfo.pluginMcp : [];
676
+ const pluginPersonas = Array.isArray(meta.rtInfo.pluginPersonas) ? meta.rtInfo.pluginPersonas : [];
677
+ const customPersonasMap = meta.debugConfig?.personas || {};
678
+ const mergedPersonas = new Map(BUILTIN_PERSONAS.map(p => [p.id, { id: p.id, name: p.name, summary: p.summary, builtin: true }]));
679
+ for (const p of pluginPersonas) {
680
+ mergedPersonas.set(p.id, { id: p.id, name: p.name, summary: (p.prompt || '').slice(0, 48), pluginId: p.pluginId });
681
+ }
682
+ for (const [k, v] of Object.entries(customPersonasMap)) {
683
+ if (!v || typeof v !== 'object' || !v.custom) continue;
684
+ if (!mergedPersonas.has(k)) {
685
+ mergedPersonas.set(k, { id: k, name: v.name || k, summary: (v.prompt || '').slice(0, 48), custom: true });
686
+ }
687
+ }
619
688
  res.writeHead(200, {
620
689
  'content-type': 'application/json; charset=utf-8',
621
690
  'cache-control': 'no-store',
@@ -624,10 +693,17 @@ export function createAgentHandler({
624
693
  res.end(JSON.stringify({
625
694
  engine: meta.activeEngine,
626
695
  provider: meta.provider,
696
+ providerId: meta.providerId,
697
+ providerLabel: meta.providerLabel,
627
698
  builtinConfigured: meta.builtinConfigured,
628
699
  model: meta.model,
700
+ llm: meta.llm,
701
+ mcpUrl: mcpUrl(),
702
+ mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
703
+ skills: listSkills(targetWorkspace, { pluginDirs }),
704
+ commands: listCommands(targetWorkspace, { pluginDirs }),
629
705
  defaultPersona: meta.defaultPersona,
630
- personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
706
+ personas: [...mergedPersonas.values()],
631
707
  personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
632
708
  executors: publicExecutorList(meta.executors),
633
709
  runs: listRunRecords(meta.rtInfo.stateDir, 10),
@@ -640,7 +716,7 @@ export function createAgentHandler({
640
716
  }));
641
717
  }
642
718
 
643
- function handleSessions(req, res, url, targetWorkspace = workspace) {
719
+ function handleSessions(req, res, url, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
644
720
  const host = req.headers.host || '';
645
721
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
646
722
  const meta = resolveMeta(targetWorkspace);
@@ -684,18 +760,21 @@ export function createAgentHandler({
684
760
 
685
761
  if (act === 'create') {
686
762
  const newId = safeSessionId(body.id) || randomUUID();
687
- const persona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : meta.defaultPersona;
763
+ const isAcpSub = body.engine === 'acp';
764
+ const persona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : meta.defaultPersona;
688
765
  const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
689
- const title = String(body.title || resolved.name || '新会话').trim().slice(0, 48);
766
+ const defaultTitle = isAcpSub ? 'ACP 子代理' : (resolved.name || '新会话');
767
+ const title = String(body.title || defaultTitle).trim().slice(0, 48);
690
768
  const saved = saveSessionRecord(stateDir, {
691
769
  id: newId,
692
770
  title,
693
771
  persona,
694
- pal: body.pal || resolved.pal || paletteForPersona(persona),
772
+ pal: body.pal || (isAcpSub ? 'cyan' : (resolved.pal || paletteForPersona(persona))),
773
+ engine: isAcpSub ? 'acp' : 'builtin',
695
774
  mode: ['general', 'design', 'qa', 'audit'].includes(body.mode) ? body.mode : 'design',
696
775
  execMode: body.execMode === 'plan' ? 'plan' : 'act',
697
776
  archived: false,
698
- liveStatus: '等待指令…',
777
+ liveStatus: isAcpSub ? 'ACP 外部子代理待命…' : '等待指令…',
699
778
  messages: [],
700
779
  uiMessages: [],
701
780
  });
@@ -705,6 +784,47 @@ export function createAgentHandler({
705
784
  return;
706
785
  }
707
786
 
787
+ if (act === 'rename') {
788
+ const targetId = safeSessionId(body.id);
789
+ const nextTitle = String(body.title || '').trim().slice(0, 48);
790
+ if (!targetId || !nextTitle) throw new DocumentError('缺少会话 id 或新名称。', 400);
791
+ const existing = loadSessionRecord(stateDir, targetId);
792
+ const mem = sessions.get(targetId);
793
+ if (mem) mem.title = nextTitle;
794
+ const updated = saveSessionRecord(stateDir, {
795
+ ...(existing || { id: targetId, persona: mem?.persona || meta.defaultPersona }),
796
+ id: targetId,
797
+ title: nextTitle,
798
+ touchActivity: false,
799
+ });
800
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
801
+ sendJson(200, { session: updated });
802
+ return;
803
+ }
804
+
805
+ if (act === 'set_persona') {
806
+ const targetId = safeSessionId(body.id);
807
+ const nextPersona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : 'architect';
808
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
809
+ const nextPal = paletteForPersona(nextPersona);
810
+ const mem = sessions.get(targetId);
811
+ if (mem) {
812
+ mem.persona = nextPersona;
813
+ mem.pal = nextPal;
814
+ }
815
+ const existing = loadSessionRecord(stateDir, targetId);
816
+ const updated = saveSessionRecord(stateDir, {
817
+ ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona, '', meta.debugConfig.personas).name }),
818
+ id: targetId,
819
+ persona: nextPersona,
820
+ pal: nextPal,
821
+ touchActivity: false,
822
+ });
823
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
824
+ sendJson(200, { session: updated });
825
+ return;
826
+ }
827
+
708
828
  if (act === 'archive' || act === 'unarchive') {
709
829
  const targetId = safeSessionId(body.id);
710
830
  if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
@@ -786,9 +906,10 @@ export function createAgentHandler({
786
906
  throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
787
907
  }
788
908
 
789
- async function handleConfig(req, res, targetWorkspace = workspace) {
909
+ async function handleConfig(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
790
910
  const host = req.headers.host || '';
791
911
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
912
+ const rootWs = typeof workspace === 'function' ? workspace() : workspace;
792
913
  const meta = resolveMeta(targetWorkspace);
793
914
  const stateDir = meta.rtInfo.stateDir;
794
915
  const sendJson = (status, data) => {
@@ -803,7 +924,7 @@ export function createAgentHandler({
803
924
  const computeSampleTelemetry = cfg => {
804
925
  const sample = buildSegmentedPromptContext({
805
926
  workspace: targetWorkspace,
806
- rootWorkspace: workspace,
927
+ rootWorkspace: rootWs,
807
928
  documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
808
929
  stateDir,
809
930
  debugConfig: cfg,
@@ -814,9 +935,19 @@ export function createAgentHandler({
814
935
  return sample.telemetry;
815
936
  };
816
937
 
938
+ const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
939
+ const pluginMcp = Array.isArray(meta.rtInfo.pluginMcp) ? meta.rtInfo.pluginMcp : [];
940
+ const pluginPersonas = Array.isArray(meta.rtInfo.pluginPersonas) ? meta.rtInfo.pluginPersonas : [];
941
+
817
942
  if (req.method === 'GET') {
818
- const memory = readWorkspaceMemory(stateDir, workspace);
943
+ const memory = readWorkspaceMemory(stateDir, rootWs);
819
944
  sendJson(200, {
945
+ llm: meta.llm,
946
+ mcpUrl: mcpUrl(),
947
+ mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
948
+ skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }),
949
+ commands: listCommands(targetWorkspace, { pluginDirs }),
950
+ pluginPersonas,
820
951
  config: meta.debugConfig,
821
952
  hasWorkspaceOverride: meta.hasWorkspaceOverride,
822
953
  memory,
@@ -830,10 +961,130 @@ export function createAgentHandler({
830
961
  throw new DocumentError('配置修改只接受本机同源页面请求。', 403);
831
962
  }
832
963
  const body = await readJsonBody(req, 64 * 1024);
964
+
965
+ if (body.action === 'save_llm') {
966
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
967
+ const providerId = String(body.providerId || 'openai').trim().toLowerCase().slice(0, 64);
968
+ const preset = getProviderPreset(providerId);
969
+ const protocol = body.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
970
+ const baseUrl = String(body.baseUrl || preset?.defaultBaseUrl || 'https://api.openai.com/v1').trim().slice(0, 512);
971
+ const model = String(body.model || preset?.defaultModel || 'gpt-4.1-mini').trim().slice(0, 128);
972
+ const updated = saveSettings(prev => {
973
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
974
+ const prevProf = prevProviders[providerId] || {};
975
+ const typedKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
976
+ const finalKey = body.clearKey
977
+ ? ''
978
+ : (typedKey ? typedKey.slice(0, 512) : (prevProf.apiKey ?? ((prev.providerId === providerId ? prev.apiKey : '') || '')));
979
+ const mergedModels = Array.isArray(body.models) && body.models.length
980
+ ? [...new Set([model, ...body.models.map(m => String(m).trim()).filter(Boolean)])].slice(0, 60)
981
+ : [...new Set([model, ...(prevProf.models || preset?.models || [])].filter(Boolean))].slice(0, 60);
982
+ prevProviders[providerId] = {
983
+ label: String(body.label || prevProf.label || preset?.label || providerId).slice(0, 80),
984
+ protocol,
985
+ baseUrl,
986
+ ...(finalKey ? { apiKey: finalKey } : {}),
987
+ model,
988
+ enabled: true,
989
+ models: mergedModels,
990
+ };
991
+ const next = {
992
+ ...prev,
993
+ mode: 'builtin',
994
+ providerId,
995
+ provider: protocol,
996
+ baseUrl,
997
+ model,
998
+ providers: prevProviders,
999
+ };
1000
+ if (finalKey) next.apiKey = finalKey;
1001
+ else delete next.apiKey;
1002
+ return next;
1003
+ });
1004
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1005
+ return;
1006
+ }
1007
+
1008
+ if (body.action === 'switch_model') {
1009
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1010
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1011
+ const model = String(body.model || '').trim().slice(0, 128);
1012
+ if (!model) throw new DocumentError('请选择要切换的模型。', 400);
1013
+ const preset = getProviderPreset(providerId);
1014
+ const updated = saveSettings(prev => {
1015
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1016
+ const prof = prevProviders[providerId] || {};
1017
+ const protocol = prof.protocol || preset?.protocol || 'openai';
1018
+ const baseUrl = prof.baseUrl || preset?.defaultBaseUrl || prev.baseUrl || 'https://api.openai.com/v1';
1019
+ prevProviders[providerId] = {
1020
+ ...prof,
1021
+ protocol,
1022
+ baseUrl,
1023
+ model,
1024
+ models: [...new Set([model, ...(prof.models || preset?.models || [])])].slice(0, 60),
1025
+ };
1026
+ const next = {
1027
+ ...prev,
1028
+ mode: 'builtin',
1029
+ providerId,
1030
+ provider: protocol,
1031
+ baseUrl,
1032
+ model,
1033
+ providers: prevProviders,
1034
+ };
1035
+ if (prof.apiKey) next.apiKey = prof.apiKey;
1036
+ return next;
1037
+ });
1038
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1039
+ return;
1040
+ }
1041
+
1042
+ if (body.action === 'fetch_models') {
1043
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1044
+ const preset = getProviderPreset(providerId);
1045
+ const curSettings = readSettings();
1046
+ const savedProf = curSettings.providers?.[providerId] || {};
1047
+ const protocol = body.protocol === 'anthropic' || savedProf.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
1048
+ const baseUrl = String(body.baseUrl || savedProf.baseUrl || preset?.defaultBaseUrl || '').trim();
1049
+ const apiKey = String(body.apiKey || '').trim() || savedProf.apiKey || (curSettings.providerId === providerId ? curSettings.apiKey : '') || '';
1050
+ const models = await fetchProviderModels({ protocol, baseUrl, apiKey, fetchImpl });
1051
+ if (saveSettings && models.length) {
1052
+ saveSettings(prev => {
1053
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1054
+ const prof = prevProviders[providerId] || {};
1055
+ prevProviders[providerId] = {
1056
+ ...prof,
1057
+ protocol,
1058
+ baseUrl: prof.baseUrl || baseUrl,
1059
+ models,
1060
+ };
1061
+ return { ...prev, providers: prevProviders };
1062
+ });
1063
+ }
1064
+ sendJson(200, { ok: true, models });
1065
+ return;
1066
+ }
1067
+
1068
+ if (body.action === 'save_acp') {
1069
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1070
+ const cmd = String(body.command || '').trim().slice(0, 2048);
1071
+ if (!cmd) throw new DocumentError('ACP 命令不能为空。', 400);
1072
+ const argsList = Array.isArray(body.args)
1073
+ ? body.args.map(a => String(a).trim()).filter(Boolean).slice(0, 32)
1074
+ : String(body.args || '').split(/\s+/).map(a => a.trim()).filter(Boolean).slice(0, 32);
1075
+ const updated = saveSettings(prev => ({
1076
+ ...prev,
1077
+ command: cmd,
1078
+ args: argsList,
1079
+ }));
1080
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1081
+ return;
1082
+ }
1083
+
833
1084
  if (body.action === 'save_memory') {
834
1085
  const text = saveWorkspaceMemory(stateDir, body.text || '');
835
1086
  const latest = readAgentDebugConfig(stateDir).config;
836
- sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, workspace), telemetry: computeSampleTelemetry(latest) });
1087
+ sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, rootWs), telemetry: computeSampleTelemetry(latest) });
837
1088
  return;
838
1089
  }
839
1090
  if (body.action === 'save_config') {
@@ -880,13 +1131,132 @@ export function createAgentHandler({
880
1131
  });
881
1132
  return;
882
1133
  }
1134
+ if (body.action === 'save_mcp') {
1135
+ try {
1136
+ const saved = saveMcpServer(targetWorkspace, {
1137
+ name: body.name,
1138
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1139
+ config: body.config || body,
1140
+ });
1141
+ sendJson(200, { ok: true, server: saved, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
1142
+ return;
1143
+ } catch (err) {
1144
+ throw new DocumentError(err.message || '保存 MCP 服务失败。', 400);
1145
+ }
1146
+ }
1147
+ if (body.action === 'toggle_mcp') {
1148
+ try {
1149
+ const saved = toggleMcpServer(targetWorkspace, {
1150
+ name: body.name,
1151
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1152
+ enabled: body.enabled !== false,
1153
+ });
1154
+ sendJson(200, { ok: true, server: saved, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
1155
+ return;
1156
+ } catch (err) {
1157
+ throw new DocumentError(err.message || '切换 MCP 状态失败。', 400);
1158
+ }
1159
+ }
1160
+ if (body.action === 'delete_mcp') {
1161
+ const deleted = deleteMcpServer(targetWorkspace, {
1162
+ name: body.name,
1163
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1164
+ });
1165
+ sendJson(200, { ok: true, deleted, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
1166
+ return;
1167
+ }
1168
+ if (body.action === 'import_mcp_json') {
1169
+ try {
1170
+ const imported = importMcpJson(targetWorkspace, {
1171
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1172
+ jsonText: body.jsonText ?? body.json ?? '',
1173
+ });
1174
+ sendJson(200, { ok: true, imported, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
1175
+ return;
1176
+ } catch (err) {
1177
+ throw new DocumentError(err.message || '导入 MCP JSON 失败。', 400);
1178
+ }
1179
+ }
1180
+ if (body.action === 'test_mcp') {
1181
+ let targetConfig = body.config;
1182
+ if (!targetConfig && body.name) {
1183
+ const found = listMcpServers(targetWorkspace, { pluginMcp, includeSecrets: true }).find(s => s.name === body.name);
1184
+ if (!found) throw new DocumentError(`未找到 MCP 服务:${body.name}`, 404);
1185
+ targetConfig = found.config;
1186
+ }
1187
+ const report = await testMcpServer(targetWorkspace, targetConfig || {});
1188
+ sendJson(200, report);
1189
+ return;
1190
+ }
1191
+
1192
+ if (body.action === 'save_skill') {
1193
+ try {
1194
+ const saved = saveSkill(targetWorkspace, {
1195
+ slug: body.slug,
1196
+ name: body.name,
1197
+ description: body.description,
1198
+ tags: Array.isArray(body.tags) ? body.tags : [],
1199
+ body: body.body,
1200
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1201
+ });
1202
+ sendJson(200, { ok: true, skill: saved, skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }) });
1203
+ return;
1204
+ } catch (err) {
1205
+ throw new DocumentError(err.message || '保存技能失败。', 400);
1206
+ }
1207
+ }
1208
+ if (body.action === 'delete_skill') {
1209
+ const deleted = deleteSkill(targetWorkspace, {
1210
+ slug: body.slug,
1211
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1212
+ });
1213
+ sendJson(200, { ok: true, deleted, skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }) });
1214
+ return;
1215
+ }
1216
+
1217
+ if (body.action === 'save_command') {
1218
+ try {
1219
+ const saved = saveCommand(targetWorkspace, {
1220
+ name: body.name,
1221
+ description: body.description,
1222
+ prompt: body.prompt,
1223
+ skill: body.skill,
1224
+ workflow: body.workflow,
1225
+ persona: body.persona,
1226
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1227
+ });
1228
+ sendJson(200, { ok: true, command: saved, commands: listCommands(targetWorkspace, { pluginDirs }) });
1229
+ return;
1230
+ } catch (err) {
1231
+ throw new DocumentError(err.message || '保存斜杠命令失败。', 400);
1232
+ }
1233
+ }
1234
+ if (body.action === 'delete_command') {
1235
+ const deleted = deleteCommand(targetWorkspace, {
1236
+ name: body.name,
1237
+ scope: body.scope === 'global' ? 'global' : 'workspace',
1238
+ });
1239
+ sendJson(200, { ok: true, deleted, commands: listCommands(targetWorkspace, { pluginDirs }) });
1240
+ return;
1241
+ }
1242
+
1243
+ if (body.action === 'delete_persona') {
1244
+ const id = String(body.id || '').trim();
1245
+ if (!id || ['architect', 'coder', 'qa', 'auditor'].includes(id)) {
1246
+ throw new DocumentError('内置人设不可删除,仅可删除自定义人设。', 400);
1247
+ }
1248
+ const saved = saveAgentDebugConfig(stateDir, { personas: { [id]: null } }, { scope: 'global' });
1249
+ sendJson(200, { ok: true, config: saved.config });
1250
+ return;
1251
+ }
1252
+
883
1253
  throw new DocumentError('不支持的配置操作。', 400);
884
1254
  }
885
1255
 
886
1256
  throw new DocumentError('配置接口仅支持 GET / POST。', 405);
887
1257
  }
888
1258
 
889
- async function handle(req, res, targetWorkspace = workspace) {
1259
+ async function handle(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
890
1260
  const host = req.headers.host || '';
891
1261
  if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
892
1262
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
@@ -933,6 +1303,7 @@ export function createAgentHandler({
933
1303
  session = ensureMemorySession(targetWorkspace, meta, input.session, {
934
1304
  title: input.title,
935
1305
  persona: input.persona,
1306
+ engine: input.engine === 'acp' ? 'acp' : 'builtin',
936
1307
  mode: input.mode,
937
1308
  execMode: input.execMode,
938
1309
  });
@@ -964,11 +1335,11 @@ export function createAgentHandler({
964
1335
  };
965
1336
  }
966
1337
 
1338
+ const sessionWantsAcp = session.engine === 'acp' || input.engine === 'acp';
967
1339
  const useBuiltin = input.action === 'answer'
968
1340
  || input.action === 'command_decision'
969
- || (input.action === 'prompt' && (
970
- input.engine === 'builtin' ||
971
- ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
1341
+ || (input.action === 'prompt' && !sessionWantsAcp && (
1342
+ input.engine === 'builtin' || meta.activeEngine === 'builtin'
972
1343
  ));
973
1344
 
974
1345
  session.running = true;
@@ -1020,8 +1391,17 @@ export function createAgentHandler({
1020
1391
  session.pendingCommand = null;
1021
1392
  }
1022
1393
 
1023
- const activeMode = input.mode || session.mode || 'general';
1024
- const activePersona = input.persona || session.persona || meta.defaultPersona;
1394
+ const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
1395
+ const slashExpanded = input.action === 'prompt'
1396
+ ? expandSlashCommand(session.workspace, input.text, { pluginDirs })
1397
+ : null;
1398
+ const effectiveInput = slashExpanded
1399
+ ? { ...input, text: slashExpanded.prompt }
1400
+ : input;
1401
+ const activeMode = (slashExpanded?.workflow && ['general', 'design', 'qa', 'audit'].includes(slashExpanded.workflow))
1402
+ ? slashExpanded.workflow
1403
+ : (input.mode || session.mode || 'general');
1404
+ const activePersona = slashExpanded?.persona || input.persona || session.persona || meta.defaultPersona;
1025
1405
  const activeExecMode = input.execMode || session.execMode || 'act';
1026
1406
  let thinkingBuf = '';
1027
1407
  let textBuf = '';
@@ -1043,13 +1423,19 @@ export function createAgentHandler({
1043
1423
 
1044
1424
  const result = await runVerticalAgent({
1045
1425
  workspace: session.workspace,
1046
- rootWorkspace: workspace,
1426
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
1047
1427
  documentRoot: meta.rtInfo.documentRoot || session.workspace,
1048
1428
  stateDir: meta.rtInfo.stateDir,
1049
1429
  workspaceService,
1050
1430
  events,
1051
1431
  config: meta.settings,
1052
1432
  debugConfig: meta.debugConfig,
1433
+ pluginMeta: {
1434
+ pluginDirs,
1435
+ pluginMcp: meta.rtInfo.pluginMcp || [],
1436
+ pluginPersonas: meta.rtInfo.pluginPersonas || [],
1437
+ },
1438
+ preloadedSkill: slashExpanded?.skill || '',
1053
1439
  history: session.history,
1054
1440
  canvasBaseline: session.canvasBaseline,
1055
1441
  activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
@@ -1059,7 +1445,7 @@ export function createAgentHandler({
1059
1445
  resumeCommandResult,
1060
1446
  sessionCommandAutoAllow: session.commandAutoAllow,
1061
1447
  drainSteering: () => session.steeringQueue.splice(0),
1062
- input,
1448
+ input: effectiveInput,
1063
1449
  mode: activeMode,
1064
1450
  execMode: activeExecMode,
1065
1451
  persona: activePersona,