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.
@@ -15,6 +15,13 @@ 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
+ readRecentWorkspaces,
22
+ recordRecentWorkspace,
23
+ resolveWorkspaceSelection,
24
+ } from './workspace-hub.js';
18
25
  import { z } from 'zod/v4';
19
26
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
20
27
  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 +185,32 @@ export function createWorkspaceHandler(directory, options = {}) {
178
185
  }
179
186
  throw new DocumentError('画布对象接口仅支持 GET 或 POST。', 405);
180
187
  }
188
+ if (url.pathname === '/library/fs-workspaces' && options.workspaceHub) {
189
+ if (req.method === 'GET') {
190
+ json(res, 200, options.workspaceHub.inspect(url.searchParams.get('dir') || ''));
191
+ return true;
192
+ }
193
+ if (req.method === 'POST') {
194
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
195
+ throw new DocumentError('工作区切换只接受同源页面请求。', 403);
196
+ }
197
+ const chunks = []; let size = 0;
198
+ for await (const chunk of req) {
199
+ size += chunk.length;
200
+ if (size > 65536) throw new DocumentError('请求体过大。', 413);
201
+ chunks.push(chunk);
202
+ }
203
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
204
+ if (body?.action === 'create_canvas') {
205
+ const target = resolveTarget(url);
206
+ json(res, 201, options.workspaceHub.createCanvas(target, body));
207
+ return true;
208
+ }
209
+ json(res, 200, options.workspaceHub.switchWorkspace(body?.path, body));
210
+ return true;
211
+ }
212
+ throw new DocumentError('工作区浏览接口仅支持 GET 或 POST。', 405);
213
+ }
181
214
  if (options.capabilities && url.pathname === '/library/plugin-bridge') {
182
215
  const view = z.uuid().safeParse(url.searchParams.get('viewId'));
183
216
  if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
@@ -210,7 +243,7 @@ export function createWorkspaceHandler(directory, options = {}) {
210
243
  const workspaces = options.listWorkspaces
211
244
  ? options.listWorkspaces()
212
245
  : [{ 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;
246
+ json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
214
247
  }
215
248
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
216
249
  const target = resolveTarget(url);
@@ -239,7 +272,7 @@ export function createWorkspaceHandler(directory, options = {}) {
239
272
  const pluginCatalog = target.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || target.inactivePlugins?.() || [];
240
273
  const pluginPreferenceKey = createHash('sha256').update(target.workspace).digest('hex');
241
274
  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">');
275
+ 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
276
  }
244
277
  send(res,200,types[name.split('.').pop()],body); return true;
245
278
  }
@@ -271,16 +304,18 @@ export function createWorkspaceHandler(directory, options = {}) {
271
304
  }
272
305
  };
273
306
  }
274
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
307
+ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
275
308
  const path = resolve(input);
276
309
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
277
310
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
278
311
  let root = statSync(path).isDirectory() ? path : dirname(path), workspace = root;
312
+ let activeHubMode = Boolean(hubMode);
279
313
  if (basename(root) === 'doc' && basename(dirname(root)) === '.clado') workspace = dirname(dirname(root));
280
314
  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
315
  const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
282
316
  }
283
- const rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
317
+ let rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
318
+ if (!activeHubMode) recordRecentWorkspace(workspace);
284
319
  const runtimes = new Map();
285
320
  function runtimeFor(ctx) {
286
321
  const existing = runtimes.get(ctx.workspace);
@@ -305,7 +340,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
305
340
  runtimes.set(ctx.workspace, rt);
306
341
  return rt;
307
342
  }
308
- const rootRuntime = runtimeFor(rootCtx);
343
+ let rootRuntime = runtimeFor(rootCtx);
309
344
  function resolveWorkspaceParam(param) {
310
345
  if (!param) return rootRuntime;
311
346
  if (typeof param !== 'string' || isAbsolute(param) || param.includes('\\') || param.includes('\0') ||
@@ -344,7 +379,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
344
379
  return current?.expiresAt > Date.now() ? current : null;
345
380
  };
346
381
  const events = createWorkspaceEvents();
347
- const baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
382
+ let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
348
383
  const mcpService = async (tool, input = {}) => {
349
384
  const result = await baseService(tool, input);
350
385
  try {
@@ -353,12 +388,19 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
353
388
  } catch {}
354
389
  return result;
355
390
  };
356
- mcpService.diagnostics = baseService.diagnostics;
391
+ mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
392
+ const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
357
393
  const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
358
- workspace, mcpUrl: () => 'http://127.0.0.1:' + server.address().port + '/mcp',
394
+ workspace: () => workspace,
395
+ mcpUrl: liveMcpUrl,
359
396
  workspaceService: mcpService,
360
397
  events,
361
398
  resolveSettings: () => rootRuntime.settings.agentLaunch(),
399
+ saveSettings: updater => {
400
+ const cur = rootRuntime.settings.read('clado.agent');
401
+ const next = updater(cur.value);
402
+ return rootRuntime.settings.save('clado.agent', next, cur.value).value;
403
+ },
362
404
  resolveRuntimeInfo: targetWorkspace => {
363
405
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
364
406
  return {
@@ -448,14 +490,62 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
448
490
  return deleted;
449
491
  },
450
492
  };
493
+ const workspaceHub = {
494
+ inspect(dir) {
495
+ return {
496
+ currentWorkspace: workspace,
497
+ currentName: basename(workspace),
498
+ hubMode: activeHubMode,
499
+ recentWorkspaces: readRecentWorkspaces(),
500
+ ...browseLocalFolders(dir || workspace),
501
+ };
502
+ },
503
+ switchWorkspace(targetPath, opts = {}) {
504
+ const next = resolveWorkspaceSelection(targetPath, {
505
+ createIfMissing: Boolean(opts.createIfMissing),
506
+ project: true,
507
+ });
508
+ if (opts.initStarterCanvas && scanDirectory(next.root).documents.length === 0) {
509
+ createStarterCanvas(next.root, { title: basename(next.workspace) + ' 架构概览' });
510
+ }
511
+ workspace = next.workspace;
512
+ root = next.root;
513
+ rootCtx = next.rootCtx;
514
+ activeHubMode = false;
515
+ runtimes.clear();
516
+ rootRuntime = runtimeFor(rootCtx);
517
+ baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
518
+ const recents = recordRecentWorkspace(workspace);
519
+ events.emit(workspace, 'workspace.updated', { action: 'switched', workspace });
520
+ return {
521
+ ok: true,
522
+ workspace,
523
+ name: basename(workspace),
524
+ documents: scanDirectory(root).documents.length,
525
+ recentWorkspaces: recents,
526
+ };
527
+ },
528
+ createCanvas(target, opts = {}) {
529
+ const created = createStarterCanvas(target.root, {
530
+ title: opts.title,
531
+ file: opts.file,
532
+ });
533
+ activeHubMode = false;
534
+ events.emit(target.workspace, 'doc.updated', { file: created.file, action: 'create', label: '新建画布 ' + created.title });
535
+ events.emit(target.workspace, 'workspace.updated', { action: 'create_canvas', file: created.file });
536
+ return { ok: true, ...created };
537
+ },
538
+ };
451
539
  const handle = createWorkspaceHandler(root,{
452
540
  entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
453
541
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
454
- agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,
542
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
543
+ mcpUrl:liveMcpUrl,
544
+ hubMode:() => activeHubMode,
455
545
  resolveWorkspace:resolveWorkspaceParam,
456
546
  listWorkspaces:() => discoverWorkspaces(workspace, root),
457
- scopeName:basename(workspace),
458
- inactivePlugins:rootRuntime.inactivePlugins,
547
+ scopeName:() => basename(workspace),
548
+ inactivePlugins:() => rootRuntime.inactivePlugins(),
459
549
  });
460
550
  const mcp = createMcpHandler(mcpService, capabilities.invoke);
461
551
  const server = createServer(async (req,res) => {