cladogram 0.5.5-beta.8 → 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.
@@ -39,12 +39,22 @@ import {
39
39
  saveSessionRecord,
40
40
  } from '../agent/sessions.js';
41
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';
42
52
 
43
53
  const idleMs = 15 * 60_000;
44
54
  const turnMs = 5 * 60_000;
45
55
  const MAX_PEER_HOPS = 8;
46
56
  const sessionId = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
47
- 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}$/);
48
58
  const execModeSchema = z.enum(['plan', 'act']);
49
59
  const canvasObjectItemSchema = z.strictObject({
50
60
  id: z.string().min(1).max(120),
@@ -661,6 +671,20 @@ export function createAgentHandler({
661
671
  if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
662
672
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
663
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
+ }
664
688
  res.writeHead(200, {
665
689
  'content-type': 'application/json; charset=utf-8',
666
690
  'cache-control': 'no-store',
@@ -675,8 +699,11 @@ export function createAgentHandler({
675
699
  model: meta.model,
676
700
  llm: meta.llm,
677
701
  mcpUrl: mcpUrl(),
702
+ mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
703
+ skills: listSkills(targetWorkspace, { pluginDirs }),
704
+ commands: listCommands(targetWorkspace, { pluginDirs }),
678
705
  defaultPersona: meta.defaultPersona,
679
- personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
706
+ personas: [...mergedPersonas.values()],
680
707
  personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
681
708
  executors: publicExecutorList(meta.executors),
682
709
  runs: listRunRecords(meta.rtInfo.stateDir, 10),
@@ -734,7 +761,7 @@ export function createAgentHandler({
734
761
  if (act === 'create') {
735
762
  const newId = safeSessionId(body.id) || randomUUID();
736
763
  const isAcpSub = body.engine === 'acp';
737
- const persona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : meta.defaultPersona;
764
+ const persona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : meta.defaultPersona;
738
765
  const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
739
766
  const defaultTitle = isAcpSub ? 'ACP 子代理' : (resolved.name || '新会话');
740
767
  const title = String(body.title || defaultTitle).trim().slice(0, 48);
@@ -777,7 +804,7 @@ export function createAgentHandler({
777
804
 
778
805
  if (act === 'set_persona') {
779
806
  const targetId = safeSessionId(body.id);
780
- const nextPersona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : 'architect';
807
+ const nextPersona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : 'architect';
781
808
  if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
782
809
  const nextPal = paletteForPersona(nextPersona);
783
810
  const mem = sessions.get(targetId);
@@ -787,7 +814,7 @@ export function createAgentHandler({
787
814
  }
788
815
  const existing = loadSessionRecord(stateDir, targetId);
789
816
  const updated = saveSessionRecord(stateDir, {
790
- ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona).name }),
817
+ ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona, '', meta.debugConfig.personas).name }),
791
818
  id: targetId,
792
819
  persona: nextPersona,
793
820
  pal: nextPal,
@@ -908,11 +935,19 @@ export function createAgentHandler({
908
935
  return sample.telemetry;
909
936
  };
910
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
+
911
942
  if (req.method === 'GET') {
912
943
  const memory = readWorkspaceMemory(stateDir, rootWs);
913
944
  sendJson(200, {
914
945
  llm: meta.llm,
915
946
  mcpUrl: mcpUrl(),
947
+ mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
948
+ skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }),
949
+ commands: listCommands(targetWorkspace, { pluginDirs }),
950
+ pluginPersonas,
916
951
  config: meta.debugConfig,
917
952
  hasWorkspaceOverride: meta.hasWorkspaceOverride,
918
953
  memory,
@@ -1096,6 +1131,125 @@ export function createAgentHandler({
1096
1131
  });
1097
1132
  return;
1098
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
+
1099
1253
  throw new DocumentError('不支持的配置操作。', 400);
1100
1254
  }
1101
1255
 
@@ -1237,8 +1391,17 @@ export function createAgentHandler({
1237
1391
  session.pendingCommand = null;
1238
1392
  }
1239
1393
 
1240
- const activeMode = input.mode || session.mode || 'general';
1241
- 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;
1242
1405
  const activeExecMode = input.execMode || session.execMode || 'act';
1243
1406
  let thinkingBuf = '';
1244
1407
  let textBuf = '';
@@ -1267,6 +1430,12 @@ export function createAgentHandler({
1267
1430
  events,
1268
1431
  config: meta.settings,
1269
1432
  debugConfig: meta.debugConfig,
1433
+ pluginMeta: {
1434
+ pluginDirs,
1435
+ pluginMcp: meta.rtInfo.pluginMcp || [],
1436
+ pluginPersonas: meta.rtInfo.pluginPersonas || [],
1437
+ },
1438
+ preloadedSkill: slashExpanded?.skill || '',
1270
1439
  history: session.history,
1271
1440
  canvasBaseline: session.canvasBaseline,
1272
1441
  activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
@@ -1276,7 +1445,7 @@ export function createAgentHandler({
1276
1445
  resumeCommandResult,
1277
1446
  sessionCommandAutoAllow: session.commandAutoAllow,
1278
1447
  drainSteering: () => session.steeringQueue.splice(0),
1279
- input,
1448
+ input: effectiveInput,
1280
1449
  mode: activeMode,
1281
1450
  execMode: activeExecMode,
1282
1451
  persona: activePersona,
@@ -124,6 +124,8 @@
124
124
  switchWorkspace: id => { location.href = workspaceUrl(id); },
125
125
  openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openWorkspacePicker() : null,
126
126
  createCanvas: config.canSwitchWorkspace && !offline ? () => createCanvasFlow() : null,
127
+ renameCanvas: config.canSwitchWorkspace && !offline ? doc => renameCanvasFlow(doc) : null,
128
+ deleteCanvas: config.canSwitchWorkspace && !offline ? doc => deleteCanvasFlow(doc) : null,
127
129
  refresh: () => scan(true),
128
130
  back: () => {
129
131
  if (modalLocked()) return;
@@ -168,6 +170,50 @@
168
170
  }
169
171
  }
170
172
 
173
+ async function renameCanvasFlow(doc) {
174
+ if (!config.canSwitchWorkspace || offline || !doc?.file) return;
175
+ const nextName = window.prompt('重命名画布文件(保留 .md):', doc.file);
176
+ if (!nextName || !nextName.trim() || nextName.trim() === doc.file) return;
177
+ try {
178
+ const res = await fetch(withWorkspace('/library/fs-workspaces'), {
179
+ method: 'POST',
180
+ headers: { 'content-type': 'application/json' },
181
+ body: JSON.stringify({ action: 'rename_canvas', oldFile: doc.file, newFile: nextName.trim() }),
182
+ });
183
+ const data = await res.json();
184
+ if (!res.ok) throw new Error(data.error || '重命名画布失败');
185
+ if (selected === doc.file) {
186
+ selected = '';
187
+ pendingOpen = data.file;
188
+ }
189
+ await scan(true);
190
+ } catch (err) {
191
+ directory.showMessage('重命名画布失败', err.message || '请稍后重试');
192
+ }
193
+ }
194
+
195
+ async function deleteCanvasFlow(doc) {
196
+ if (!config.canSwitchWorkspace || offline || !doc?.file) return;
197
+ if (!window.confirm(`确定要永久删除画布「${doc.title || doc.file}」(${doc.file}) 吗?`)) return;
198
+ try {
199
+ const res = await fetch(withWorkspace('/library/fs-workspaces'), {
200
+ method: 'POST',
201
+ headers: { 'content-type': 'application/json' },
202
+ body: JSON.stringify({ action: 'delete_canvas', file: doc.file }),
203
+ });
204
+ const data = await res.json();
205
+ if (!res.ok) throw new Error(data.error || '删除画布失败');
206
+ if (selected === doc.file) {
207
+ selected = '';
208
+ version = '';
209
+ saveView();
210
+ }
211
+ await scan(true);
212
+ } catch (err) {
213
+ directory.showMessage('删除画布失败', err.message || '请稍后重试');
214
+ }
215
+ }
216
+
171
217
  async function applyWorkspaceSwitch(targetPath, { createIfMissing = false, initStarterCanvas = false } = {}) {
172
218
  if (!targetPath || !targetPath.trim()) return;
173
219
  const res = await fetch('/library/fs-workspaces', {
@@ -23,6 +23,22 @@ const permission = z.enum([
23
23
  ...PLUGIN_SLOTS.map(slot => 'ui.mount:' + slot),
24
24
  ...PLUGIN_FIELDS.map(field => 'canvas.' + field + '.read'),
25
25
  ]);
26
+ const pluginMcpEntry = z.strictObject({
27
+ name: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/),
28
+ type: z.enum(['stdio', 'http', 'streamable-http']).optional(),
29
+ command: z.string().trim().min(1).max(200).optional(),
30
+ args: z.array(z.string().max(200)).max(32).optional(),
31
+ env: z.record(z.string(), z.string()).optional(),
32
+ url: z.string().trim().min(1).max(400).optional(),
33
+ headers: z.record(z.string(), z.string()).optional(),
34
+ enabled: z.boolean().optional(),
35
+ });
36
+ const pluginPersonaEntry = z.strictObject({
37
+ id: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/),
38
+ name: z.string().trim().min(1).max(40),
39
+ prompt: z.string().max(4000).default(''),
40
+ initContext: z.string().max(2000).default(''),
41
+ });
26
42
  const manifest = z.strictObject({
27
43
  manifestVersion: z.literal(1),
28
44
  id: pluginId,
@@ -33,15 +49,19 @@ const manifest = z.strictObject({
33
49
  }, '需要有效 SemVer'),
34
50
  engines: z.strictObject({ clado: z.string().min(1).max(200) }),
35
51
  protocols: z.array(z.string().regex(/^\d+\.\d+$/)).min(1).max(16),
36
- entrypoints: z.strictObject({ ui: z.strictObject({ path: z.string().max(240).regex(uiPath) }) }),
52
+ entrypoints: z.strictObject({ ui: z.strictObject({ path: z.string().max(240).regex(uiPath) }).optional() }).optional(),
37
53
  permissions: z.array(z.union([permission, capabilityPermission])).max(64).default([]),
38
54
  configuration: pluginConfiguration.optional(),
39
55
  contributes: z.strictObject({
40
56
  mounts: z.array(z.strictObject({
41
57
  id: mountId, slot: z.enum(PLUGIN_SLOTS),
42
- })).min(1).max(8),
58
+ })).max(8).default([]),
43
59
  capabilities: z.array(capabilityDefinition).max(16).default([]),
44
60
  executors: z.array(executorSchema).max(8).default([]),
61
+ mcp: z.array(pluginMcpEntry).max(16).default([]),
62
+ personas: z.array(pluginPersonaEntry).max(12).default([]),
63
+ skills: z.boolean().optional(),
64
+ commands: z.boolean().optional(),
45
65
  events: z.tuple([]).optional(),
46
66
  }),
47
67
  });
@@ -110,12 +130,27 @@ function readManifest(root) {
110
130
  throw new Error(`插件需要 Clado ${data.engines.clado},当前版本为 ${VERSION}。`);
111
131
  }
112
132
  if (!data.protocols.includes(PLUGIN_PROTOCOL)) throw new Error(`插件需要声明协议 ${PLUGIN_PROTOCOL}。`);
113
- const mounts = data.contributes.mounts;
133
+ const mounts = data.contributes.mounts || [];
114
134
  if (new Set(mounts.map(mount => mount.id)).size !== mounts.length) throw new Error('挂载 ID 重复。');
115
135
  for (const { slot } of mounts) {
116
136
  if (!data.permissions.includes('ui.mount:' + slot)) throw new Error(`缺少挂载权限 ui.mount:${slot}。`);
117
137
  }
118
- readPackageFile(root, data.entrypoints.ui.path.split('/'), 2 * 1024 * 1024);
138
+ const hasUi = Boolean(data.entrypoints?.ui?.path);
139
+ const hasAgentBundle = Boolean(
140
+ data.contributes.executors?.length
141
+ || data.contributes.mcp?.length
142
+ || data.contributes.personas?.length
143
+ || data.contributes.skills
144
+ || data.contributes.commands
145
+ || existsSync(join(root, 'skills'))
146
+ || existsSync(join(root, 'commands'))
147
+ );
148
+ if (hasUi) {
149
+ if (!mounts.length) throw new Error('声明了 UI 入口的插件至少需要一个挂载点(contributes.mounts)。');
150
+ readPackageFile(root, data.entrypoints.ui.path.split('/'), 2 * 1024 * 1024);
151
+ } else if (!hasAgentBundle) {
152
+ throw new Error('插件需要提供 UI 入口或至少声明一项能力(skills / commands / mcp / personas / executors)。');
153
+ }
119
154
  return { data, capabilities: compileCapabilities(data.id, mounts, data.contributes.capabilities),
120
155
  configuration: compileConfiguration(data.configuration) };
121
156
  }
@@ -127,8 +162,13 @@ export function installWorkspacePlugin(ctx, files, runtime) {
127
162
  for (const file of files) {
128
163
  if (typeof file?.path !== 'string' || typeof file.data !== 'string' || file.path.length > 240) fail('插件文件参数无效。');
129
164
  const parts = file.path.split('/');
130
- if (!parts.every(part => segment.test(part)) ||
131
- (file.path !== 'clado-plugin.json' && (parts[0] !== 'ui' || !contentTypes.has(extname(file.path).toLowerCase())))) fail('插件包仅接受清单和 ui 目录中的资源。');
165
+ const ext = extname(file.path).toLowerCase();
166
+ const isManifest = file.path === 'clado-plugin.json';
167
+ const isUiAsset = parts[0] === 'ui' && contentTypes.has(ext);
168
+ const isBundleDoc = (parts[0] === 'skills' || parts[0] === 'commands') && (ext === '.md' || ext === '.json' || ext === '.txt');
169
+ if (!parts.every(part => segment.test(part)) || (!isManifest && !isUiAsset && !isBundleDoc)) {
170
+ fail('插件包仅接受清单、ui 静态资源以及 skills / commands 文本文件。');
171
+ }
132
172
  if (parsed.has(file.path)) fail('插件包中有重复的文件路径。');
133
173
  const data = Buffer.from(file.data, 'base64');
134
174
  if (data.toString('base64') !== file.data) fail('插件文件编码无效。');
@@ -178,16 +218,28 @@ export function loadWorkspacePlugins(state) {
178
218
  if (error.code !== 'ENOENT') warnings.push({ directory: '.clado/plugins', message: error.message });
179
219
  }
180
220
  const candidates = new Map();
221
+ const pluginDirs = [];
222
+ const pluginMcp = [];
223
+ const pluginPersonas = [];
181
224
  function register(root, { data, capabilities: declared, configuration }) {
182
225
  configurations.set(data.id, configuration);
183
226
  capabilities.push(...declared);
227
+ pluginDirs.push({ id: data.id, dir: root });
228
+ for (const m of data.contributes.mcp || []) {
229
+ pluginMcp.push({ ...m, pluginId: data.id });
230
+ }
231
+ for (const p of data.contributes.personas || []) {
232
+ pluginPersonas.push({ ...p, pluginId: data.id });
233
+ }
184
234
  const key = randomUUID();
185
235
  packages.set(key, root);
186
236
  plugins.push({
187
237
  id: data.id, name: data.name, version: data.version,
188
- entry: ASSETS + key + '/' + data.entrypoints.ui.path,
189
- permissions: data.permissions, mounts: data.contributes.mounts, capabilities: declared.map(item => item.descriptor),
238
+ ...(data.entrypoints?.ui?.path ? { entry: ASSETS + key + '/' + data.entrypoints.ui.path } : {}),
239
+ permissions: data.permissions, mounts: data.contributes.mounts || [], capabilities: declared.map(item => item.descriptor),
190
240
  ...(data.contributes.executors?.length ? { executors: data.contributes.executors } : {}),
241
+ ...(data.contributes.mcp?.length ? { mcp: data.contributes.mcp.map(m => m.name) } : {}),
242
+ ...(data.contributes.personas?.length ? { personas: data.contributes.personas.map(p => p.id) } : {}),
191
243
  });
192
244
  }
193
245
  for (const entry of entries) {
@@ -232,7 +284,7 @@ export function loadWorkspacePlugins(state) {
232
284
  });
233
285
  res.end(req.method === 'HEAD' ? undefined : body);
234
286
  }
235
- return { descriptor, warnings, serveAsset, hasAsset: key => packages.has(key), capabilities, configurations, register };
287
+ return { descriptor, warnings, serveAsset, hasAsset: key => packages.has(key), capabilities, configurations, register, pluginDirs, pluginMcp, pluginPersonas };
236
288
  }
237
289
 
238
290
  export function inspectWorkspacePlugins(state) {
@@ -5,7 +5,7 @@
5
5
  * - 浏览器端一键新建初始画布文档(告别“必须先用外部客户端建文档”的死胡同)
6
6
  */
7
7
 
8
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
8
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
9
9
  import { homedir } from 'node:os';
10
10
  import { basename, dirname, join, resolve } from 'node:path';
11
11
  import { DocumentError, scanDirectory, workspacePath } from '../workspace/documents.js';
@@ -221,3 +221,30 @@ export function createStarterCanvas(docRoot, { title = '系统架构概览', fil
221
221
  writeFileSync(fullPath, body, 'utf8');
222
222
  return { file: fileName, title: cleanTitle };
223
223
  }
224
+
225
+ export function renameCanvasDocument(docRoot, oldFile, newFileInput) {
226
+ const cleanOld = String(oldFile || '').trim();
227
+ if (!cleanOld) throw new DocumentError('请提供原画布文件名。', 400);
228
+ const oldPath = workspacePath(docRoot, cleanOld, false);
229
+ if (!existsSync(oldPath)) throw new DocumentError(`找不到画布:${cleanOld}`, 404);
230
+
231
+ let cleanNew = String(newFileInput || '').trim().replace(/\\/g, '/').replace(/^\/+/, '');
232
+ if (!cleanNew) throw new DocumentError('新画布名称不能为空。', 400);
233
+ if (!/\.mdc?$/i.test(cleanNew)) cleanNew += '.md';
234
+
235
+ const newPath = workspacePath(docRoot, cleanNew, true);
236
+ if (oldPath === newPath) return { oldFile: cleanOld, file: cleanNew };
237
+ if (existsSync(newPath)) throw new DocumentError(`目标画布已存在:${cleanNew}`, 409);
238
+ if (!existsSync(dirname(newPath))) mkdirSync(dirname(newPath), { recursive: true });
239
+ renameSync(oldPath, newPath);
240
+ return { oldFile: cleanOld, file: cleanNew };
241
+ }
242
+
243
+ export function deleteCanvasDocument(docRoot, file) {
244
+ const cleanFile = String(file || '').trim();
245
+ if (!cleanFile) throw new DocumentError('请提供要删除的画布文件名。', 400);
246
+ const targetPath = workspacePath(docRoot, cleanFile, false);
247
+ if (!existsSync(targetPath)) throw new DocumentError(`找不到画布:${cleanFile}`, 404);
248
+ rmSync(targetPath, { force: true });
249
+ return { deleted: cleanFile };
250
+ }
@@ -18,8 +18,10 @@ import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
18
18
  import {
19
19
  browseLocalFolders,
20
20
  createStarterCanvas,
21
+ deleteCanvasDocument,
21
22
  readRecentWorkspaces,
22
23
  recordRecentWorkspace,
24
+ renameCanvasDocument,
23
25
  resolveWorkspaceSelection,
24
26
  } from './workspace-hub.js';
25
27
  import { z } from 'zod/v4';
@@ -206,6 +208,16 @@ export function createWorkspaceHandler(directory, options = {}) {
206
208
  json(res, 201, options.workspaceHub.createCanvas(target, body));
207
209
  return true;
208
210
  }
211
+ if (body?.action === 'rename_canvas') {
212
+ const target = resolveTarget(url);
213
+ json(res, 200, options.workspaceHub.renameCanvas(target, body));
214
+ return true;
215
+ }
216
+ if (body?.action === 'delete_canvas') {
217
+ const target = resolveTarget(url);
218
+ json(res, 200, options.workspaceHub.deleteCanvas(target, body));
219
+ return true;
220
+ }
209
221
  json(res, 200, options.workspaceHub.switchWorkspace(body?.path, body));
210
222
  return true;
211
223
  }
@@ -407,6 +419,9 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
407
419
  stateDir: rt.ctx.state,
408
420
  documentRoot: rt.root,
409
421
  pluginDescriptors: rt.plugins?.descriptor.plugins || [],
422
+ pluginDirs: rt.plugins?.pluginDirs || [],
423
+ pluginMcp: rt.plugins?.pluginMcp || [],
424
+ pluginPersonas: rt.plugins?.pluginPersonas || [],
410
425
  };
411
426
  },
412
427
  ...(agentName === 'acp' && { resolveLaunch: () => {
@@ -438,6 +453,9 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
438
453
  const removed = removeWorkspacePlugin(rt.ctx, id);
439
454
  if (rt.plugins) {
440
455
  rt.plugins.descriptor.plugins = rt.plugins.descriptor.plugins.filter(p => p.id !== removed.id);
456
+ rt.plugins.pluginDirs = (rt.plugins.pluginDirs || []).filter(p => p.id !== removed.id);
457
+ rt.plugins.pluginMcp = (rt.plugins.pluginMcp || []).filter(p => p.pluginId !== removed.id);
458
+ rt.plugins.pluginPersonas = (rt.plugins.pluginPersonas || []).filter(p => p.pluginId !== removed.id);
441
459
  rt.grants.delete(removed.id);
442
460
  rt.providers = rt.providers.filter(p => p.pluginId !== removed.id);
443
461
  }
@@ -535,6 +553,16 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
535
553
  events.emit(target.workspace, 'workspace.updated', { action: 'create_canvas', file: created.file });
536
554
  return { ok: true, ...created };
537
555
  },
556
+ renameCanvas(target, opts = {}) {
557
+ const renamed = renameCanvasDocument(target.root, opts.oldFile || opts.file, opts.newFile || opts.name);
558
+ events.emit(target.workspace, 'workspace.updated', { action: 'rename_canvas', oldFile: renamed.oldFile, file: renamed.file });
559
+ return { ok: true, ...renamed };
560
+ },
561
+ deleteCanvas(target, opts = {}) {
562
+ const removed = deleteCanvasDocument(target.root, opts.file);
563
+ events.emit(target.workspace, 'workspace.updated', { action: 'delete_canvas', file: removed.deleted });
564
+ return { ok: true, ...removed };
565
+ },
538
566
  };
539
567
  const handle = createWorkspaceHandler(root,{
540
568
  entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,