cladogram 0.5.5-beta.7 → 0.5.5-beta.8

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,
@@ -192,6 +199,7 @@ export function createAgentHandler({
192
199
  args = [],
193
200
  resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
194
201
  resolveSettings = null,
202
+ saveSettings = null,
195
203
  resolveRuntimeInfo = null,
196
204
  workspaceService = null,
197
205
  events = null,
@@ -205,6 +213,40 @@ export function createAgentHandler({
205
213
  return { ...launch, ...base };
206
214
  };
207
215
 
216
+ function buildLlmState(settings = {}) {
217
+ const creds = resolveProviderCredentials(settings);
218
+ const profiles = {};
219
+ for (const preset of PROVIDER_PRESETS) {
220
+ const raw = settings.providers?.[preset.id] || {};
221
+ const isLegacyMatch = !settings.providers && (settings.providerId || 'openai') === preset.id;
222
+ const key = raw.apiKey ?? (isLegacyMatch ? settings.apiKey : '');
223
+ profiles[preset.id] = {
224
+ label: raw.label || preset.label,
225
+ protocol: raw.protocol || preset.protocol,
226
+ baseUrl: raw.baseUrl || (isLegacyMatch ? settings.baseUrl : '') || preset.defaultBaseUrl,
227
+ model: raw.model || (isLegacyMatch ? settings.model : '') || preset.defaultModel,
228
+ models: Array.isArray(raw.models) && raw.models.length ? raw.models : preset.models,
229
+ hasApiKey: Boolean(String(key || '').trim()),
230
+ maskedKey: maskApiKey(key),
231
+ requiresKey: preset.requiresKey !== false,
232
+ };
233
+ }
234
+ return {
235
+ configured: creds.configured,
236
+ providerId: creds.providerId,
237
+ providerLabel: creds.providerLabel,
238
+ protocol: creds.provider,
239
+ baseUrl: creds.baseUrl,
240
+ model: creds.model,
241
+ hasApiKey: creds.hasApiKey,
242
+ presets: PROVIDER_PRESETS,
243
+ profiles,
244
+ quickModels: listConfiguredModels(settings),
245
+ acpCommand: settings.command || 'zcode-acp-server',
246
+ acpArgs: Array.isArray(settings.args) ? settings.args : [],
247
+ };
248
+ }
249
+
208
250
  function runningSessionIds(targetWorkspace) {
209
251
  const set = new Set();
210
252
  for (const s of sessions.values()) {
@@ -280,24 +322,26 @@ export function createAgentHandler({
280
322
  settings,
281
323
  pluginDescriptors: rtInfo.pluginDescriptors || [],
282
324
  });
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');
325
+ const llm = buildLlmState(settings);
326
+ const builtinConfigured = Boolean(llm.configured);
327
+ // Clado 产品定位为原生 Agent 优先:只要挂载了工作区设置(resolveSettings),主引擎默认恒为 builtin,
328
+ // 仅当显式强制设为 acp(或纯 ACP 单元测试未提供 resolveSettings)时才退回 acp。
329
+ const activeEngine = !resolveSettings
330
+ ? (builtinConfigured ? 'builtin' : 'acp')
331
+ : (settings.mode === 'acp' ? 'acp' : 'builtin');
291
332
  return {
292
333
  settings,
334
+ llm,
293
335
  debugConfig: debugBundle.config,
294
336
  hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
295
337
  rtInfo,
296
338
  executors,
297
339
  builtinConfigured,
298
340
  activeEngine,
299
- provider: creds.provider,
300
- model: creds.model,
341
+ provider: llm.protocol,
342
+ providerId: llm.providerId,
343
+ providerLabel: llm.providerLabel,
344
+ model: llm.model,
301
345
  defaultPersona: settings.persona || 'architect',
302
346
  };
303
347
  }
@@ -313,6 +357,7 @@ export function createAgentHandler({
313
357
  title: defaults.title || saved?.title || '',
314
358
  persona,
315
359
  pal: saved?.pal || paletteForPersona(persona),
360
+ engine: (defaults.engine || saved?.engine) === 'acp' ? 'acp' : 'builtin',
316
361
  mode: defaults.mode || saved?.mode || 'design',
317
362
  execMode: defaults.execMode || saved?.execMode || 'act',
318
363
  liveStatus: saved?.liveStatus || '',
@@ -376,7 +421,7 @@ export function createAgentHandler({
376
421
  const incoming = peerSession.incomingPeerMessages.splice(0);
377
422
  const result = await runVerticalAgent({
378
423
  workspace: targetWorkspace,
379
- rootWorkspace: workspace,
424
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
380
425
  documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
381
426
  stateDir: meta.rtInfo.stateDir,
382
427
  workspaceService,
@@ -611,7 +656,7 @@ export function createAgentHandler({
611
656
  };
612
657
  }
613
658
 
614
- function handleMeta(req, res, targetWorkspace = workspace) {
659
+ function handleMeta(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
615
660
  const host = req.headers.host || '';
616
661
  if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
617
662
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
@@ -624,8 +669,12 @@ export function createAgentHandler({
624
669
  res.end(JSON.stringify({
625
670
  engine: meta.activeEngine,
626
671
  provider: meta.provider,
672
+ providerId: meta.providerId,
673
+ providerLabel: meta.providerLabel,
627
674
  builtinConfigured: meta.builtinConfigured,
628
675
  model: meta.model,
676
+ llm: meta.llm,
677
+ mcpUrl: mcpUrl(),
629
678
  defaultPersona: meta.defaultPersona,
630
679
  personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
631
680
  personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
@@ -640,7 +689,7 @@ export function createAgentHandler({
640
689
  }));
641
690
  }
642
691
 
643
- function handleSessions(req, res, url, targetWorkspace = workspace) {
692
+ function handleSessions(req, res, url, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
644
693
  const host = req.headers.host || '';
645
694
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
646
695
  const meta = resolveMeta(targetWorkspace);
@@ -684,18 +733,21 @@ export function createAgentHandler({
684
733
 
685
734
  if (act === 'create') {
686
735
  const newId = safeSessionId(body.id) || randomUUID();
736
+ const isAcpSub = body.engine === 'acp';
687
737
  const persona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : meta.defaultPersona;
688
738
  const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
689
- const title = String(body.title || resolved.name || '新会话').trim().slice(0, 48);
739
+ const defaultTitle = isAcpSub ? 'ACP 子代理' : (resolved.name || '新会话');
740
+ const title = String(body.title || defaultTitle).trim().slice(0, 48);
690
741
  const saved = saveSessionRecord(stateDir, {
691
742
  id: newId,
692
743
  title,
693
744
  persona,
694
- pal: body.pal || resolved.pal || paletteForPersona(persona),
745
+ pal: body.pal || (isAcpSub ? 'cyan' : (resolved.pal || paletteForPersona(persona))),
746
+ engine: isAcpSub ? 'acp' : 'builtin',
695
747
  mode: ['general', 'design', 'qa', 'audit'].includes(body.mode) ? body.mode : 'design',
696
748
  execMode: body.execMode === 'plan' ? 'plan' : 'act',
697
749
  archived: false,
698
- liveStatus: '等待指令…',
750
+ liveStatus: isAcpSub ? 'ACP 外部子代理待命…' : '等待指令…',
699
751
  messages: [],
700
752
  uiMessages: [],
701
753
  });
@@ -705,6 +757,47 @@ export function createAgentHandler({
705
757
  return;
706
758
  }
707
759
 
760
+ if (act === 'rename') {
761
+ const targetId = safeSessionId(body.id);
762
+ const nextTitle = String(body.title || '').trim().slice(0, 48);
763
+ if (!targetId || !nextTitle) throw new DocumentError('缺少会话 id 或新名称。', 400);
764
+ const existing = loadSessionRecord(stateDir, targetId);
765
+ const mem = sessions.get(targetId);
766
+ if (mem) mem.title = nextTitle;
767
+ const updated = saveSessionRecord(stateDir, {
768
+ ...(existing || { id: targetId, persona: mem?.persona || meta.defaultPersona }),
769
+ id: targetId,
770
+ title: nextTitle,
771
+ touchActivity: false,
772
+ });
773
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
774
+ sendJson(200, { session: updated });
775
+ return;
776
+ }
777
+
778
+ if (act === 'set_persona') {
779
+ const targetId = safeSessionId(body.id);
780
+ const nextPersona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : 'architect';
781
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
782
+ const nextPal = paletteForPersona(nextPersona);
783
+ const mem = sessions.get(targetId);
784
+ if (mem) {
785
+ mem.persona = nextPersona;
786
+ mem.pal = nextPal;
787
+ }
788
+ const existing = loadSessionRecord(stateDir, targetId);
789
+ const updated = saveSessionRecord(stateDir, {
790
+ ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona).name }),
791
+ id: targetId,
792
+ persona: nextPersona,
793
+ pal: nextPal,
794
+ touchActivity: false,
795
+ });
796
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
797
+ sendJson(200, { session: updated });
798
+ return;
799
+ }
800
+
708
801
  if (act === 'archive' || act === 'unarchive') {
709
802
  const targetId = safeSessionId(body.id);
710
803
  if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
@@ -786,9 +879,10 @@ export function createAgentHandler({
786
879
  throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
787
880
  }
788
881
 
789
- async function handleConfig(req, res, targetWorkspace = workspace) {
882
+ async function handleConfig(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
790
883
  const host = req.headers.host || '';
791
884
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
885
+ const rootWs = typeof workspace === 'function' ? workspace() : workspace;
792
886
  const meta = resolveMeta(targetWorkspace);
793
887
  const stateDir = meta.rtInfo.stateDir;
794
888
  const sendJson = (status, data) => {
@@ -803,7 +897,7 @@ export function createAgentHandler({
803
897
  const computeSampleTelemetry = cfg => {
804
898
  const sample = buildSegmentedPromptContext({
805
899
  workspace: targetWorkspace,
806
- rootWorkspace: workspace,
900
+ rootWorkspace: rootWs,
807
901
  documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
808
902
  stateDir,
809
903
  debugConfig: cfg,
@@ -815,8 +909,10 @@ export function createAgentHandler({
815
909
  };
816
910
 
817
911
  if (req.method === 'GET') {
818
- const memory = readWorkspaceMemory(stateDir, workspace);
912
+ const memory = readWorkspaceMemory(stateDir, rootWs);
819
913
  sendJson(200, {
914
+ llm: meta.llm,
915
+ mcpUrl: mcpUrl(),
820
916
  config: meta.debugConfig,
821
917
  hasWorkspaceOverride: meta.hasWorkspaceOverride,
822
918
  memory,
@@ -830,10 +926,130 @@ export function createAgentHandler({
830
926
  throw new DocumentError('配置修改只接受本机同源页面请求。', 403);
831
927
  }
832
928
  const body = await readJsonBody(req, 64 * 1024);
929
+
930
+ if (body.action === 'save_llm') {
931
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
932
+ const providerId = String(body.providerId || 'openai').trim().toLowerCase().slice(0, 64);
933
+ const preset = getProviderPreset(providerId);
934
+ const protocol = body.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
935
+ const baseUrl = String(body.baseUrl || preset?.defaultBaseUrl || 'https://api.openai.com/v1').trim().slice(0, 512);
936
+ const model = String(body.model || preset?.defaultModel || 'gpt-4.1-mini').trim().slice(0, 128);
937
+ const updated = saveSettings(prev => {
938
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
939
+ const prevProf = prevProviders[providerId] || {};
940
+ const typedKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
941
+ const finalKey = body.clearKey
942
+ ? ''
943
+ : (typedKey ? typedKey.slice(0, 512) : (prevProf.apiKey ?? ((prev.providerId === providerId ? prev.apiKey : '') || '')));
944
+ const mergedModels = Array.isArray(body.models) && body.models.length
945
+ ? [...new Set([model, ...body.models.map(m => String(m).trim()).filter(Boolean)])].slice(0, 60)
946
+ : [...new Set([model, ...(prevProf.models || preset?.models || [])].filter(Boolean))].slice(0, 60);
947
+ prevProviders[providerId] = {
948
+ label: String(body.label || prevProf.label || preset?.label || providerId).slice(0, 80),
949
+ protocol,
950
+ baseUrl,
951
+ ...(finalKey ? { apiKey: finalKey } : {}),
952
+ model,
953
+ enabled: true,
954
+ models: mergedModels,
955
+ };
956
+ const next = {
957
+ ...prev,
958
+ mode: 'builtin',
959
+ providerId,
960
+ provider: protocol,
961
+ baseUrl,
962
+ model,
963
+ providers: prevProviders,
964
+ };
965
+ if (finalKey) next.apiKey = finalKey;
966
+ else delete next.apiKey;
967
+ return next;
968
+ });
969
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
970
+ return;
971
+ }
972
+
973
+ if (body.action === 'switch_model') {
974
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
975
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
976
+ const model = String(body.model || '').trim().slice(0, 128);
977
+ if (!model) throw new DocumentError('请选择要切换的模型。', 400);
978
+ const preset = getProviderPreset(providerId);
979
+ const updated = saveSettings(prev => {
980
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
981
+ const prof = prevProviders[providerId] || {};
982
+ const protocol = prof.protocol || preset?.protocol || 'openai';
983
+ const baseUrl = prof.baseUrl || preset?.defaultBaseUrl || prev.baseUrl || 'https://api.openai.com/v1';
984
+ prevProviders[providerId] = {
985
+ ...prof,
986
+ protocol,
987
+ baseUrl,
988
+ model,
989
+ models: [...new Set([model, ...(prof.models || preset?.models || [])])].slice(0, 60),
990
+ };
991
+ const next = {
992
+ ...prev,
993
+ mode: 'builtin',
994
+ providerId,
995
+ provider: protocol,
996
+ baseUrl,
997
+ model,
998
+ providers: prevProviders,
999
+ };
1000
+ if (prof.apiKey) next.apiKey = prof.apiKey;
1001
+ return next;
1002
+ });
1003
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1004
+ return;
1005
+ }
1006
+
1007
+ if (body.action === 'fetch_models') {
1008
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1009
+ const preset = getProviderPreset(providerId);
1010
+ const curSettings = readSettings();
1011
+ const savedProf = curSettings.providers?.[providerId] || {};
1012
+ const protocol = body.protocol === 'anthropic' || savedProf.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
1013
+ const baseUrl = String(body.baseUrl || savedProf.baseUrl || preset?.defaultBaseUrl || '').trim();
1014
+ const apiKey = String(body.apiKey || '').trim() || savedProf.apiKey || (curSettings.providerId === providerId ? curSettings.apiKey : '') || '';
1015
+ const models = await fetchProviderModels({ protocol, baseUrl, apiKey, fetchImpl });
1016
+ if (saveSettings && models.length) {
1017
+ saveSettings(prev => {
1018
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1019
+ const prof = prevProviders[providerId] || {};
1020
+ prevProviders[providerId] = {
1021
+ ...prof,
1022
+ protocol,
1023
+ baseUrl: prof.baseUrl || baseUrl,
1024
+ models,
1025
+ };
1026
+ return { ...prev, providers: prevProviders };
1027
+ });
1028
+ }
1029
+ sendJson(200, { ok: true, models });
1030
+ return;
1031
+ }
1032
+
1033
+ if (body.action === 'save_acp') {
1034
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1035
+ const cmd = String(body.command || '').trim().slice(0, 2048);
1036
+ if (!cmd) throw new DocumentError('ACP 命令不能为空。', 400);
1037
+ const argsList = Array.isArray(body.args)
1038
+ ? body.args.map(a => String(a).trim()).filter(Boolean).slice(0, 32)
1039
+ : String(body.args || '').split(/\s+/).map(a => a.trim()).filter(Boolean).slice(0, 32);
1040
+ const updated = saveSettings(prev => ({
1041
+ ...prev,
1042
+ command: cmd,
1043
+ args: argsList,
1044
+ }));
1045
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1046
+ return;
1047
+ }
1048
+
833
1049
  if (body.action === 'save_memory') {
834
1050
  const text = saveWorkspaceMemory(stateDir, body.text || '');
835
1051
  const latest = readAgentDebugConfig(stateDir).config;
836
- sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, workspace), telemetry: computeSampleTelemetry(latest) });
1052
+ sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, rootWs), telemetry: computeSampleTelemetry(latest) });
837
1053
  return;
838
1054
  }
839
1055
  if (body.action === 'save_config') {
@@ -886,7 +1102,7 @@ export function createAgentHandler({
886
1102
  throw new DocumentError('配置接口仅支持 GET / POST。', 405);
887
1103
  }
888
1104
 
889
- async function handle(req, res, targetWorkspace = workspace) {
1105
+ async function handle(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
890
1106
  const host = req.headers.host || '';
891
1107
  if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
892
1108
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
@@ -933,6 +1149,7 @@ export function createAgentHandler({
933
1149
  session = ensureMemorySession(targetWorkspace, meta, input.session, {
934
1150
  title: input.title,
935
1151
  persona: input.persona,
1152
+ engine: input.engine === 'acp' ? 'acp' : 'builtin',
936
1153
  mode: input.mode,
937
1154
  execMode: input.execMode,
938
1155
  });
@@ -964,11 +1181,11 @@ export function createAgentHandler({
964
1181
  };
965
1182
  }
966
1183
 
1184
+ const sessionWantsAcp = session.engine === 'acp' || input.engine === 'acp';
967
1185
  const useBuiltin = input.action === 'answer'
968
1186
  || input.action === 'command_decision'
969
- || (input.action === 'prompt' && (
970
- input.engine === 'builtin' ||
971
- ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
1187
+ || (input.action === 'prompt' && !sessionWantsAcp && (
1188
+ input.engine === 'builtin' || meta.activeEngine === 'builtin'
972
1189
  ));
973
1190
 
974
1191
  session.running = true;
@@ -1043,7 +1260,7 @@ export function createAgentHandler({
1043
1260
 
1044
1261
  const result = await runVerticalAgent({
1045
1262
  workspace: session.workspace,
1046
- rootWorkspace: workspace,
1263
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
1047
1264
  documentRoot: meta.rtInfo.documentRoot || session.workspace,
1048
1265
  stateDir: meta.rtInfo.stateDir,
1049
1266
  workspaceService,