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.
@@ -0,0 +1,250 @@
1
+ /**
2
+ * 本机工作区中心(Workspace Hub):
3
+ * - 最近打开工作区持久化(~/.clado/recent-workspaces.json)
4
+ * - 本机目录安全浏览(供网页端选择/切换/新建项目目录)
5
+ * - 浏览器端一键新建初始画布文档(告别“必须先用外部客户端建文档”的死胡同)
6
+ */
7
+
8
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { basename, dirname, join, resolve } from 'node:path';
11
+ import { DocumentError, scanDirectory, workspacePath } from '../workspace/documents.js';
12
+ import { contextFor, initialize } from '../workspace/storage.js';
13
+ import { userTemplatePaths } from '../skill/templates.js';
14
+
15
+ const MAX_RECENTS = 16;
16
+
17
+ function recentsFilePath() {
18
+ const dir = userTemplatePaths().state;
19
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
20
+ return join(dir, 'recent-workspaces.json');
21
+ }
22
+
23
+ function countMarkdownInWorkspace(wsDir) {
24
+ try {
25
+ const cladoDoc = join(wsDir, '.clado', 'doc');
26
+ if (existsSync(cladoDoc) && lstatSync(cladoDoc).isDirectory()) {
27
+ return scanDirectory(cladoDoc).documents.length;
28
+ }
29
+ return scanDirectory(wsDir).documents.length;
30
+ } catch {
31
+ return 0;
32
+ }
33
+ }
34
+
35
+ export function readRecentWorkspaces() {
36
+ const file = recentsFilePath();
37
+ if (!existsSync(file)) return [];
38
+ try {
39
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
40
+ if (!Array.isArray(raw)) return [];
41
+ const out = [];
42
+ for (const item of raw) {
43
+ if (!item || typeof item.path !== 'string') continue;
44
+ const p = resolve(item.path);
45
+ try {
46
+ if (!existsSync(p) || !statSync(p).isDirectory()) continue;
47
+ out.push({
48
+ path: p,
49
+ name: basename(p) || p,
50
+ hasClado: existsSync(join(p, '.clado')),
51
+ isGit: existsSync(join(p, '.git')),
52
+ documents: countMarkdownInWorkspace(p),
53
+ lastOpenedAt: item.lastOpenedAt || new Date().toISOString(),
54
+ });
55
+ } catch {}
56
+ }
57
+ return out.slice(0, MAX_RECENTS);
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+
63
+ export function recordRecentWorkspace(wsPath) {
64
+ if (!wsPath) return [];
65
+ const clean = resolve(wsPath);
66
+ const existing = readRecentWorkspaces().filter(item => item.path !== clean);
67
+ const next = [
68
+ {
69
+ path: clean,
70
+ name: basename(clean) || clean,
71
+ lastOpenedAt: new Date().toISOString(),
72
+ },
73
+ ...existing,
74
+ ].slice(0, MAX_RECENTS);
75
+ try {
76
+ writeFileSync(recentsFilePath(), JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
77
+ } catch {}
78
+ return readRecentWorkspaces();
79
+ }
80
+
81
+ export function browseLocalFolders(dirInput = '') {
82
+ const home = homedir();
83
+ const target = dirInput ? resolve(String(dirInput)) : home;
84
+ if (!existsSync(target)) {
85
+ throw new DocumentError(`目录不存在:${target}`, 404);
86
+ }
87
+ const st = statSync(target);
88
+ const currentDir = st.isDirectory() ? target : dirname(target);
89
+ const parent = dirname(currentDir);
90
+ const parentDir = parent !== currentDir ? parent : '';
91
+
92
+ const entries = [];
93
+ let rawEntries = [];
94
+ try {
95
+ rawEntries = readdirSync(currentDir, { withFileTypes: true });
96
+ } catch {
97
+ throw new DocumentError(`无权读取目录:${currentDir}`, 403);
98
+ }
99
+
100
+ for (const entry of rawEntries) {
101
+ if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '$RECYCLE.BIN') {
102
+ continue;
103
+ }
104
+ const full = join(currentDir, entry.name);
105
+ try {
106
+ const info = lstatSync(full);
107
+ if (!info.isDirectory() || info.isSymbolicLink()) continue;
108
+ let mdCount = 0;
109
+ const hasClado = existsSync(join(full, '.clado'));
110
+ const isGit = existsSync(join(full, '.git'));
111
+ if (hasClado && existsSync(join(full, '.clado', 'doc'))) {
112
+ try {
113
+ mdCount = readdirSync(join(full, '.clado', 'doc')).filter(n => /\.mdc?$/i.test(n)).length;
114
+ } catch {}
115
+ } else {
116
+ try {
117
+ mdCount = readdirSync(full).filter(n => /\.mdc?$/i.test(n) && !/^readme\.md$/i.test(n)).length;
118
+ } catch {}
119
+ }
120
+ entries.push({
121
+ name: entry.name,
122
+ path: full,
123
+ hasClado,
124
+ isGit,
125
+ mdCount,
126
+ });
127
+ } catch {}
128
+ }
129
+
130
+ entries.sort((a, b) => {
131
+ const scoreA = (a.hasClado ? 4 : 0) + (a.isGit ? 2 : 0) + (a.mdCount > 0 ? 1 : 0);
132
+ const scoreB = (b.hasClado ? 4 : 0) + (b.isGit ? 2 : 0) + (b.mdCount > 0 ? 1 : 0);
133
+ if (scoreA !== scoreB) return scoreB - scoreA;
134
+ return a.name.localeCompare(b.name, 'zh-CN');
135
+ });
136
+
137
+ return {
138
+ currentDir,
139
+ parentDir,
140
+ homeDir: home,
141
+ hasClado: existsSync(join(currentDir, '.clado')),
142
+ isGit: existsSync(join(currentDir, '.git')),
143
+ entries: entries.slice(0, 120),
144
+ };
145
+ }
146
+
147
+ export function resolveWorkspaceSelection(targetPath, { createIfMissing = false, project = true } = {}) {
148
+ if (!targetPath || typeof targetPath !== 'string') {
149
+ throw new DocumentError('请提供有效的工作区目录路径。', 400);
150
+ }
151
+ const clean = resolve(targetPath.trim());
152
+ if (!existsSync(clean)) {
153
+ if (!createIfMissing) throw new DocumentError(`目录不存在:${clean}(可勾选新建目录)`, 404);
154
+ mkdirSync(clean, { recursive: true });
155
+ }
156
+ const st = statSync(clean);
157
+ if (!st.isDirectory()) throw new DocumentError('工作区路径必须是文件夹。', 400);
158
+
159
+ let workspace = clean;
160
+ let root = clean;
161
+ if (basename(clean) === 'doc' && basename(dirname(clean)) === '.clado') {
162
+ workspace = dirname(dirname(clean));
163
+ root = clean;
164
+ } else if (
165
+ project
166
+ || existsSync(join(clean, '.clado/workspace.json'))
167
+ || existsSync(join(clean, 'package.json'))
168
+ || existsSync(join(clean, '.git'))
169
+ || !scanDirectory(clean).documents.some(d => !/^readme\.md$/i.test(d.file))
170
+ ) {
171
+ const ctx = contextFor(clean, clean);
172
+ workspace = clean;
173
+ root = ctx.documents;
174
+ }
175
+ const rootCtx = contextFor(workspace, workspace, root);
176
+ initialize(rootCtx);
177
+ return { workspace, root, rootCtx };
178
+ }
179
+
180
+ export function createStarterCanvas(docRoot, { title = '系统架构概览', file = '' } = {}) {
181
+ const cleanTitle = String(title || '系统架构概览').trim().slice(0, 80) || '系统架构概览';
182
+ const slug = String(file || '')
183
+ .trim()
184
+ .replace(/\.mdc?$/i, '')
185
+ .replace(/[\\/:*?"<>|]/g, '-')
186
+ .slice(0, 64);
187
+
188
+ let fileName = (slug || 'overview') + '.md';
189
+ if (!file && existsSync(join(docRoot, fileName))) {
190
+ let idx = 2;
191
+ while (existsSync(join(docRoot, `canvas-${idx}.md`)) && idx < 99) idx++;
192
+ fileName = `canvas-${idx}.md`;
193
+ }
194
+
195
+ const fullPath = workspacePath(docRoot, fileName, true);
196
+ if (existsSync(fullPath)) {
197
+ throw new DocumentError(`画布文件已存在:${fileName}`, 409);
198
+ }
199
+ if (!existsSync(dirname(fullPath))) mkdirSync(dirname(fullPath), { recursive: true });
200
+
201
+ const body = [
202
+ `# ${cleanTitle}`,
203
+ '',
204
+ '在此梳理核心模块职责、接口契约与关键状态流转 [#核心入口|blue](#entry-contract),下游衔接 [协作与演进边界](#协作与演进边界)。',
205
+ '',
206
+ '## 核心入口契约 {#entry-contract}',
207
+ '',
208
+ '- 明确输入校验、幂等边界与状态推进条件',
209
+ '- 可在右下角直接让 Clado Agent 扫描当前代码库自动补全卡片',
210
+ '',
211
+ '# 协作与演进边界',
212
+ '',
213
+ '记录模块间调用约定、异常兜底与待确认事项。',
214
+ '',
215
+ '## 待办与验收点',
216
+ '',
217
+ '- 选中任意卡片或长按贴上便签,一键发给当前分身深化设计',
218
+ '',
219
+ ].join('\n');
220
+
221
+ writeFileSync(fullPath, body, 'utf8');
222
+ return { file: fileName, title: cleanTitle };
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
+ }
@@ -15,6 +15,15 @@ import { installCatalogPlugin, listInstalledWorkspacePlugins, loadRegistryIndex,
15
15
  import { createCapabilityRegistry } from './plugin-capabilities.js';
16
16
  import { createPluginSettings } from './plugin-settings.js';
17
17
  import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
18
+ import {
19
+ browseLocalFolders,
20
+ createStarterCanvas,
21
+ deleteCanvasDocument,
22
+ readRecentWorkspaces,
23
+ recordRecentWorkspace,
24
+ renameCanvasDocument,
25
+ resolveWorkspaceSelection,
26
+ } from './workspace-hub.js';
18
27
  import { z } from 'zod/v4';
19
28
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
20
29
  const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
@@ -178,6 +187,42 @@ export function createWorkspaceHandler(directory, options = {}) {
178
187
  }
179
188
  throw new DocumentError('画布对象接口仅支持 GET 或 POST。', 405);
180
189
  }
190
+ if (url.pathname === '/library/fs-workspaces' && options.workspaceHub) {
191
+ if (req.method === 'GET') {
192
+ json(res, 200, options.workspaceHub.inspect(url.searchParams.get('dir') || ''));
193
+ return true;
194
+ }
195
+ if (req.method === 'POST') {
196
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
197
+ throw new DocumentError('工作区切换只接受同源页面请求。', 403);
198
+ }
199
+ const chunks = []; let size = 0;
200
+ for await (const chunk of req) {
201
+ size += chunk.length;
202
+ if (size > 65536) throw new DocumentError('请求体过大。', 413);
203
+ chunks.push(chunk);
204
+ }
205
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
206
+ if (body?.action === 'create_canvas') {
207
+ const target = resolveTarget(url);
208
+ json(res, 201, options.workspaceHub.createCanvas(target, body));
209
+ return true;
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
+ }
221
+ json(res, 200, options.workspaceHub.switchWorkspace(body?.path, body));
222
+ return true;
223
+ }
224
+ throw new DocumentError('工作区浏览接口仅支持 GET 或 POST。', 405);
225
+ }
181
226
  if (options.capabilities && url.pathname === '/library/plugin-bridge') {
182
227
  const view = z.uuid().safeParse(url.searchParams.get('viewId'));
183
228
  if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
@@ -210,7 +255,7 @@ export function createWorkspaceHandler(directory, options = {}) {
210
255
  const workspaces = options.listWorkspaces
211
256
  ? options.listWorkspaces()
212
257
  : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
213
- json(res, 200, { scope: options.scopeName || basename(root), workspaces }); return true;
258
+ json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
214
259
  }
215
260
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
216
261
  const target = resolveTarget(url);
@@ -239,7 +284,7 @@ export function createWorkspaceHandler(directory, options = {}) {
239
284
  const pluginCatalog = target.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || target.inactivePlugins?.() || [];
240
285
  const pluginPreferenceKey = createHash('sha256').update(target.workspace).digest('hex');
241
286
  const pluginSettings = Object.fromEntries(Object.entries(target.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
242
- body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'cards',theme:options.theme || 'light',entry:target.id ? '' : (options.entry || ''),workspaceId:target.id,workspaceName:basename(target.workspace),workspacePath:target.workspace,multiWorkspace:!!options.listWorkspaces,selection:!!options.publishSelection,plugins:!!target.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!target.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
287
+ body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'cards',theme:options.theme || 'light',entry:target.id ? '' : (options.entry || ''),workspaceId:target.id,workspaceName:basename(target.workspace),workspacePath:target.workspace,multiWorkspace:!!options.listWorkspaces,canSwitchWorkspace:!!options.workspaceHub,hubMode:Boolean(options.hubMode?.()),mcpUrl:options.mcpUrl?.() || '',selection:!!options.publishSelection,plugins:!!target.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!target.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
243
288
  }
244
289
  send(res,200,types[name.split('.').pop()],body); return true;
245
290
  }
@@ -271,16 +316,18 @@ export function createWorkspaceHandler(directory, options = {}) {
271
316
  }
272
317
  };
273
318
  }
274
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
319
+ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
275
320
  const path = resolve(input);
276
321
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
277
322
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
278
323
  let root = statSync(path).isDirectory() ? path : dirname(path), workspace = root;
324
+ let activeHubMode = Boolean(hubMode);
279
325
  if (basename(root) === 'doc' && basename(dirname(root)) === '.clado') workspace = dirname(dirname(root));
280
326
  else if (project || existsSync(join(root, '.clado/workspace.json')) || existsSync(join(root, 'package.json')) || existsSync(join(root, '.git')) || (statSync(path).isDirectory() && !scanDirectory(root).documents.some(d => !/^readme\.md$/i.test(d.file)))) {
281
327
  const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
282
328
  }
283
- const rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
329
+ let rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
330
+ if (!activeHubMode) recordRecentWorkspace(workspace);
284
331
  const runtimes = new Map();
285
332
  function runtimeFor(ctx) {
286
333
  const existing = runtimes.get(ctx.workspace);
@@ -305,7 +352,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
305
352
  runtimes.set(ctx.workspace, rt);
306
353
  return rt;
307
354
  }
308
- const rootRuntime = runtimeFor(rootCtx);
355
+ let rootRuntime = runtimeFor(rootCtx);
309
356
  function resolveWorkspaceParam(param) {
310
357
  if (!param) return rootRuntime;
311
358
  if (typeof param !== 'string' || isAbsolute(param) || param.includes('\\') || param.includes('\0') ||
@@ -344,7 +391,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
344
391
  return current?.expiresAt > Date.now() ? current : null;
345
392
  };
346
393
  const events = createWorkspaceEvents();
347
- const baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
394
+ let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
348
395
  const mcpService = async (tool, input = {}) => {
349
396
  const result = await baseService(tool, input);
350
397
  try {
@@ -353,18 +400,28 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
353
400
  } catch {}
354
401
  return result;
355
402
  };
356
- mcpService.diagnostics = baseService.diagnostics;
403
+ mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
404
+ const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
357
405
  const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
358
- workspace, mcpUrl: () => 'http://127.0.0.1:' + server.address().port + '/mcp',
406
+ workspace: () => workspace,
407
+ mcpUrl: liveMcpUrl,
359
408
  workspaceService: mcpService,
360
409
  events,
361
410
  resolveSettings: () => rootRuntime.settings.agentLaunch(),
411
+ saveSettings: updater => {
412
+ const cur = rootRuntime.settings.read('clado.agent');
413
+ const next = updater(cur.value);
414
+ return rootRuntime.settings.save('clado.agent', next, cur.value).value;
415
+ },
362
416
  resolveRuntimeInfo: targetWorkspace => {
363
417
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
364
418
  return {
365
419
  stateDir: rt.ctx.state,
366
420
  documentRoot: rt.root,
367
421
  pluginDescriptors: rt.plugins?.descriptor.plugins || [],
422
+ pluginDirs: rt.plugins?.pluginDirs || [],
423
+ pluginMcp: rt.plugins?.pluginMcp || [],
424
+ pluginPersonas: rt.plugins?.pluginPersonas || [],
368
425
  };
369
426
  },
370
427
  ...(agentName === 'acp' && { resolveLaunch: () => {
@@ -396,6 +453,9 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
396
453
  const removed = removeWorkspacePlugin(rt.ctx, id);
397
454
  if (rt.plugins) {
398
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);
399
459
  rt.grants.delete(removed.id);
400
460
  rt.providers = rt.providers.filter(p => p.pluginId !== removed.id);
401
461
  }
@@ -448,14 +508,72 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
448
508
  return deleted;
449
509
  },
450
510
  };
511
+ const workspaceHub = {
512
+ inspect(dir) {
513
+ return {
514
+ currentWorkspace: workspace,
515
+ currentName: basename(workspace),
516
+ hubMode: activeHubMode,
517
+ recentWorkspaces: readRecentWorkspaces(),
518
+ ...browseLocalFolders(dir || workspace),
519
+ };
520
+ },
521
+ switchWorkspace(targetPath, opts = {}) {
522
+ const next = resolveWorkspaceSelection(targetPath, {
523
+ createIfMissing: Boolean(opts.createIfMissing),
524
+ project: true,
525
+ });
526
+ if (opts.initStarterCanvas && scanDirectory(next.root).documents.length === 0) {
527
+ createStarterCanvas(next.root, { title: basename(next.workspace) + ' 架构概览' });
528
+ }
529
+ workspace = next.workspace;
530
+ root = next.root;
531
+ rootCtx = next.rootCtx;
532
+ activeHubMode = false;
533
+ runtimes.clear();
534
+ rootRuntime = runtimeFor(rootCtx);
535
+ baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
536
+ const recents = recordRecentWorkspace(workspace);
537
+ events.emit(workspace, 'workspace.updated', { action: 'switched', workspace });
538
+ return {
539
+ ok: true,
540
+ workspace,
541
+ name: basename(workspace),
542
+ documents: scanDirectory(root).documents.length,
543
+ recentWorkspaces: recents,
544
+ };
545
+ },
546
+ createCanvas(target, opts = {}) {
547
+ const created = createStarterCanvas(target.root, {
548
+ title: opts.title,
549
+ file: opts.file,
550
+ });
551
+ activeHubMode = false;
552
+ events.emit(target.workspace, 'doc.updated', { file: created.file, action: 'create', label: '新建画布 ' + created.title });
553
+ events.emit(target.workspace, 'workspace.updated', { action: 'create_canvas', file: created.file });
554
+ return { ok: true, ...created };
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
+ },
566
+ };
451
567
  const handle = createWorkspaceHandler(root,{
452
568
  entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
453
569
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
454
- agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,
570
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
571
+ mcpUrl:liveMcpUrl,
572
+ hubMode:() => activeHubMode,
455
573
  resolveWorkspace:resolveWorkspaceParam,
456
574
  listWorkspaces:() => discoverWorkspaces(workspace, root),
457
- scopeName:basename(workspace),
458
- inactivePlugins:rootRuntime.inactivePlugins,
575
+ scopeName:() => basename(workspace),
576
+ inactivePlugins:() => rootRuntime.inactivePlugins(),
459
577
  });
460
578
  const mcp = createMcpHandler(mcpService, capabilities.invoke);
461
579
  const server = createServer(async (req,res) => {