cladogram 0.5.4 → 0.5.5-beta.2

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.
Files changed (54) hide show
  1. package/README.md +8 -6
  2. package/bin/clado.js +5 -5
  3. package/docs/release.md +13 -0
  4. package/package.json +1 -1
  5. package/plugins/agent/index.js +458 -25
  6. package/plugins/agent/style.css +299 -8
  7. package/plugins/directory/capabilities.json +1 -1
  8. package/plugins/directory/index.js +57 -2
  9. package/plugins/directory/style.css +11 -0
  10. package/plugins/view-controls/index.js +1 -1
  11. package/plugins/view-controls/style.css +30 -10
  12. package/skills/clado/SKILL.md +17 -16
  13. package/src/agent/executors.js +213 -0
  14. package/src/agent/probe.js +176 -0
  15. package/src/agent/providers/anthropic.js +220 -0
  16. package/src/agent/providers/index.js +52 -0
  17. package/src/agent/providers/openai.js +146 -0
  18. package/src/agent/runtime.js +557 -0
  19. package/src/agent/sessions.js +129 -0
  20. package/src/html/app-css.js +62 -9
  21. package/src/html/canvas-chain.js +2 -1
  22. package/src/html/canvas-ui.css +63 -0
  23. package/src/html/page.js +4 -0
  24. package/src/html/plugin-ui.css +12 -0
  25. package/src/html/plugin-ui.js +8 -2
  26. package/src/html/runtime-api.js +136 -5
  27. package/src/html/runtime.js +160 -290
  28. package/src/html/view-registry.js +95 -0
  29. package/src/html/views/view-cards.js +28 -0
  30. package/src/html/views/view-doc.js +51 -0
  31. package/src/html/views/view-mindmap.js +173 -0
  32. package/src/server/agent.js +335 -17
  33. package/src/server/assets/library-canvas.js +13 -3
  34. package/src/server/assets/library-plugin-bridge.js +2 -2
  35. package/src/server/assets/library-plugins.js +2 -2
  36. package/src/server/assets/library.css +5 -0
  37. package/src/server/assets/library.html +1 -1
  38. package/src/server/assets/library.js +157 -20
  39. package/src/server/events.js +189 -0
  40. package/src/server/export.js +1 -1
  41. package/src/server/mcp.js +16 -16
  42. package/src/server/plugin-capabilities.js +38 -22
  43. package/src/server/plugin-settings.js +27 -1
  44. package/src/server/plugins.js +17 -4
  45. package/src/server/workspace.js +171 -56
  46. package/src/skill/install.js +1 -1
  47. package/src/skill/targets.js +3 -3
  48. package/src/util/update.js +3 -2
  49. package/src/workspace/service.js +23 -15
  50. package/src/workspace/storage.js +88 -20
  51. package/templates/business-flow.mdc +1 -1
  52. package/templates/call-chain.mdc +1 -1
  53. package/templates/data-design.mdc +1 -1
  54. package/templates/test-cases.mdc +47 -0
@@ -4,19 +4,49 @@ import { client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk
4
4
  import { z } from 'zod/v4';
5
5
  import { VERSION } from '../util/version.js';
6
6
  import { DocumentError } from '../workspace/documents.js';
7
+ import {
8
+ buildDispatchPrompt, createRunRecord, discoverExecutors, listRunRecords, publicExecutorList, updateRunRecord,
9
+ } from '../agent/executors.js';
10
+ import { resolveProviderCredentials } from '../agent/providers/index.js';
11
+ import {
12
+ BUILTIN_PERSONAS, deleteSessionRecord, listSessionRecords, loadSessionRecord, saveSessionRecord,
13
+ } from '../agent/sessions.js';
14
+ import { runVerticalAgent } from '../agent/runtime.js';
7
15
 
8
16
  const idleMs = 15 * 60_000;
9
17
  const turnMs = 5 * 60_000;
10
18
  const sessionId = z.uuid();
19
+ const personaSchema = z.enum(['architect', 'qa', 'auditor', 'custom']);
20
+ const canvasSchema = z.strictObject({
21
+ file: z.string().min(1).max(1500),
22
+ revision: z.string().regex(/^[a-f0-9]{64}$/),
23
+ selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200),
24
+ });
11
25
  const requestSchema = z.discriminatedUnion('action', [
12
26
  z.strictObject({
13
27
  action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
14
28
  viewId: z.uuid().optional(),
15
- canvas: z.strictObject({
16
- file: z.string().min(1).max(1500),
17
- revision: z.string().regex(/^[a-f0-9]{64}$/),
18
- selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200),
19
- }).optional(),
29
+ mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
30
+ persona: personaSchema.optional(),
31
+ engine: z.enum(['auto', 'builtin', 'acp']).optional(),
32
+ canvas: canvasSchema.optional(),
33
+ }),
34
+ z.strictObject({
35
+ action: z.literal('answer'), session: sessionId,
36
+ questionId: z.string().min(1).max(128),
37
+ choiceId: z.string().max(128).optional(),
38
+ answer: z.string().trim().min(1).max(12_000),
39
+ viewId: z.uuid().optional(),
40
+ mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
41
+ persona: personaSchema.optional(),
42
+ canvas: canvasSchema.optional(),
43
+ }),
44
+ z.strictObject({
45
+ action: z.literal('dispatch'), session: sessionId,
46
+ executorId: z.string().min(1).max(128).optional(),
47
+ text: z.string().trim().max(12_000).default(''),
48
+ viewId: z.uuid().optional(),
49
+ canvas: canvasSchema.optional(),
20
50
  }),
21
51
  z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
22
52
  ]);
@@ -106,20 +136,38 @@ export function createAgentHandler({
106
136
  command = process.env.CLADO_CODEX_ACP_PATH || 'codex-acp',
107
137
  args = [],
108
138
  resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
139
+ resolveSettings = null,
140
+ resolveRuntimeInfo = null,
141
+ workspaceService = null,
142
+ events = null,
143
+ fetchImpl = fetch,
109
144
  }) {
110
145
  const sessions = new Map();
111
146
  const mcpName = () => 'clado_canvas_' + new URL(mcpUrl()).port;
147
+ const readSettings = () => {
148
+ const base = resolveSettings ? resolveSettings() : {};
149
+ const launch = resolveLaunch();
150
+ return { ...launch, ...base };
151
+ };
152
+
112
153
  function close(session, error) {
113
154
  if (sessions.get(session.key) !== session) return;
114
155
  sessions.delete(session.key);
115
156
  clearTimeout(session.idle);
157
+ session.abortController?.abort();
116
158
  session.fail?.(error || new Error('Agent 会话已关闭。'));
117
159
  session.agent?.dispose();
118
160
  }
119
161
 
120
- async function connect(session) {
162
+ async function connectAcp(session, launchOverride = null) {
163
+ const launch = launchOverride || resolveLaunch();
121
164
  session.agent = startAgent({
122
- workspace, ...resolveLaunch(), mcpName: mcpName(), emit: event => session.emit?.(event),
165
+ workspace: session.workspace,
166
+ command: launch.command,
167
+ args: launch.args || [],
168
+ env: launch.env || {},
169
+ mcpName: mcpName(),
170
+ emit: event => session.emit?.(event),
123
171
  closed: error => close(session, error),
124
172
  });
125
173
  const { rpc } = session.agent;
@@ -131,13 +179,101 @@ export function createAgentHandler({
131
179
  if (init.protocolVersion !== PROTOCOL_VERSION) throw new Error('当前适配器不支持 Clado 的 ACP 协议版本。');
132
180
  session.hasMcp = !!init.agentCapabilities?.mcpCapabilities?.http;
133
181
  const result = await rpc.request('session/new', {
134
- cwd: workspace,
182
+ cwd: session.workspace,
135
183
  mcpServers: session.hasMcp ? [{ name: mcpName(), type: 'http', url: mcpUrl(), headers: [] }] : [],
136
184
  });
137
185
  session.id = result.sessionId;
138
186
  }
139
187
 
140
- async function handle(req, res) {
188
+ function resolveMeta(targetWorkspace) {
189
+ const settings = readSettings();
190
+ const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
191
+ const executors = discoverExecutors({
192
+ stateDir: rtInfo.stateDir,
193
+ settings,
194
+ pluginDescriptors: rtInfo.pluginDescriptors || [],
195
+ });
196
+ const creds = resolveProviderCredentials(settings);
197
+ const builtinConfigured = Boolean(creds.apiKey);
198
+ const configuredMode = settings.mode || 'auto';
199
+ const activeEngine = configuredMode === 'builtin'
200
+ ? 'builtin'
201
+ : configuredMode === 'acp'
202
+ ? 'acp'
203
+ : (builtinConfigured ? 'builtin' : 'acp');
204
+ return {
205
+ settings,
206
+ rtInfo,
207
+ executors,
208
+ builtinConfigured,
209
+ activeEngine,
210
+ provider: creds.provider,
211
+ model: creds.model,
212
+ defaultPersona: settings.persona || 'architect',
213
+ };
214
+ }
215
+
216
+ function handleMeta(req, res, targetWorkspace = workspace) {
217
+ const host = req.headers.host || '';
218
+ if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
219
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
220
+ const meta = resolveMeta(targetWorkspace);
221
+ res.writeHead(200, {
222
+ 'content-type': 'application/json; charset=utf-8',
223
+ 'cache-control': 'no-store',
224
+ 'x-content-type-options': 'nosniff',
225
+ });
226
+ res.end(JSON.stringify({
227
+ engine: meta.activeEngine,
228
+ provider: meta.provider,
229
+ builtinConfigured: meta.builtinConfigured,
230
+ model: meta.model,
231
+ defaultPersona: meta.defaultPersona,
232
+ personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
233
+ executors: publicExecutorList(meta.executors),
234
+ runs: listRunRecords(meta.rtInfo.stateDir, 10),
235
+ sessions: listSessionRecords(meta.rtInfo.stateDir, 20),
236
+ }));
237
+ }
238
+
239
+ function handleSessions(req, res, url, targetWorkspace = workspace) {
240
+ const host = req.headers.host || '';
241
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
242
+ const meta = resolveMeta(targetWorkspace);
243
+ const stateDir = meta.rtInfo.stateDir;
244
+ const id = url.searchParams.get('id');
245
+ const sendJson = (status, data) => {
246
+ res.writeHead(status, {
247
+ 'content-type': 'application/json; charset=utf-8',
248
+ 'cache-control': 'no-store',
249
+ 'x-content-type-options': 'nosniff',
250
+ });
251
+ res.end(JSON.stringify(data));
252
+ };
253
+ if (req.method === 'GET') {
254
+ if (id) {
255
+ const record = loadSessionRecord(stateDir, id);
256
+ if (!record) throw new DocumentError('未找到该历史会话。', 404);
257
+ sendJson(200, { session: record });
258
+ return;
259
+ }
260
+ sendJson(200, { sessions: listSessionRecords(stateDir, 30) });
261
+ return;
262
+ }
263
+ if (req.method === 'DELETE') {
264
+ if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
265
+ if (!id) throw new DocumentError('缺少会话 id。', 400);
266
+ const active = sessions.get(id);
267
+ if (active) close(active);
268
+ const deleted = deleteSessionRecord(stateDir, id);
269
+ if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
270
+ sendJson(200, { deleted: true });
271
+ return;
272
+ }
273
+ throw new DocumentError('会话接口仅支持 GET / DELETE。', 405);
274
+ }
275
+
276
+ async function handle(req, res, targetWorkspace = workspace) {
141
277
  const host = req.headers.host || '';
142
278
  if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
143
279
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
@@ -147,12 +283,14 @@ export function createAgentHandler({
147
283
  }
148
284
  const input = await readRequest(req);
149
285
  let session = sessions.get(input.session);
150
- if (input.action !== 'prompt') {
286
+ if (input.action === 'cancel' || input.action === 'close') {
151
287
  if (input.action === 'close') {
152
288
  close(session || { key: input.session });
153
289
  } else if (session?.running) {
154
290
  session.cancelled = true;
155
- if (session.id) {
291
+ if (session.abortController) {
292
+ session.abortController.abort();
293
+ } else if (session.id && session.agent) {
156
294
  session.agent.rpc.notify('session/cancel', { sessionId: session.id }).catch(error => close(session, error));
157
295
  session.stopTimer ||= setTimeout(() => close(session, new Error('Agent 停止超时,会话已关闭。')), 5000);
158
296
  } else close(session, new Error('已停止连接。'));
@@ -160,12 +298,44 @@ export function createAgentHandler({
160
298
  res.writeHead(204).end();
161
299
  return;
162
300
  }
301
+
163
302
  if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
303
+ if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
304
+ const meta = resolveMeta(targetWorkspace);
164
305
  if (!session) {
165
306
  if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
166
- session = { key: input.session };
307
+ const saved = loadSessionRecord(meta.rtInfo.stateDir, input.session);
308
+ session = {
309
+ key: input.session,
310
+ workspace: targetWorkspace,
311
+ title: saved?.title || '',
312
+ persona: saved?.persona || meta.defaultPersona,
313
+ mode: saved?.mode || 'design',
314
+ history: Array.isArray(saved?.messages) ? saved.messages : [],
315
+ uiMessages: Array.isArray(saved?.uiMessages) ? saved.uiMessages : [],
316
+ pendingQuestion: saved?.pendingQuestion || null,
317
+ };
167
318
  sessions.set(input.session, session);
168
319
  }
320
+
321
+ let resumeToolResult = null;
322
+ if (input.action === 'answer') {
323
+ const pending = session.pendingQuestion;
324
+ if (!pending || pending.id !== input.questionId) {
325
+ throw new DocumentError('当前没有待确认的提问,或该提问已失效。', 409);
326
+ }
327
+ resumeToolResult = {
328
+ toolCallId: pending.toolCallId,
329
+ choiceId: input.choiceId || '',
330
+ answer: input.answer,
331
+ };
332
+ }
333
+
334
+ const useBuiltin = input.action === 'answer' || (input.action === 'prompt' && (
335
+ input.engine === 'builtin' ||
336
+ ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
337
+ ));
338
+
169
339
  session.running = true;
170
340
  session.cancelled = false;
171
341
  clearTimeout(session.idle);
@@ -182,19 +352,166 @@ export function createAgentHandler({
182
352
  const onDisconnect = () => { if (!res.writableEnded) close(session); };
183
353
  res.on('close', onDisconnect);
184
354
  const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
355
+
185
356
  const run = async () => {
186
- if (!session.agent) await connect(session);
357
+ if (useBuiltin) {
358
+ session.abortController = new AbortController();
359
+ // 若上一轮有未回答的 ask_user,但用户直接发起了新指令,补一条跳过回执避免协议报孤立 tool_call 错误
360
+ if (input.action === 'prompt' && session.pendingQuestion) {
361
+ session.history.push({
362
+ role: 'tool',
363
+ tool_call_id: session.pendingQuestion.toolCallId,
364
+ content: JSON.stringify({ answered: false, skipped: true, reason: '用户发起了新的指令' }),
365
+ });
366
+ for (let i = session.uiMessages.length - 1; i >= 0; i--) {
367
+ if (session.uiMessages[i]?.question?.id === session.pendingQuestion.id) {
368
+ session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: '(已跳过,发起新指令)' };
369
+ break;
370
+ }
371
+ }
372
+ session.pendingQuestion = null;
373
+ }
374
+ const activeMode = input.mode || session.mode || 'general';
375
+ const activePersona = input.persona || session.persona || meta.defaultPersona;
376
+ let thinkingBuf = '';
377
+ let textBuf = '';
378
+ let changesBuf = [];
379
+ const emitBuiltin = ev => {
380
+ if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
381
+ else if (ev.type === 'text' && ev.text) textBuf += ev.text;
382
+ else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
383
+ emit(ev);
384
+ };
385
+ const result = await runVerticalAgent({
386
+ workspace: session.workspace,
387
+ stateDir: meta.rtInfo.stateDir,
388
+ workspaceService,
389
+ events,
390
+ config: meta.settings,
391
+ history: session.history,
392
+ resumeToolResult,
393
+ input,
394
+ mode: activeMode,
395
+ persona: activePersona,
396
+ emit: emitBuiltin,
397
+ signal: session.abortController.signal,
398
+ fetchImpl,
399
+ });
400
+ if (input.action === 'answer') {
401
+ for (let i = session.uiMessages.length - 1; i >= 0; i--) {
402
+ if (session.uiMessages[i]?.question?.id === input.questionId) {
403
+ session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: input.answer };
404
+ break;
405
+ }
406
+ }
407
+ session.uiMessages.push({ role: 'human', text: input.answer, isAnswer: true });
408
+ } else {
409
+ session.uiMessages.push({
410
+ role: 'human',
411
+ text: input.text,
412
+ canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
413
+ });
414
+ }
415
+ if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion) {
416
+ session.uiMessages.push({
417
+ role: 'assistant',
418
+ thinking: thinkingBuf,
419
+ text: textBuf,
420
+ changes: changesBuf,
421
+ question: result.pendingQuestion || null,
422
+ });
423
+ }
424
+ session.history = Array.isArray(result.conversation) ? result.conversation : session.history;
425
+ session.pendingQuestion = result.pendingQuestion || null;
426
+ session.persona = activePersona;
427
+ session.mode = activeMode;
428
+ if (!session.title) session.title = (input.text || input.answer || '新对话').slice(0, 48);
429
+ saveSessionRecord(meta.rtInfo.stateDir, {
430
+ id: session.key,
431
+ title: session.title,
432
+ persona: session.persona,
433
+ mode: session.mode,
434
+ messages: session.history,
435
+ uiMessages: session.uiMessages,
436
+ pendingQuestion: session.pendingQuestion,
437
+ });
438
+ return { stopReason: result.stopReason };
439
+ }
440
+
441
+ if (input.action === 'dispatch') {
442
+ const chosen = input.executorId
443
+ ? meta.executors.find(item => item.id === input.executorId)
444
+ : meta.executors[0];
445
+ if (!chosen) throw new Error('找不到指定的 ACP 执行器插件:' + (input.executorId || '默认'));
446
+ const runRec = createRunRecord(meta.rtInfo.stateDir, {
447
+ kind: 'dispatch',
448
+ mode: 'implement',
449
+ executorId: chosen.id,
450
+ file: input.canvas?.file || '',
451
+ instruction: input.text || '按画布规格实施开发',
452
+ });
453
+ emit({ type: 'run', run: runRec });
454
+ emit({ type: 'status', text: `正在派发给执行器:${chosen.name}` });
455
+ events?.emit(session.workspace, 'agent.activity', {
456
+ file: input.canvas?.file || '',
457
+ action: 'dispatch',
458
+ kind: 'write',
459
+ nodes: input.canvas?.selection || [],
460
+ label: `ACP 派发开发中 · ${chosen.name}`,
461
+ });
462
+
463
+ // 如果当前会话绑定的不是这个执行器,重新建立对应执行器的 ACP 连接
464
+ if (session.agent && session.executorId !== chosen.id) {
465
+ session.agent.dispose();
466
+ session.agent = null;
467
+ session.id = null;
468
+ session.started = false;
469
+ }
470
+ session.executorId = chosen.id;
471
+ if (!session.agent) await connectAcp(session, chosen);
472
+ if (session.cancelled || sessions.get(session.key) !== session) {
473
+ updateRunRecord(meta.rtInfo.stateDir, runRec, { status: 'cancelled' });
474
+ return { stopReason: 'cancelled' };
475
+ }
476
+ emit({ type: 'status', text: `${chosen.name} 执行中(无需切换窗口)…` });
477
+ const prompt = buildDispatchPrompt({
478
+ workspace: session.workspace,
479
+ documentRoot: meta.rtInfo.documentRoot,
480
+ file: input.canvas?.file || '',
481
+ selection: input.canvas?.selection || [],
482
+ instruction: input.text,
483
+ mcpName: session.hasMcp ? mcpName() : '',
484
+ });
485
+ const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
486
+ const finished = updateRunRecord(meta.rtInfo.stateDir, runRec, {
487
+ status: session.cancelled ? 'cancelled' : 'completed',
488
+ summary: `执行器 ${chosen.name} 已完成(${response.stopReason})`,
489
+ });
490
+ emit({ type: 'run', run: finished });
491
+ events?.emit(session.workspace, 'agent.activity', {
492
+ file: input.canvas?.file || '',
493
+ action: 'dispatch.done',
494
+ kind: 'write',
495
+ nodes: input.canvas?.selection || [],
496
+ label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
497
+ });
498
+ return response;
499
+ }
500
+
501
+ // 默认 ACP 对话模式(完全兼容既有行为)
502
+ if (!session.agent) await connectAcp(session);
187
503
  if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
188
504
  emit({ type: 'status', text: '正在生成' });
189
- const prompt = promptBlocks(workspace, input);
505
+ const prompt = promptBlocks(session.workspace, input);
190
506
  if (!session.started && session.hasMcp) {
191
507
  prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
192
508
  session.started = true;
193
509
  }
194
510
  return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
195
511
  };
512
+
196
513
  try {
197
- emit({ type: 'status', text: session.agent ? '正在发送' : '正在连接 Agent' });
514
+ emit({ type: 'status', text: useBuiltin ? '正在启动 Clado 独立 Agent' : (session.agent ? '正在发送' : '正在连接 Agent') });
198
515
  const result = await Promise.race([run(), abort]);
199
516
  emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
200
517
  } catch (error) {
@@ -203,11 +520,12 @@ export function createAgentHandler({
203
520
  const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
204
521
  emit({ type: 'error', text: message });
205
522
  }
206
- close(session, error);
523
+ if (!useBuiltin) close(session, error);
207
524
  } finally {
208
525
  clearTimeout(timer);
209
526
  clearTimeout(session.stopTimer);
210
527
  session.stopTimer = undefined;
528
+ session.abortController = undefined;
211
529
  session.running = false;
212
530
  session.emit = session.fail = undefined;
213
531
  res.off('close', onDisconnect);
@@ -218,5 +536,5 @@ export function createAgentHandler({
218
536
  }
219
537
  }
220
538
  }
221
- return { handle, close: () => { for (const session of sessions.values()) close(session); } };
539
+ return { handle, handleMeta, handleSessions, close: () => { for (const session of sessions.values()) close(session); } };
222
540
  }
@@ -67,7 +67,8 @@
67
67
  const target = new URL(href,'https://clado.local/documents/'+file);
68
68
  if (!target.pathname.startsWith('/documents/')) return null;
69
69
  const path=decodeURIComponent(target.pathname.slice('/documents/'.length));
70
- return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path));
70
+ const workspace = window.__CLADO_WORKSPACE_ID__ ? '&workspace=' + encodeURIComponent(window.__CLADO_WORKSPACE_ID__) : '';
71
+ return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path)+workspace);
71
72
  }
72
73
  function rewriteDocumentLinks() {
73
74
  document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
@@ -137,10 +138,19 @@
137
138
  if (deferredDisplay) { const next=deferredDisplay;deferredDisplay=null;window.dispatchEvent(new MessageEvent('message', { source:parent,data:next })); }
138
139
  });
139
140
  window.addEventListener('message', async event => {
140
- if(event.source!==parent || event.data?.type!=='clado-workspace:display')return;
141
+ if (event.source !== parent) return;
142
+ if (event.data?.type === 'clado-workspace:ai-touch') {
143
+ runtime.highlightActivity?.(event.data);
144
+ return;
145
+ }
146
+ if (event.data?.type === 'clado-workspace:focus-node') {
147
+ runtime.focusNodePath?.(event.data.node, event.data.label);
148
+ return;
149
+ }
150
+ if (event.data?.type !== 'clado-workspace:display') return;
141
151
  if (runtime.isChainOpen?.()) { deferredDisplay=event.data;return; }
142
152
  const {mode,theme,anchor}=event.data;
143
- if(['doc','cards','mindmap'].includes(mode)) runtime.setMode(mode);
153
+ if(window.CladoViews ? window.CladoViews.has(mode) : ['doc','cards','mindmap'].includes(mode)) runtime.setMode(mode);
144
154
  if(['light','dark'].includes(theme))runtime.setTheme(theme,false);
145
155
  await settle();
146
156
  if(anchor) { let title=anchor;try{title=decodeURIComponent(anchor);}catch{}runtime.focusTitle(title); }
@@ -1,7 +1,7 @@
1
1
  (() => {
2
- window.CladoCapabilityBridge = () => {
2
+ window.CladoCapabilityBridge = (workspaceId = '') => {
3
3
  const viewId = crypto.randomUUID();
4
- const endpoint = '/library/plugin-bridge?viewId=' + encodeURIComponent(viewId);
4
+ const endpoint = '/library/plugin-bridge?viewId=' + encodeURIComponent(viewId) + (workspaceId ? '&workspace=' + encodeURIComponent(workspaceId) : '');
5
5
  const handlers = new Map();
6
6
  const keyOf = ({ pluginId, mountId }) => JSON.stringify([pluginId, mountId]);
7
7
  let stream, connected = false;
@@ -6,7 +6,7 @@
6
6
  new Set(value).size === value.length && value.every(item => expected.includes(item));
7
7
  const byteLength = value => new TextEncoder().encode(value).length;
8
8
 
9
- window.CladoPluginHost = ({ host, readView, capabilities, isEnabled }) => {
9
+ window.CladoPluginHost = ({ host, readView, capabilities, isEnabled, workspaceId = '' }) => {
10
10
  const viewId = capabilities.viewId;
11
11
  let catalog;
12
12
  const tickets = new Map(), registered = new Set();
@@ -186,7 +186,7 @@
186
186
  event.source.postMessage({ type: 'clado-plugin:port', ticket }, '*', [channel.port2]);
187
187
  }
188
188
  addEventListener('message', accept);
189
- fetch('/library/plugins.json', { cache: 'no-store' }).then(response => {
189
+ fetch('/library/plugins.json' + (workspaceId ? '?workspace=' + encodeURIComponent(workspaceId) : ''), { cache: 'no-store' }).then(response => {
190
190
  if (!response.ok) throw new Error('插件清单读取失败。');
191
191
  return response.json();
192
192
  }).then(data => {
@@ -3,4 +3,9 @@
3
3
  .viewer,.viewer main{position:absolute;inset:0}iframe{height:100%;width:100%;display:block;border:0}
4
4
  .canvas-loading{position:absolute;inset:0;background:var(--panel);color:var(--muted);display:grid;place-items:center;font-size:12px;z-index:2}.canvas-loading[hidden],#directory[hidden],.update-error[hidden],.empty-state[hidden],.skipped[hidden]{display:none}.update-error{position:absolute;top:60px;left:16px;right:16px;z-index:5;background:#fff6dd;color:#896213;border:1px solid #ecd9a6;border-radius:7px;padding:10px 13px;font-size:11px;box-shadow:0 3px 12px #0001}.empty-state{position:absolute;inset:0;background:var(--panel);padding:70px 35px;text-align:center}.empty-state h1{font-size:17px;font-weight:550}.empty-state p{font-size:12px;line-height:1.9;color:var(--muted);max-width:360px;margin:15px auto}
5
5
  [data-theme="dark"]{color-scheme:dark;--panel:#1c222b;--bg:#151a22;--ink:#dfe7ef;--muted:#9ba8b8;--line:#343e4c;--soft:#203753}
6
+ .empty-workspaces{margin:24px auto 0;max-width:460px;display:flex;flex-direction:column;gap:8px;text-align:left}
7
+ .empty-workspaces-title{font-size:11px;color:var(--muted);font-weight:600}
8
+ .empty-workspace-card{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px;border:1px solid var(--line);border-radius:10px;background:var(--bg);color:var(--ink);text-decoration:none;font-size:12px}
9
+ .empty-workspace-card:hover{border-color:var(--accent)}
10
+ .empty-workspace-card small{color:var(--muted);font-size:11px;flex:none}
6
11
  [hidden]{display:none!important}
@@ -3,7 +3,7 @@
3
3
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Clado · Markdown 目录预览</title><link rel="stylesheet" href="library.css"><!--CLADO-PLUGIN-STYLES--></head>
4
4
  <body>
5
5
  <div class="viewer">
6
- <main><div id="updateError" class="update-error" role="alert" hidden></div><iframe id="canvas" title="当前 Markdown 的脑图、卡片与文档"></iframe><div id="canvasLoading" class="canvas-loading">正在读取 Markdown…</div><div id="emptyState" class="empty-state" hidden><h1>目录中还没有可展示的画布</h1><p>让 AI 连接当前服务的 MCP,读取模板并创建 .mdc 文档,保存后会自动出现在这里。</p></div></main>
6
+ <main><div id="updateError" class="update-error" role="alert" hidden></div><iframe id="canvas" title="当前 Markdown 的卡片、脑图与文档"></iframe><div id="canvasLoading" class="canvas-loading">正在读取 Markdown…</div><div id="emptyState" class="empty-state" hidden><h1>目录中还没有可展示的画布</h1><p>让 AI 连接当前服务的 MCP,读取模板并创建 .mdc 文档,保存后会自动出现在这里。</p></div></main>
7
7
  </div>
8
8
  <!--CLADO-PLUGIN-SCRIPTS-->
9
9
  <script src="library.js"></script>