cladogram 0.5.5-beta.6 → 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.
- package/bin/clado.js +33 -10
- package/docs/release.md +13 -0
- package/package.json +2 -2
- package/plugins/agent/index.js +2378 -461
- package/plugins/agent/style.css +1267 -422
- package/plugins/brand/index.js +211 -2
- package/plugins/directory/index.js +18 -1
- package/src/agent/context.js +430 -0
- package/src/agent/probe.js +58 -0
- package/src/agent/providers/index.js +197 -14
- package/src/agent/runtime.js +418 -28
- package/src/agent/sessions.js +239 -32
- package/src/html/canvas-ui.css +75 -11
- package/src/html/plugin-ui.css +378 -1
- package/src/server/agent.js +1049 -64
- package/src/server/assets/library-canvas.js +305 -1
- package/src/server/assets/library.js +564 -7
- package/src/server/plugin-registry.js +98 -0
- package/src/server/plugin-settings.js +29 -3
- package/src/server/workspace-hub.js +223 -0
- package/src/server/workspace.js +213 -18
- package/src/workspace/objects.js +125 -0
package/src/server/workspace.js
CHANGED
|
@@ -7,13 +7,21 @@ import { renderHtml } from '../html/page.js';
|
|
|
7
7
|
import { pluginMarkup, workspacePluginAssets } from '../html/plugin-assets.js';
|
|
8
8
|
import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
|
|
9
9
|
import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage.js';
|
|
10
|
+
import { deleteCanvasObject, listCanvasObjects, readCanvasObject, saveCanvasObject } from '../workspace/objects.js';
|
|
10
11
|
import { createWorkspaceService } from '../workspace/service.js';
|
|
11
12
|
import { createMcpHandler } from './mcp.js';
|
|
12
13
|
import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
|
|
13
|
-
import { loadRegistryIndex, removeWorkspacePlugin, searchRegistry } from './plugin-registry.js';
|
|
14
|
+
import { installCatalogPlugin, listInstalledWorkspacePlugins, loadRegistryIndex, removeWorkspacePlugin, searchRegistry } from './plugin-registry.js';
|
|
14
15
|
import { createCapabilityRegistry } from './plugin-capabilities.js';
|
|
15
16
|
import { createPluginSettings } from './plugin-settings.js';
|
|
16
17
|
import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
|
|
18
|
+
import {
|
|
19
|
+
browseLocalFolders,
|
|
20
|
+
createStarterCanvas,
|
|
21
|
+
readRecentWorkspaces,
|
|
22
|
+
recordRecentWorkspace,
|
|
23
|
+
resolveWorkspaceSelection,
|
|
24
|
+
} from './workspace-hub.js';
|
|
17
25
|
import { z } from 'zod/v4';
|
|
18
26
|
const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
|
|
19
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'};
|
|
@@ -71,7 +79,11 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
71
79
|
}
|
|
72
80
|
if (options.agent && url.pathname === '/library/agent/sessions') {
|
|
73
81
|
const target = resolveTarget(url);
|
|
74
|
-
options.agent.handleSessions(req, res, url, target.workspace); return true;
|
|
82
|
+
await options.agent.handleSessions(req, res, url, target.workspace); return true;
|
|
83
|
+
}
|
|
84
|
+
if (options.agent && url.pathname === '/library/agent/config' && options.agent.handleConfig) {
|
|
85
|
+
const target = resolveTarget(url);
|
|
86
|
+
await options.agent.handleConfig(req, res, target.workspace); return true;
|
|
75
87
|
}
|
|
76
88
|
if (options.agent && url.pathname === '/library/agent') {
|
|
77
89
|
const target = resolveTarget(url);
|
|
@@ -116,10 +128,88 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
116
128
|
return true;
|
|
117
129
|
}
|
|
118
130
|
if (url.pathname === '/library/plugin-registry' && options.readPluginRegistry) {
|
|
119
|
-
if (req.method !== 'GET') throw new DocumentError('插件市场索引仅支持 GET。', 405);
|
|
120
131
|
const target = resolveTarget(url);
|
|
121
|
-
|
|
122
|
-
|
|
132
|
+
if (req.method === 'GET') {
|
|
133
|
+
json(res, 200, await options.readPluginRegistry(target.workspace, url.searchParams.get('q') || ''));
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
if (req.method === 'POST' && options.installCatalog) {
|
|
137
|
+
if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
|
|
138
|
+
throw new DocumentError('插件市场安装只接受同源页面请求。', 403);
|
|
139
|
+
}
|
|
140
|
+
const chunks = []; let size = 0;
|
|
141
|
+
for await (const chunk of req) {
|
|
142
|
+
size += chunk.length;
|
|
143
|
+
if (size > 65536) throw new DocumentError('请求体过大。', 413);
|
|
144
|
+
chunks.push(chunk);
|
|
145
|
+
}
|
|
146
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
147
|
+
if (!body?.id || typeof body.id !== 'string') throw new DocumentError('缺少插件 id。', 400);
|
|
148
|
+
json(res, 201, await options.installCatalog(target.workspace, body.id));
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
throw new DocumentError('插件市场索引仅支持 GET 或 POST。', 405);
|
|
152
|
+
}
|
|
153
|
+
if (url.pathname === '/library/objects' && options.canvasObjects) {
|
|
154
|
+
const target = resolveTarget(url);
|
|
155
|
+
if (req.method === 'GET') {
|
|
156
|
+
const objId = url.searchParams.get('id');
|
|
157
|
+
if (objId) {
|
|
158
|
+
const obj = options.canvasObjects.read(target.workspace, objId);
|
|
159
|
+
if (!obj) throw new DocumentError('未找到该画布对象。', 404);
|
|
160
|
+
json(res, 200, { object: obj });
|
|
161
|
+
} else {
|
|
162
|
+
json(res, 200, { objects: options.canvasObjects.list(target.workspace) });
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
if (req.method === 'POST') {
|
|
167
|
+
if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
|
|
168
|
+
throw new DocumentError('画布组件操作只接受同源页面请求。', 403);
|
|
169
|
+
}
|
|
170
|
+
const chunks = []; let size = 0;
|
|
171
|
+
for await (const chunk of req) {
|
|
172
|
+
size += chunk.length;
|
|
173
|
+
if (size > 131072) throw new DocumentError('画布对象数据过大。', 413);
|
|
174
|
+
chunks.push(chunk);
|
|
175
|
+
}
|
|
176
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
177
|
+
if (body?.action === 'delete') {
|
|
178
|
+
const deleted = options.canvasObjects.remove(target.workspace, body.id);
|
|
179
|
+
json(res, 200, { deleted, id: body.id });
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
const saved = options.canvasObjects.save(target.workspace, body);
|
|
183
|
+
json(res, 200, { object: saved });
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
throw new DocumentError('画布对象接口仅支持 GET 或 POST。', 405);
|
|
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);
|
|
123
213
|
}
|
|
124
214
|
if (options.capabilities && url.pathname === '/library/plugin-bridge') {
|
|
125
215
|
const view = z.uuid().safeParse(url.searchParams.get('viewId'));
|
|
@@ -153,7 +243,7 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
153
243
|
const workspaces = options.listWorkspaces
|
|
154
244
|
? options.listWorkspaces()
|
|
155
245
|
: [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
|
|
156
|
-
json(res, 200, { scope: options.scopeName
|
|
246
|
+
json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
|
|
157
247
|
}
|
|
158
248
|
if (pluginsEnabled && url.pathname === '/library/plugins.json') {
|
|
159
249
|
const target = resolveTarget(url);
|
|
@@ -182,7 +272,7 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
182
272
|
const pluginCatalog = target.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || target.inactivePlugins?.() || [];
|
|
183
273
|
const pluginPreferenceKey = createHash('sha256').update(target.workspace).digest('hex');
|
|
184
274
|
const pluginSettings = Object.fromEntries(Object.entries(target.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
|
|
185
|
-
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">');
|
|
186
276
|
}
|
|
187
277
|
send(res,200,types[name.split('.').pop()],body); return true;
|
|
188
278
|
}
|
|
@@ -214,16 +304,18 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
214
304
|
}
|
|
215
305
|
};
|
|
216
306
|
}
|
|
217
|
-
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' } = {}) {
|
|
218
308
|
const path = resolve(input);
|
|
219
309
|
if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
|
|
220
310
|
if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
|
|
221
311
|
let root = statSync(path).isDirectory() ? path : dirname(path), workspace = root;
|
|
312
|
+
let activeHubMode = Boolean(hubMode);
|
|
222
313
|
if (basename(root) === 'doc' && basename(dirname(root)) === '.clado') workspace = dirname(dirname(root));
|
|
223
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)))) {
|
|
224
315
|
const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
|
|
225
316
|
}
|
|
226
|
-
|
|
317
|
+
let rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
|
|
318
|
+
if (!activeHubMode) recordRecentWorkspace(workspace);
|
|
227
319
|
const runtimes = new Map();
|
|
228
320
|
function runtimeFor(ctx) {
|
|
229
321
|
const existing = runtimes.get(ctx.workspace);
|
|
@@ -248,7 +340,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
|
|
|
248
340
|
runtimes.set(ctx.workspace, rt);
|
|
249
341
|
return rt;
|
|
250
342
|
}
|
|
251
|
-
|
|
343
|
+
let rootRuntime = runtimeFor(rootCtx);
|
|
252
344
|
function resolveWorkspaceParam(param) {
|
|
253
345
|
if (!param) return rootRuntime;
|
|
254
346
|
if (typeof param !== 'string' || isAbsolute(param) || param.includes('\\') || param.includes('\0') ||
|
|
@@ -287,7 +379,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
|
|
|
287
379
|
return current?.expiresAt > Date.now() ? current : null;
|
|
288
380
|
};
|
|
289
381
|
const events = createWorkspaceEvents();
|
|
290
|
-
|
|
382
|
+
let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
|
|
291
383
|
const mcpService = async (tool, input = {}) => {
|
|
292
384
|
const result = await baseService(tool, input);
|
|
293
385
|
try {
|
|
@@ -296,12 +388,19 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
|
|
|
296
388
|
} catch {}
|
|
297
389
|
return result;
|
|
298
390
|
};
|
|
299
|
-
mcpService.diagnostics = baseService.diagnostics;
|
|
391
|
+
mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
|
|
392
|
+
const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
|
|
300
393
|
const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
|
|
301
|
-
workspace
|
|
394
|
+
workspace: () => workspace,
|
|
395
|
+
mcpUrl: liveMcpUrl,
|
|
302
396
|
workspaceService: mcpService,
|
|
303
397
|
events,
|
|
304
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
|
+
},
|
|
305
404
|
resolveRuntimeInfo: targetWorkspace => {
|
|
306
405
|
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
307
406
|
return {
|
|
@@ -336,21 +435,117 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
|
|
|
336
435
|
}
|
|
337
436
|
function removePlugin(targetWorkspace, id) {
|
|
338
437
|
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
339
|
-
|
|
438
|
+
const removed = removeWorkspacePlugin(rt.ctx, id);
|
|
439
|
+
if (rt.plugins) {
|
|
440
|
+
rt.plugins.descriptor.plugins = rt.plugins.descriptor.plugins.filter(p => p.id !== removed.id);
|
|
441
|
+
rt.grants.delete(removed.id);
|
|
442
|
+
rt.providers = rt.providers.filter(p => p.pluginId !== removed.id);
|
|
443
|
+
}
|
|
444
|
+
return removed;
|
|
340
445
|
}
|
|
341
446
|
async function readPluginRegistry(targetWorkspace, query) {
|
|
342
447
|
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
343
448
|
const reg = await loadRegistryIndex({ stateDir: rt.ctx.state });
|
|
344
|
-
|
|
449
|
+
const installedIds = listInstalledWorkspacePlugins(rt.ctx.state).map(p => p.id);
|
|
450
|
+
return {
|
|
451
|
+
name: reg.name,
|
|
452
|
+
origin: reg.origin,
|
|
453
|
+
installedIds: [...new Set(installedIds)],
|
|
454
|
+
plugins: searchRegistry(reg, query),
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
async function installCatalog(targetWorkspace, id) {
|
|
458
|
+
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
459
|
+
const previous = rt.plugins?.capabilities.length || 0;
|
|
460
|
+
const installed = await installCatalogPlugin(rt.ctx, id, { runtime: rt.plugins });
|
|
461
|
+
if (rt.plugins) {
|
|
462
|
+
const descriptor = rt.plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
|
|
463
|
+
if (descriptor) {
|
|
464
|
+
rt.grants.set(installed.id, descriptor.permissions);
|
|
465
|
+
rt.providers.push(...rt.plugins.capabilities.slice(previous));
|
|
466
|
+
rt.settings.register(installed.id, rt.plugins.configurations.get(installed.id));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
return installed;
|
|
345
470
|
}
|
|
471
|
+
const canvasObjects = {
|
|
472
|
+
list(targetWorkspace) {
|
|
473
|
+
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
474
|
+
return listCanvasObjects(rt.ctx.state);
|
|
475
|
+
},
|
|
476
|
+
read(targetWorkspace, id) {
|
|
477
|
+
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
478
|
+
return readCanvasObject(rt.ctx.state, id);
|
|
479
|
+
},
|
|
480
|
+
save(targetWorkspace, payload) {
|
|
481
|
+
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
482
|
+
const saved = saveCanvasObject(rt.ctx.state, payload);
|
|
483
|
+
events.emit(rt.workspace, 'objects.updated', { action: 'save', object: saved });
|
|
484
|
+
return saved;
|
|
485
|
+
},
|
|
486
|
+
remove(targetWorkspace, id) {
|
|
487
|
+
const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
|
|
488
|
+
const deleted = deleteCanvasObject(rt.ctx.state, id);
|
|
489
|
+
if (deleted) events.emit(rt.workspace, 'objects.updated', { action: 'delete', id });
|
|
490
|
+
return deleted;
|
|
491
|
+
},
|
|
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
|
+
};
|
|
346
539
|
const handle = createWorkspaceHandler(root,{
|
|
347
540
|
entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
|
|
348
541
|
plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
|
|
349
|
-
agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,
|
|
542
|
+
agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
|
|
543
|
+
mcpUrl:liveMcpUrl,
|
|
544
|
+
hubMode:() => activeHubMode,
|
|
350
545
|
resolveWorkspace:resolveWorkspaceParam,
|
|
351
546
|
listWorkspaces:() => discoverWorkspaces(workspace, root),
|
|
352
|
-
scopeName:basename(workspace),
|
|
353
|
-
inactivePlugins:rootRuntime.inactivePlugins,
|
|
547
|
+
scopeName:() => basename(workspace),
|
|
548
|
+
inactivePlugins:() => rootRuntime.inactivePlugins(),
|
|
354
549
|
});
|
|
355
550
|
const mcp = createMcpHandler(mcpService, capabilities.invoke);
|
|
356
551
|
const server = createServer(async (req,res) => {
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 多实例画布对象持久化存储(`<子工作区>/.clado/objects/<id>.json`)。
|
|
3
|
+
*
|
|
4
|
+
* 支持:
|
|
5
|
+
* - 多张画布便签(sticky):各自拥有独立 ID、世界坐标 (x, y)、色卡(amber / mint / lavender)与文本内容;
|
|
6
|
+
* - 多实例视图+工具混合组件(如专注播放器 widget):支持容器级属性与子区域靶点状态(data.tracks 等);
|
|
7
|
+
* - AI 与前端画布可按 ID 单独或批量读取、创建、修改与删除。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
|
|
14
|
+
const SAFE_OBJECT_ID = /^[a-zA-Z0-9_-]{2,80}$/;
|
|
15
|
+
const ALLOWED_TINTS = new Set(['amber', 'mint', 'lavender', 'sky']);
|
|
16
|
+
const ALLOWED_KINDS = new Set(['sticky', 'music', 'widget']);
|
|
17
|
+
|
|
18
|
+
export function safeObjectId(id) {
|
|
19
|
+
const s = String(id || '').trim();
|
|
20
|
+
return SAFE_OBJECT_ID.test(s) ? s : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function objectsDir(stateDir) {
|
|
24
|
+
const dir = join(stateDir, 'objects');
|
|
25
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
26
|
+
return dir;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readCanvasObject(stateDir, id) {
|
|
30
|
+
const clean = safeObjectId(id);
|
|
31
|
+
if (!stateDir || !clean) return null;
|
|
32
|
+
const full = join(stateDir, 'objects', clean + '.json');
|
|
33
|
+
if (!existsSync(full)) return null;
|
|
34
|
+
try {
|
|
35
|
+
const data = JSON.parse(readFileSync(full, 'utf8'));
|
|
36
|
+
return data && data.id === clean ? data : null;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function listCanvasObjects(stateDir, limit = 120) {
|
|
43
|
+
if (!stateDir) return [];
|
|
44
|
+
const dir = join(stateDir, 'objects');
|
|
45
|
+
if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return [];
|
|
46
|
+
const items = [];
|
|
47
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
48
|
+
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
|
|
49
|
+
try {
|
|
50
|
+
const data = JSON.parse(readFileSync(join(dir, entry.name), 'utf8'));
|
|
51
|
+
if (data && safeObjectId(data.id)) items.push(data);
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
return items
|
|
55
|
+
.sort((a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || '')) || a.id.localeCompare(b.id))
|
|
56
|
+
.slice(0, limit);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function saveCanvasObject(stateDir, input = {}) {
|
|
60
|
+
if (!stateDir) throw new Error('缺少工作区状态目录。');
|
|
61
|
+
const existingCount = listCanvasObjects(stateDir, 200).length;
|
|
62
|
+
const rawKind = ALLOWED_KINDS.has(input.kind) ? input.kind : 'sticky';
|
|
63
|
+
const cleanId = safeObjectId(input.id) || `${rawKind === 'sticky' ? 'note' : rawKind}-${existingCount + 1}-${randomUUID().slice(0, 4)}`;
|
|
64
|
+
const prev = readCanvasObject(stateDir, cleanId);
|
|
65
|
+
const nowIso = new Date().toISOString();
|
|
66
|
+
|
|
67
|
+
const kind = ALLOWED_KINDS.has(input.kind) ? input.kind : (prev?.kind || 'sticky');
|
|
68
|
+
const pluginId = String(input.pluginId || prev?.pluginId || (kind === 'music' ? 'starter.lofi-player' : 'starter.sticky-notes')).slice(0, 80);
|
|
69
|
+
const x = Number.isFinite(Number(input.x)) ? Math.round(Number(input.x)) : (prev?.x ?? 180);
|
|
70
|
+
const y = Number.isFinite(Number(input.y)) ? Math.round(Number(input.y)) : (prev?.y ?? 140);
|
|
71
|
+
const width = Number.isFinite(Number(input.width))
|
|
72
|
+
? Math.min(560, Math.max(140, Math.round(Number(input.width))))
|
|
73
|
+
: (prev?.width ?? (kind === 'music' ? 320 : 184));
|
|
74
|
+
const tint = ALLOWED_TINTS.has(input.tint) ? input.tint : (prev?.tint || 'amber');
|
|
75
|
+
const title = String(
|
|
76
|
+
input.title || prev?.title || (kind === 'music' ? 'Lo-Fi 专注播放器' : `便签 #${cleanId}`)
|
|
77
|
+
).trim().slice(0, 100);
|
|
78
|
+
const text = input.text !== undefined
|
|
79
|
+
? String(input.text || '').slice(0, 4000)
|
|
80
|
+
: (prev?.text ?? (kind === 'sticky' ? '记录一条设计备忘…' : ''));
|
|
81
|
+
|
|
82
|
+
const defaultMusicData = kind === 'music' ? {
|
|
83
|
+
expanded: false,
|
|
84
|
+
selRenderMode: 'default',
|
|
85
|
+
tracks: [
|
|
86
|
+
{ id: 'song-1', title: '晴天 · 周杰伦', duration: '04:29', liked: false },
|
|
87
|
+
{ id: 'song-2', title: 'Midnight Coding · Synth', duration: '03:18', liked: true },
|
|
88
|
+
],
|
|
89
|
+
} : {};
|
|
90
|
+
|
|
91
|
+
const data = (input.data && typeof input.data === 'object' && !Array.isArray(input.data))
|
|
92
|
+
? { ...(prev?.data || defaultMusicData), ...input.data }
|
|
93
|
+
: (prev?.data || defaultMusicData);
|
|
94
|
+
|
|
95
|
+
const record = {
|
|
96
|
+
id: cleanId,
|
|
97
|
+
kind,
|
|
98
|
+
pluginId,
|
|
99
|
+
title,
|
|
100
|
+
x,
|
|
101
|
+
y,
|
|
102
|
+
width,
|
|
103
|
+
tint,
|
|
104
|
+
text,
|
|
105
|
+
data,
|
|
106
|
+
createdAt: prev?.createdAt || nowIso,
|
|
107
|
+
updatedAt: nowIso,
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
writeFileSync(join(objectsDir(stateDir), cleanId + '.json'), JSON.stringify(record, null, 2) + '\n');
|
|
111
|
+
return record;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function deleteCanvasObject(stateDir, id) {
|
|
115
|
+
const clean = safeObjectId(id);
|
|
116
|
+
if (!stateDir || !clean) return false;
|
|
117
|
+
const full = join(stateDir, 'objects', clean + '.json');
|
|
118
|
+
if (!existsSync(full)) return false;
|
|
119
|
+
try {
|
|
120
|
+
unlinkSync(full);
|
|
121
|
+
return true;
|
|
122
|
+
} catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|