cladogram 0.5.5-beta.6 → 0.5.5-beta.7

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.
@@ -1,32 +1,64 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { spawn } from 'node:child_process';
3
+ import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
2
4
  import { Readable, Writable } from 'node:stream';
3
5
  import { client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
4
6
  import { z } from 'zod/v4';
5
7
  import { VERSION } from '../util/version.js';
6
- import { DocumentError } from '../workspace/documents.js';
8
+ import { DocumentError, workspacePath } from '../workspace/documents.js';
9
+ import {
10
+ buildSegmentedPromptContext,
11
+ readAgentDebugConfig,
12
+ readWorkspaceMemory,
13
+ resetAgentDebugConfig,
14
+ saveAgentDebugConfig,
15
+ saveWorkspaceMemory,
16
+ } from '../agent/context.js';
7
17
  import {
8
18
  buildDispatchPrompt, createRunRecord, discoverExecutors, listRunRecords, publicExecutorList, updateRunRecord,
9
19
  } from '../agent/executors.js';
10
20
  import { resolveProviderCredentials } from '../agent/providers/index.js';
11
21
  import {
12
- BUILTIN_PERSONAS, deleteSessionRecord, listSessionRecords, loadSessionRecord, saveSessionRecord,
22
+ archiveSessionRecord,
23
+ BUILTIN_PERSONAS,
24
+ compactMessages,
25
+ deleteSessionRecord,
26
+ listSessionRecords,
27
+ loadSessionRecord,
28
+ paletteForPersona,
29
+ PERSONA_TEMPLATES,
30
+ resolvePersona,
31
+ safeSessionId,
32
+ saveSessionRecord,
13
33
  } from '../agent/sessions.js';
14
34
  import { runVerticalAgent } from '../agent/runtime.js';
15
35
 
16
36
  const idleMs = 15 * 60_000;
17
37
  const turnMs = 5 * 60_000;
18
- const sessionId = z.uuid();
19
- const personaSchema = z.enum(['architect', 'qa', 'auditor', 'custom']);
38
+ const MAX_PEER_HOPS = 8;
39
+ const sessionId = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
40
+ const personaSchema = z.enum(['architect', 'coder', 'qa', 'auditor', 'custom']);
41
+ const execModeSchema = z.enum(['plan', 'act']);
42
+ const canvasObjectItemSchema = z.strictObject({
43
+ id: z.string().min(1).max(120),
44
+ kind: z.string().min(1).max(60),
45
+ title: z.string().max(160),
46
+ pluginId: z.string().max(120).optional(),
47
+ subtarget: z.string().max(160).optional(),
48
+ });
20
49
  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),
50
+ file: z.string().max(1500).optional(),
51
+ revision: z.string().regex(/^[a-f0-9]{64}$/).optional(),
52
+ selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200).default([]),
53
+ objectSelection: z.array(canvasObjectItemSchema).max(100).optional(),
24
54
  });
25
55
  const requestSchema = z.discriminatedUnion('action', [
26
56
  z.strictObject({
27
57
  action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
58
+ title: z.string().max(60).optional(),
28
59
  viewId: z.uuid().optional(),
29
60
  mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
61
+ execMode: execModeSchema.optional(),
30
62
  persona: personaSchema.optional(),
31
63
  engine: z.enum(['auto', 'builtin', 'acp']).optional(),
32
64
  canvas: canvasSchema.optional(),
@@ -38,9 +70,24 @@ const requestSchema = z.discriminatedUnion('action', [
38
70
  answer: z.string().trim().min(1).max(12_000),
39
71
  viewId: z.uuid().optional(),
40
72
  mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
73
+ execMode: execModeSchema.optional(),
41
74
  persona: personaSchema.optional(),
42
75
  canvas: canvasSchema.optional(),
43
76
  }),
77
+ z.strictObject({
78
+ action: z.literal('command_decision'), session: sessionId,
79
+ commandId: z.string().min(1).max(128),
80
+ decision: z.enum(['allow', 'session_allow', 'deny']),
81
+ viewId: z.uuid().optional(),
82
+ mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
83
+ execMode: execModeSchema.optional(),
84
+ persona: personaSchema.optional(),
85
+ canvas: canvasSchema.optional(),
86
+ }),
87
+ z.strictObject({
88
+ action: z.literal('steer'), session: sessionId,
89
+ text: z.string().trim().min(1).max(4_000),
90
+ }),
44
91
  z.strictObject({
45
92
  action: z.literal('dispatch'), session: sessionId,
46
93
  executorId: z.string().min(1).max(128).optional(),
@@ -51,15 +98,20 @@ const requestSchema = z.discriminatedUnion('action', [
51
98
  z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
52
99
  ]);
53
100
 
54
- async function readRequest(req) {
101
+ async function readJsonBody(req, maxBytes = 96 * 1024) {
55
102
  const chunks = [];
56
103
  let bytes = 0;
57
104
  for await (const chunk of req) {
58
105
  bytes += chunk.length;
59
- if (bytes > 96 * 1024) throw new DocumentError('发送内容过长。', 413);
106
+ if (bytes > maxBytes) throw new DocumentError('发送内容过长。', 413);
60
107
  chunks.push(chunk);
61
108
  }
62
- const parsed = requestSchema.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
109
+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
110
+ }
111
+
112
+ async function readRequest(req) {
113
+ const raw = await readJsonBody(req, 96 * 1024);
114
+ const parsed = requestSchema.safeParse(raw);
63
115
  if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
64
116
  return parsed.data;
65
117
  }
@@ -68,10 +120,15 @@ function promptBlocks(workspace, input) {
68
120
  const context = {
69
121
  workspace,
70
122
  ...(input.viewId && { viewId: input.viewId }),
71
- ...(input.canvas && { file: input.canvas.file, revision: input.canvas.revision, selection: input.canvas.selection }),
123
+ ...(input.canvas && {
124
+ file: input.canvas.file,
125
+ revision: input.canvas.revision,
126
+ selection: input.canvas.selection,
127
+ ...(input.canvas.objectSelection?.length ? { objectSelection: input.canvas.objectSelection } : {}),
128
+ }),
72
129
  };
73
130
  return [
74
- { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径。' },
131
+ { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径,objectSelection 是选中的多实例画布组件或子区域靶点。' },
75
132
  { type: 'text', text: JSON.stringify(context) },
76
133
  { type: 'text', text: '用户指令:\n' + input.text },
77
134
  ];
@@ -95,8 +152,6 @@ function startAgent({ workspace, command, args, env, mcpName, emit, closed }) {
95
152
  proc.on('exit', code => closed(new Error('ACP 进程已退出' + (code ? '(退出码 ' + code + ')' : '') + '。请检查启动命令和登录状态。')));
96
153
  const connection = client()
97
154
  .onRequest('session/request_permission', ({ params }) => {
98
- // The send action enables canvas operations on this serve instance.
99
- // Match the adapter's correlated tool call, never its display text alone.
100
155
  const option = params.options.find(option => option.kind === 'allow_once');
101
156
  if (option && params._meta?.is_mcp_tool_approval === true &&
102
157
  cladoCalls.get(params.toolCall.toolCallId) === params.sessionId) {
@@ -150,6 +205,37 @@ export function createAgentHandler({
150
205
  return { ...launch, ...base };
151
206
  };
152
207
 
208
+ function runningSessionIds(targetWorkspace) {
209
+ const set = new Set();
210
+ for (const s of sessions.values()) {
211
+ if (s.running && s.workspace === targetWorkspace) set.add(s.key);
212
+ }
213
+ return set;
214
+ }
215
+
216
+ function activePeerLocksFor(targetWorkspace, excludeSessionKey) {
217
+ const locks = [];
218
+ for (const s of sessions.values()) {
219
+ if (s.running && s.workspace === targetWorkspace && s.key !== excludeSessionKey && s.activeCardTarget) {
220
+ locks.push({ peerId: s.key, peerName: s.title || '同伴', target: s.activeCardTarget });
221
+ }
222
+ }
223
+ return locks;
224
+ }
225
+
226
+ function emitSessionSync(targetWorkspace, stateDir, autoArchiveHours = 24) {
227
+ if (!events || !stateDir) return;
228
+ try {
229
+ const list = listSessionRecords(stateDir, {
230
+ limit: 40,
231
+ includeArchived: false,
232
+ autoArchiveHours,
233
+ runningIds: runningSessionIds(targetWorkspace),
234
+ });
235
+ events.emit(targetWorkspace, 'agent.sessions', { sessions: list });
236
+ } catch {}
237
+ }
238
+
153
239
  function close(session, error) {
154
240
  if (sessions.get(session.key) !== session) return;
155
241
  sessions.delete(session.key);
@@ -188,6 +274,7 @@ export function createAgentHandler({
188
274
  function resolveMeta(targetWorkspace) {
189
275
  const settings = readSettings();
190
276
  const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
277
+ const debugBundle = readAgentDebugConfig(rtInfo.stateDir);
191
278
  const executors = discoverExecutors({
192
279
  stateDir: rtInfo.stateDir,
193
280
  settings,
@@ -203,6 +290,8 @@ export function createAgentHandler({
203
290
  : (builtinConfigured ? 'builtin' : 'acp');
204
291
  return {
205
292
  settings,
293
+ debugConfig: debugBundle.config,
294
+ hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
206
295
  rtInfo,
207
296
  executors,
208
297
  builtinConfigured,
@@ -213,6 +302,315 @@ export function createAgentHandler({
213
302
  };
214
303
  }
215
304
 
305
+ function ensureMemorySession(targetWorkspace, meta, id, defaults = {}) {
306
+ let session = sessions.get(id);
307
+ if (!session) {
308
+ const saved = loadSessionRecord(meta.rtInfo.stateDir, id);
309
+ const persona = defaults.persona || saved?.persona || meta.defaultPersona;
310
+ session = {
311
+ key: id,
312
+ workspace: targetWorkspace,
313
+ title: defaults.title || saved?.title || '',
314
+ persona,
315
+ pal: saved?.pal || paletteForPersona(persona),
316
+ mode: defaults.mode || saved?.mode || 'design',
317
+ execMode: defaults.execMode || saved?.execMode || 'act',
318
+ liveStatus: saved?.liveStatus || '',
319
+ todos: Array.isArray(saved?.todos) ? saved.todos : [],
320
+ calledBy: saved?.calledBy || null,
321
+ peerHopCount: saved?.peerHopCount || 0,
322
+ canvasBaseline: saved?.canvasBaseline || null,
323
+ checkpoints: Array.isArray(saved?.checkpoints) ? saved.checkpoints : [],
324
+ history: Array.isArray(saved?.messages) ? saved.messages : [],
325
+ uiMessages: Array.isArray(saved?.uiMessages) ? saved.uiMessages : [],
326
+ pendingQuestion: saved?.pendingQuestion || null,
327
+ pendingCommand: saved?.pendingCommand || null,
328
+ incomingPeerMessages: [],
329
+ steeringQueue: [],
330
+ commandAutoAllow: false,
331
+ };
332
+ sessions.set(id, session);
333
+ }
334
+ return session;
335
+ }
336
+
337
+ /**
338
+ * 后台异步唤醒平级同伴会话执行一轮任务(用于 spawn_peer / message_peer request)。
339
+ */
340
+ async function runBackgroundPeerTurn(targetWorkspace, peerSession, taskText, { hopCount = 1 } = {}) {
341
+ if (peerSession.running) return;
342
+ const meta = resolveMeta(targetWorkspace);
343
+ if (!meta.builtinConfigured) return;
344
+
345
+ peerSession.running = true;
346
+ peerSession.cancelled = false;
347
+ peerSession.peerHopCount = hopCount;
348
+ peerSession.abortController = new AbortController();
349
+ peerSession.liveStatus = '收到呼叫,正在处理…';
350
+
351
+ if (meta.rtInfo.stateDir) {
352
+ saveSessionRecord(meta.rtInfo.stateDir, {
353
+ id: peerSession.key,
354
+ title: peerSession.title,
355
+ persona: peerSession.persona,
356
+ pal: peerSession.pal,
357
+ mode: peerSession.mode,
358
+ execMode: peerSession.execMode,
359
+ archived: false,
360
+ liveStatus: peerSession.liveStatus,
361
+ todos: peerSession.todos,
362
+ calledBy: peerSession.calledBy,
363
+ peerHopCount: peerSession.peerHopCount,
364
+ messages: peerSession.history,
365
+ uiMessages: peerSession.uiMessages,
366
+ });
367
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
368
+ }
369
+
370
+ let thinkingBuf = '';
371
+ let textBuf = '';
372
+ let changesBuf = [];
373
+ const peerCoord = createPeerCoordinator(targetWorkspace, meta, peerSession);
374
+
375
+ try {
376
+ const incoming = peerSession.incomingPeerMessages.splice(0);
377
+ const result = await runVerticalAgent({
378
+ workspace: targetWorkspace,
379
+ rootWorkspace: workspace,
380
+ documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
381
+ stateDir: meta.rtInfo.stateDir,
382
+ workspaceService,
383
+ events,
384
+ config: meta.settings,
385
+ debugConfig: meta.debugConfig,
386
+ history: peerSession.history,
387
+ canvasBaseline: peerSession.canvasBaseline,
388
+ activePeerLocks: activePeerLocksFor(targetWorkspace, peerSession.key),
389
+ incomingPeerMessages: incoming,
390
+ peerCoordinator: peerCoord,
391
+ sessionCommandAutoAllow: peerSession.commandAutoAllow,
392
+ drainSteering: () => peerSession.steeringQueue.splice(0),
393
+ input: { text: taskText },
394
+ mode: peerSession.mode,
395
+ execMode: peerSession.execMode,
396
+ persona: peerSession.persona,
397
+ todos: peerSession.todos,
398
+ signal: peerSession.abortController.signal,
399
+ fetchImpl,
400
+ emit: ev => {
401
+ if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
402
+ else if (ev.type === 'text' && ev.text) textBuf += ev.text;
403
+ else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
404
+ else if (ev.type === 'todos' && Array.isArray(ev.todos)) peerSession.todos = ev.todos;
405
+ else if (ev.type === 'status' && ev.text) {
406
+ peerSession.liveStatus = ev.text;
407
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
408
+ }
409
+ },
410
+ });
411
+
412
+ peerSession.history = Array.isArray(result.conversation) ? result.conversation : peerSession.history;
413
+ peerSession.todos = Array.isArray(result.todos) ? result.todos : peerSession.todos;
414
+ peerSession.canvasBaseline = result.nextBaseline || peerSession.canvasBaseline;
415
+ peerSession.pendingQuestion = result.pendingQuestion || null;
416
+ peerSession.pendingCommand = result.pendingCommand || null;
417
+ if (result.checkpoint) peerSession.checkpoints.push(result.checkpoint);
418
+
419
+ if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
420
+ peerSession.uiMessages.push({
421
+ role: 'assistant',
422
+ thinking: thinkingBuf,
423
+ text: textBuf,
424
+ changes: changesBuf,
425
+ checkpointId: result.checkpoint?.id || null,
426
+ question: result.pendingQuestion || null,
427
+ commandApproval: result.pendingCommand || null,
428
+ });
429
+ }
430
+ peerSession.liveStatus = result.pendingCommand
431
+ ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
432
+ : result.pendingQuestion
433
+ ? '等待确认方案…'
434
+ : '已完成协作任务';
435
+ } catch (err) {
436
+ peerSession.liveStatus = '任务中断';
437
+ peerSession.uiMessages.push({ role: 'assistant', text: `执行异常:${err.message || '失败'}` });
438
+ } finally {
439
+ peerSession.running = false;
440
+ peerSession.abortController = undefined;
441
+ if (meta.rtInfo.stateDir) {
442
+ saveSessionRecord(meta.rtInfo.stateDir, {
443
+ id: peerSession.key,
444
+ title: peerSession.title,
445
+ persona: peerSession.persona,
446
+ pal: peerSession.pal,
447
+ mode: peerSession.mode,
448
+ execMode: peerSession.execMode,
449
+ archived: false,
450
+ liveStatus: peerSession.liveStatus,
451
+ todos: peerSession.todos,
452
+ calledBy: peerSession.calledBy,
453
+ peerHopCount: peerSession.peerHopCount,
454
+ canvasBaseline: peerSession.canvasBaseline,
455
+ checkpoints: peerSession.checkpoints,
456
+ messages: peerSession.history,
457
+ uiMessages: peerSession.uiMessages,
458
+ pendingQuestion: peerSession.pendingQuestion,
459
+ pendingCommand: peerSession.pendingCommand,
460
+ });
461
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
462
+ }
463
+ }
464
+ }
465
+
466
+ function createPeerCoordinator(targetWorkspace, meta, callerSession) {
467
+ const stateDir = meta.rtInfo.stateDir;
468
+ if (!stateDir) return null;
469
+
470
+ return {
471
+ async spawnPeer({ name, persona = 'qa', task = '' }) {
472
+ const cleanName = String(name || '协作分身').trim().slice(0, 32);
473
+ const id = randomUUID();
474
+ const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
475
+ const peer = ensureMemorySession(targetWorkspace, meta, id, {
476
+ title: cleanName,
477
+ persona: resolved.id,
478
+ mode: persona === 'qa' ? 'qa' : persona === 'auditor' ? 'audit' : 'design',
479
+ execMode: persona === 'auditor' ? 'plan' : 'act',
480
+ });
481
+ peer.title = cleanName;
482
+ peer.pal = resolved.pal || paletteForPersona(persona);
483
+ peer.calledBy = {
484
+ fromId: callerSession.key,
485
+ fromName: callerSession.title || '主会话',
486
+ pal: callerSession.pal || 'blue',
487
+ at: Date.now(),
488
+ };
489
+ const fullTask = [
490
+ resolved.initContext ? `【角色初始上下文】${resolved.initContext}` : '',
491
+ `来自同伴「${callerSession.title || '上游会话'}」的委派任务:\n${task}`,
492
+ ].filter(Boolean).join('\n\n');
493
+
494
+ peer.uiMessages.push({
495
+ role: 'peer_in',
496
+ fromName: callerSession.title || '上游会话',
497
+ fromPal: callerSession.pal || 'blue',
498
+ kind: 'request',
499
+ text: task,
500
+ });
501
+ callerSession.uiMessages.push({
502
+ role: 'peer_out',
503
+ toName: cleanName,
504
+ kind: 'request',
505
+ text: task,
506
+ });
507
+
508
+ saveSessionRecord(stateDir, {
509
+ id: peer.key,
510
+ title: peer.title,
511
+ persona: peer.persona,
512
+ pal: peer.pal,
513
+ mode: peer.mode,
514
+ execMode: peer.execMode,
515
+ archived: false,
516
+ liveStatus: '已就绪,启动中…',
517
+ calledBy: peer.calledBy,
518
+ messages: peer.history,
519
+ uiMessages: peer.uiMessages,
520
+ });
521
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
522
+
523
+ const nextHop = (callerSession.peerHopCount || 0) + 1;
524
+ if (nextHop <= MAX_PEER_HOPS) {
525
+ setImmediate(() => {
526
+ runBackgroundPeerTurn(targetWorkspace, peer, fullTask, { hopCount: nextHop }).catch(() => {});
527
+ });
528
+ }
529
+ return { spawned: true, peerId: id, name: cleanName, persona: resolved.id };
530
+ },
531
+
532
+ async messagePeer({ target, message, kind = 'request' }) {
533
+ const q = String(target || '').trim();
534
+ const msgText = String(message || '').trim().slice(0, 4000);
535
+ if (!q || !msgText) throw new Error('target 与 message 必填。');
536
+
537
+ const all = listSessionRecords(stateDir, { limit: 60, includeArchived: true, autoArchiveHours: 0 });
538
+ const hit = all.find(s => s.id === q || s.title === q || s.title.includes(q));
539
+ if (!hit) {
540
+ return { delivered: false, error: `未找到名为「${q}」的同伴会话,请先使用 spawn_peer 创建。` };
541
+ }
542
+ if (hit.id === callerSession.key) {
543
+ return { delivered: false, error: '不能向当前会话自身发送同伴消息。' };
544
+ }
545
+
546
+ const peer = ensureMemorySession(targetWorkspace, meta, hit.id);
547
+ peer.calledBy = {
548
+ fromId: callerSession.key,
549
+ fromName: callerSession.title || '同伴',
550
+ pal: callerSession.pal || 'blue',
551
+ at: Date.now(),
552
+ };
553
+ peer.incomingPeerMessages.push({
554
+ fromId: callerSession.key,
555
+ fromName: callerSession.title || '同伴',
556
+ kind: kind === 'notify' ? 'notify' : 'request',
557
+ text: msgText,
558
+ });
559
+ peer.uiMessages.push({
560
+ role: 'peer_in',
561
+ fromName: callerSession.title || '同伴',
562
+ fromPal: callerSession.pal || 'blue',
563
+ kind: kind === 'notify' ? 'notify' : 'request',
564
+ text: msgText,
565
+ });
566
+ callerSession.uiMessages.push({
567
+ role: 'peer_out',
568
+ toName: peer.title || hit.title,
569
+ kind: kind === 'notify' ? 'notify' : 'request',
570
+ text: msgText,
571
+ });
572
+
573
+ const nextHop = (callerSession.peerHopCount || 0) + 1;
574
+ const circuitBroken = nextHop > MAX_PEER_HOPS;
575
+ peer.liveStatus = kind === 'notify'
576
+ ? `收到「${callerSession.title || '同伴'}」通知`
577
+ : circuitBroken
578
+ ? `已达 ${MAX_PEER_HOPS} 跳上限,转入静息待命`
579
+ : `收到「${callerSession.title || '同伴'}」呼叫…`;
580
+
581
+ saveSessionRecord(stateDir, {
582
+ id: peer.key,
583
+ title: peer.title || hit.title,
584
+ persona: peer.persona,
585
+ pal: peer.pal,
586
+ mode: peer.mode,
587
+ execMode: peer.execMode,
588
+ archived: false,
589
+ liveStatus: peer.liveStatus,
590
+ calledBy: peer.calledBy,
591
+ peerHopCount: nextHop,
592
+ messages: peer.history,
593
+ uiMessages: peer.uiMessages,
594
+ });
595
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
596
+
597
+ if (kind !== 'notify' && !circuitBroken && !peer.running) {
598
+ setImmediate(() => {
599
+ runBackgroundPeerTurn(targetWorkspace, peer, `请处理同伴「${callerSession.title || '同伴'}」发来的协作请求:\n${msgText}`, { hopCount: nextHop }).catch(() => {});
600
+ });
601
+ }
602
+
603
+ return {
604
+ delivered: true,
605
+ peerId: peer.key,
606
+ peerName: peer.title || hit.title,
607
+ kind,
608
+ circuitBroken,
609
+ };
610
+ },
611
+ };
612
+ }
613
+
216
614
  function handleMeta(req, res, targetWorkspace = workspace) {
217
615
  const host = req.headers.host || '';
218
616
  if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
@@ -230,9 +628,15 @@ export function createAgentHandler({
230
628
  model: meta.model,
231
629
  defaultPersona: meta.defaultPersona,
232
630
  personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
631
+ personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
233
632
  executors: publicExecutorList(meta.executors),
234
633
  runs: listRunRecords(meta.rtInfo.stateDir, 10),
235
- sessions: listSessionRecords(meta.rtInfo.stateDir, 20),
634
+ sessions: listSessionRecords(meta.rtInfo.stateDir, {
635
+ limit: 30,
636
+ includeArchived: false,
637
+ autoArchiveHours: meta.debugConfig.autoArchiveHours,
638
+ runningIds: runningSessionIds(targetWorkspace),
639
+ }),
236
640
  }));
237
641
  }
238
642
 
@@ -242,6 +646,7 @@ export function createAgentHandler({
242
646
  const meta = resolveMeta(targetWorkspace);
243
647
  const stateDir = meta.rtInfo.stateDir;
244
648
  const id = url.searchParams.get('id');
649
+ const includeArchived = url.searchParams.get('includeArchived') === '1' || url.searchParams.get('includeArchived') === 'true';
245
650
  const sendJson = (status, data) => {
246
651
  res.writeHead(status, {
247
652
  'content-type': 'application/json; charset=utf-8',
@@ -250,6 +655,7 @@ export function createAgentHandler({
250
655
  });
251
656
  res.end(JSON.stringify(data));
252
657
  };
658
+
253
659
  if (req.method === 'GET') {
254
660
  if (id) {
255
661
  const record = loadSessionRecord(stateDir, id);
@@ -257,9 +663,115 @@ export function createAgentHandler({
257
663
  sendJson(200, { session: record });
258
664
  return;
259
665
  }
260
- sendJson(200, { sessions: listSessionRecords(stateDir, 30) });
666
+ sendJson(200, {
667
+ sessions: listSessionRecords(stateDir, {
668
+ limit: 50,
669
+ includeArchived,
670
+ autoArchiveHours: meta.debugConfig.autoArchiveHours,
671
+ runningIds: runningSessionIds(targetWorkspace),
672
+ }),
673
+ });
261
674
  return;
262
675
  }
676
+
677
+ if (req.method === 'POST') {
678
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
679
+ throw new DocumentError('会话操作只接受本机同源页面请求。', 403);
680
+ }
681
+ return (async () => {
682
+ const body = await readJsonBody(req, 32 * 1024);
683
+ const act = body?.action;
684
+
685
+ if (act === 'create') {
686
+ const newId = safeSessionId(body.id) || randomUUID();
687
+ const persona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : meta.defaultPersona;
688
+ const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
689
+ const title = String(body.title || resolved.name || '新会话').trim().slice(0, 48);
690
+ const saved = saveSessionRecord(stateDir, {
691
+ id: newId,
692
+ title,
693
+ persona,
694
+ pal: body.pal || resolved.pal || paletteForPersona(persona),
695
+ mode: ['general', 'design', 'qa', 'audit'].includes(body.mode) ? body.mode : 'design',
696
+ execMode: body.execMode === 'plan' ? 'plan' : 'act',
697
+ archived: false,
698
+ liveStatus: '等待指令…',
699
+ messages: [],
700
+ uiMessages: [],
701
+ });
702
+ ensureMemorySession(targetWorkspace, meta, newId, saved);
703
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
704
+ sendJson(201, { session: saved });
705
+ return;
706
+ }
707
+
708
+ if (act === 'archive' || act === 'unarchive') {
709
+ const targetId = safeSessionId(body.id);
710
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
711
+ const updated = archiveSessionRecord(stateDir, targetId, act === 'archive');
712
+ if (!updated) throw new DocumentError('未找到该会话。', 404);
713
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
714
+ sendJson(200, { session: updated });
715
+ return;
716
+ }
717
+
718
+ if (act === 'exec_mode') {
719
+ const targetId = safeSessionId(body.id);
720
+ const nextExec = body.execMode === 'plan' ? 'plan' : 'act';
721
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
722
+ const mem = sessions.get(targetId);
723
+ if (mem) mem.execMode = nextExec;
724
+ const existing = loadSessionRecord(stateDir, targetId);
725
+ if (existing) {
726
+ const updated = saveSessionRecord(stateDir, { ...existing, execMode: nextExec, touchActivity: false });
727
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
728
+ sendJson(200, { session: updated });
729
+ return;
730
+ }
731
+ sendJson(200, { ok: true, execMode: nextExec });
732
+ return;
733
+ }
734
+
735
+ if (act === 'rollback') {
736
+ const targetId = safeSessionId(body.id);
737
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
738
+ const record = loadSessionRecord(stateDir, targetId);
739
+ if (!record || !Array.isArray(record.checkpoints) || !record.checkpoints.length) {
740
+ throw new DocumentError('当前会话暂无可回退的画布快照。', 404);
741
+ }
742
+ const cp = body.checkpointId
743
+ ? record.checkpoints.find(c => c.id === body.checkpointId)
744
+ : record.checkpoints.at(-1);
745
+ if (!cp || !cp.files) throw new DocumentError('未找到指定轮次快照。', 404);
746
+
747
+ const docRoot = meta.rtInfo.documentRoot || targetWorkspace;
748
+ const restoredFiles = [];
749
+ for (const [relFile, snap] of Object.entries(cp.files)) {
750
+ try {
751
+ const full = workspacePath(docRoot, relFile, true);
752
+ if (snap.existed) {
753
+ writeFileSync(full, snap.content, 'utf8');
754
+ } else if (existsSync(full)) {
755
+ unlinkSync(full);
756
+ }
757
+ restoredFiles.push(relFile);
758
+ events?.emit(targetWorkspace, 'doc.updated', { file: relFile, action: 'rollback', label: '已回退上轮画布修改' });
759
+ } catch {}
760
+ }
761
+ if (restoredFiles.length) events?.emit(targetWorkspace, 'workspace.updated', { action: 'rollback' });
762
+ cp.rolledBack = true;
763
+ const mem = sessions.get(targetId);
764
+ if (mem) mem.checkpoints = record.checkpoints;
765
+ saveSessionRecord(stateDir, { ...record, checkpoints: record.checkpoints, liveStatus: '已回退上轮修改' });
766
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
767
+ sendJson(200, { ok: true, restoredFiles, checkpointId: cp.id });
768
+ return;
769
+ }
770
+
771
+ throw new DocumentError('不支持的会话管理动作。', 400);
772
+ })();
773
+ }
774
+
263
775
  if (req.method === 'DELETE') {
264
776
  if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
265
777
  if (!id) throw new DocumentError('缺少会话 id。', 400);
@@ -267,10 +779,111 @@ export function createAgentHandler({
267
779
  if (active) close(active);
268
780
  const deleted = deleteSessionRecord(stateDir, id);
269
781
  if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
782
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
270
783
  sendJson(200, { deleted: true });
271
784
  return;
272
785
  }
273
- throw new DocumentError('会话接口仅支持 GET / DELETE。', 405);
786
+ throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
787
+ }
788
+
789
+ async function handleConfig(req, res, targetWorkspace = workspace) {
790
+ const host = req.headers.host || '';
791
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
792
+ const meta = resolveMeta(targetWorkspace);
793
+ const stateDir = meta.rtInfo.stateDir;
794
+ const sendJson = (status, data) => {
795
+ res.writeHead(status, {
796
+ 'content-type': 'application/json; charset=utf-8',
797
+ 'cache-control': 'no-store',
798
+ 'x-content-type-options': 'nosniff',
799
+ });
800
+ res.end(JSON.stringify(data));
801
+ };
802
+
803
+ const computeSampleTelemetry = cfg => {
804
+ const sample = buildSegmentedPromptContext({
805
+ workspace: targetWorkspace,
806
+ rootWorkspace: workspace,
807
+ documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
808
+ stateDir,
809
+ debugConfig: cfg,
810
+ baseSystemPrompt: resolvePersona('architect', '', cfg.personas).prompt,
811
+ history: [{ role: 'user', content: '示例历史上下文' }, { role: 'assistant', content: '已核对架构契约与幂等锚点。' }],
812
+ userInstruction: '继续推进',
813
+ });
814
+ return sample.telemetry;
815
+ };
816
+
817
+ if (req.method === 'GET') {
818
+ const memory = readWorkspaceMemory(stateDir, workspace);
819
+ sendJson(200, {
820
+ config: meta.debugConfig,
821
+ hasWorkspaceOverride: meta.hasWorkspaceOverride,
822
+ memory,
823
+ telemetry: computeSampleTelemetry(meta.debugConfig),
824
+ });
825
+ return;
826
+ }
827
+
828
+ if (req.method === 'POST') {
829
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
830
+ throw new DocumentError('配置修改只接受本机同源页面请求。', 403);
831
+ }
832
+ const body = await readJsonBody(req, 64 * 1024);
833
+ if (body.action === 'save_memory') {
834
+ const text = saveWorkspaceMemory(stateDir, body.text || '');
835
+ const latest = readAgentDebugConfig(stateDir).config;
836
+ sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, workspace), telemetry: computeSampleTelemetry(latest) });
837
+ return;
838
+ }
839
+ if (body.action === 'save_config') {
840
+ const saved = saveAgentDebugConfig(stateDir, body.patch || {}, { scope: body.scope === 'workspace' ? 'workspace' : 'global' });
841
+ sendJson(200, {
842
+ ok: true,
843
+ config: saved.config,
844
+ hasWorkspaceOverride: saved.hasWorkspaceOverride,
845
+ telemetry: computeSampleTelemetry(saved.config),
846
+ });
847
+ return;
848
+ }
849
+ if (body.action === 'reset') {
850
+ const saved = resetAgentDebugConfig(stateDir, body.section || 'all');
851
+ sendJson(200, {
852
+ ok: true,
853
+ config: saved.config,
854
+ hasWorkspaceOverride: saved.hasWorkspaceOverride,
855
+ telemetry: computeSampleTelemetry(saved.config),
856
+ });
857
+ return;
858
+ }
859
+ if (body.action === 'test_compact') {
860
+ const targetSess = body.sessionId ? loadSessionRecord(stateDir, body.sessionId) : null;
861
+ const srcMsgs = Array.isArray(targetSess?.messages) && targetSess.messages.length
862
+ ? targetSess.messages
863
+ : Array.from({ length: 12 }, (_, idx) => ({
864
+ role: idx % 2 === 0 ? 'user' : 'assistant',
865
+ content: `示例第 ${idx + 1} 轮架构与代码对齐记录(幂等键 idempotencyKey、3000ms 超时重试与账务落库校验)。`.repeat(4),
866
+ }));
867
+ const beforeChars = JSON.stringify(srcMsgs).length;
868
+ const after = compactMessages(srcMsgs, {
869
+ maxChars: Math.max(600, Math.floor(beforeChars * 0.6)),
870
+ thresholdPct: meta.debugConfig.compactThresholdPct,
871
+ compactPrompt: meta.debugConfig.compactPrompt,
872
+ });
873
+ const afterChars = JSON.stringify(after).length;
874
+ sendJson(200, {
875
+ ok: true,
876
+ beforeTurns: srcMsgs.length,
877
+ afterTurns: after.length,
878
+ beforeTokens: Math.ceil(beforeChars / 2.8),
879
+ afterTokens: Math.ceil(afterChars / 2.8),
880
+ });
881
+ return;
882
+ }
883
+ throw new DocumentError('不支持的配置操作。', 400);
884
+ }
885
+
886
+ throw new DocumentError('配置接口仅支持 GET / POST。', 405);
274
887
  }
275
888
 
276
889
  async function handle(req, res, targetWorkspace = workspace) {
@@ -283,6 +896,7 @@ export function createAgentHandler({
283
896
  }
284
897
  const input = await readRequest(req);
285
898
  let session = sessions.get(input.session);
899
+
286
900
  if (input.action === 'cancel' || input.action === 'close') {
287
901
  if (input.action === 'close') {
288
902
  close(session || { key: input.session });
@@ -299,26 +913,34 @@ export function createAgentHandler({
299
913
  return;
300
914
  }
301
915
 
916
+ // 运行中实时插话纠偏(Steer):不打断已完成的工具步骤,排入下一步队首立即生效
917
+ if (input.action === 'steer') {
918
+ if (session?.running && Array.isArray(session.steeringQueue)) {
919
+ session.steeringQueue.push(input.text);
920
+ session.uiMessages.push({ role: 'human', text: input.text, isSteer: true });
921
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
922
+ res.end(JSON.stringify({ ok: true, mode: 'steered' }));
923
+ return;
924
+ }
925
+ throw new DocumentError('当前会话未在运行中,请直接发送消息。', 409);
926
+ }
927
+
302
928
  if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
303
929
  if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
304
930
  const meta = resolveMeta(targetWorkspace);
305
931
  if (!session) {
306
- if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
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
- };
318
- sessions.set(input.session, session);
932
+ if (sessions.size >= 16) throw new DocumentError('Agent 并发会话过多,请归档或关闭部分会话后再试。', 429);
933
+ session = ensureMemorySession(targetWorkspace, meta, input.session, {
934
+ title: input.title,
935
+ persona: input.persona,
936
+ mode: input.mode,
937
+ execMode: input.execMode,
938
+ });
319
939
  }
940
+ if (input.execMode) session.execMode = input.execMode;
320
941
 
321
942
  let resumeToolResult = null;
943
+ let resumeCommandResult = null;
322
944
  if (input.action === 'answer') {
323
945
  const pending = session.pendingQuestion;
324
946
  if (!pending || pending.id !== input.questionId) {
@@ -329,16 +951,34 @@ export function createAgentHandler({
329
951
  choiceId: input.choiceId || '',
330
952
  answer: input.answer,
331
953
  };
954
+ } else if (input.action === 'command_decision') {
955
+ const pendingCmd = session.pendingCommand;
956
+ if (!pendingCmd || pendingCmd.id !== input.commandId) {
957
+ throw new DocumentError('当前没有待审批的命令,或该请求已失效。', 409);
958
+ }
959
+ if (input.decision === 'session_allow') session.commandAutoAllow = true;
960
+ resumeCommandResult = {
961
+ toolCallId: pendingCmd.toolCallId,
962
+ command: pendingCmd.command,
963
+ decision: input.decision,
964
+ };
332
965
  }
333
966
 
334
- const useBuiltin = input.action === 'answer' || (input.action === 'prompt' && (
335
- input.engine === 'builtin' ||
336
- ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
337
- ));
967
+ const useBuiltin = input.action === 'answer'
968
+ || input.action === 'command_decision'
969
+ || (input.action === 'prompt' && (
970
+ input.engine === 'builtin' ||
971
+ ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
972
+ ));
338
973
 
339
974
  session.running = true;
340
975
  session.cancelled = false;
976
+ session.peerHopCount = 0; // 人类主动交互立即清零连续互发计数
977
+ session.activeCardTarget = input.canvas?.file
978
+ ? `${input.canvas.file}${input.canvas.selection?.[0]?.[0] ? '#' + input.canvas.selection[0][0] : ''}`
979
+ : '';
341
980
  clearTimeout(session.idle);
981
+
342
982
  res.writeHead(200, {
343
983
  'content-type': 'application/x-ndjson; charset=utf-8',
344
984
  'cache-control': 'no-store, no-transform',
@@ -356,7 +996,7 @@ export function createAgentHandler({
356
996
  const run = async () => {
357
997
  if (useBuiltin) {
358
998
  session.abortController = new AbortController();
359
- // 若上一轮有未回答的 ask_user,但用户直接发起了新指令,补一条跳过回执避免协议报孤立 tool_call 错误
999
+ // 若上一轮有未回答的 ask_user 或待审命令,但用户直接发起了新指令,自动补齐跳过回执保持消息配对合法
360
1000
  if (input.action === 'prompt' && session.pendingQuestion) {
361
1001
  session.history.push({
362
1002
  role: 'tool',
@@ -371,32 +1011,64 @@ export function createAgentHandler({
371
1011
  }
372
1012
  session.pendingQuestion = null;
373
1013
  }
1014
+ if (input.action === 'prompt' && session.pendingCommand) {
1015
+ session.history.push({
1016
+ role: 'tool',
1017
+ tool_call_id: session.pendingCommand.toolCallId,
1018
+ content: JSON.stringify({ approved: false, skipped: true, reason: '用户发起了新的指令' }),
1019
+ });
1020
+ session.pendingCommand = null;
1021
+ }
1022
+
374
1023
  const activeMode = input.mode || session.mode || 'general';
375
1024
  const activePersona = input.persona || session.persona || meta.defaultPersona;
1025
+ const activeExecMode = input.execMode || session.execMode || 'act';
376
1026
  let thinkingBuf = '';
377
1027
  let textBuf = '';
378
1028
  let changesBuf = [];
1029
+ const incomingPeers = session.incomingPeerMessages.splice(0);
1030
+ const peerCoord = createPeerCoordinator(targetWorkspace, meta, session);
1031
+
379
1032
  const emitBuiltin = ev => {
380
1033
  if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
381
1034
  else if (ev.type === 'text' && ev.text) textBuf += ev.text;
382
1035
  else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
1036
+ else if (ev.type === 'todos' && Array.isArray(ev.todos)) session.todos = ev.todos;
1037
+ else if (ev.type === 'status' && ev.text) {
1038
+ session.liveStatus = ev.text;
1039
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1040
+ }
383
1041
  emit(ev);
384
1042
  };
1043
+
385
1044
  const result = await runVerticalAgent({
386
1045
  workspace: session.workspace,
1046
+ rootWorkspace: workspace,
1047
+ documentRoot: meta.rtInfo.documentRoot || session.workspace,
387
1048
  stateDir: meta.rtInfo.stateDir,
388
1049
  workspaceService,
389
1050
  events,
390
1051
  config: meta.settings,
1052
+ debugConfig: meta.debugConfig,
391
1053
  history: session.history,
1054
+ canvasBaseline: session.canvasBaseline,
1055
+ activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
1056
+ incomingPeerMessages: incomingPeers,
1057
+ peerCoordinator: peerCoord,
392
1058
  resumeToolResult,
1059
+ resumeCommandResult,
1060
+ sessionCommandAutoAllow: session.commandAutoAllow,
1061
+ drainSteering: () => session.steeringQueue.splice(0),
393
1062
  input,
394
1063
  mode: activeMode,
1064
+ execMode: activeExecMode,
395
1065
  persona: activePersona,
1066
+ todos: session.todos,
396
1067
  emit: emitBuiltin,
397
1068
  signal: session.abortController.signal,
398
1069
  fetchImpl,
399
1070
  });
1071
+
400
1072
  if (input.action === 'answer') {
401
1073
  for (let i = session.uiMessages.length - 1; i >= 0; i--) {
402
1074
  if (session.uiMessages[i]?.question?.id === input.questionId) {
@@ -405,6 +1077,9 @@ export function createAgentHandler({
405
1077
  }
406
1078
  }
407
1079
  session.uiMessages.push({ role: 'human', text: input.answer, isAnswer: true });
1080
+ } else if (input.action === 'command_decision') {
1081
+ const labelMap = { allow: '已允许执行', session_allow: '本会话免审允许', deny: '已拒绝命令' };
1082
+ session.uiMessages.push({ role: 'human', text: `${labelMap[input.decision]}:${resumeCommandResult.command}`, isAnswer: true });
408
1083
  } else {
409
1084
  session.uiMessages.push({
410
1085
  role: 'human',
@@ -412,37 +1087,81 @@ export function createAgentHandler({
412
1087
  canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
413
1088
  });
414
1089
  }
415
- if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion) {
1090
+
1091
+ if (result.checkpoint) session.checkpoints.push(result.checkpoint);
1092
+ if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
416
1093
  session.uiMessages.push({
417
1094
  role: 'assistant',
418
1095
  thinking: thinkingBuf,
419
1096
  text: textBuf,
420
1097
  changes: changesBuf,
1098
+ checkpointId: result.checkpoint?.id || null,
421
1099
  question: result.pendingQuestion || null,
1100
+ commandApproval: result.pendingCommand || null,
422
1101
  });
423
1102
  }
1103
+
424
1104
  session.history = Array.isArray(result.conversation) ? result.conversation : session.history;
1105
+ session.todos = Array.isArray(result.todos) ? result.todos : session.todos;
1106
+ session.canvasBaseline = result.nextBaseline || session.canvasBaseline;
425
1107
  session.pendingQuestion = result.pendingQuestion || null;
1108
+ session.pendingCommand = result.pendingCommand || null;
426
1109
  session.persona = activePersona;
1110
+ session.pal = paletteForPersona(activePersona);
427
1111
  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
- });
1112
+ session.execMode = activeExecMode;
1113
+ if (!session.title) session.title = (input.title || input.text || input.answer || '新会话').slice(0, 48);
1114
+ session.liveStatus = result.pendingCommand
1115
+ ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
1116
+ : result.pendingQuestion
1117
+ ? '等待确认方案…'
1118
+ : (changesBuf[0]?.label || '已完成');
1119
+
1120
+ if (meta.rtInfo.stateDir) {
1121
+ saveSessionRecord(meta.rtInfo.stateDir, {
1122
+ id: session.key,
1123
+ title: session.title,
1124
+ persona: session.persona,
1125
+ pal: session.pal,
1126
+ mode: session.mode,
1127
+ execMode: session.execMode,
1128
+ archived: false,
1129
+ liveStatus: session.liveStatus,
1130
+ todos: session.todos,
1131
+ calledBy: null,
1132
+ canvasBaseline: session.canvasBaseline,
1133
+ checkpoints: session.checkpoints,
1134
+ messages: session.history,
1135
+ uiMessages: session.uiMessages,
1136
+ pendingQuestion: session.pendingQuestion,
1137
+ pendingCommand: session.pendingCommand,
1138
+ });
1139
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1140
+ }
438
1141
  return { stopReason: result.stopReason };
439
1142
  }
440
1143
 
1144
+ // 外部 ACP 执行器(dispatch / 默认 ACP 对话):同样接入底部会话胶囊持久化,但不接管其内部压缩
1145
+ let acpTextBuf = '';
1146
+ const prevEmit = session.emit;
1147
+ session.emit = ev => {
1148
+ if (ev.type === 'text' && ev.text) acpTextBuf += ev.text;
1149
+ else if (ev.type === 'tool' && ev.title) {
1150
+ session.liveStatus = `调用 ${String(ev.title).split('.').pop()}…`;
1151
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1152
+ }
1153
+ prevEmit?.(ev);
1154
+ };
1155
+
441
1156
  if (input.action === 'dispatch') {
442
1157
  const chosen = input.executorId
443
1158
  ? meta.executors.find(item => item.id === input.executorId)
444
1159
  : meta.executors[0];
445
1160
  if (!chosen) throw new Error('找不到指定的 ACP 执行器插件:' + (input.executorId || '默认'));
1161
+ if (!session.title) session.title = chosen.name;
1162
+ session.liveStatus = `${chosen.name} 执行中…`;
1163
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1164
+
446
1165
  const runRec = createRunRecord(meta.rtInfo.stateDir, {
447
1166
  kind: 'dispatch',
448
1167
  mode: 'implement',
@@ -460,7 +1179,6 @@ export function createAgentHandler({
460
1179
  label: `ACP 派发开发中 · ${chosen.name}`,
461
1180
  });
462
1181
 
463
- // 如果当前会话绑定的不是这个执行器,重新建立对应执行器的 ACP 连接
464
1182
  if (session.agent && session.executorId !== chosen.id) {
465
1183
  session.agent.dispose();
466
1184
  session.agent = null;
@@ -495,19 +1213,61 @@ export function createAgentHandler({
495
1213
  nodes: input.canvas?.selection || [],
496
1214
  label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
497
1215
  });
1216
+ session.uiMessages.push(
1217
+ { role: 'human', text: `[派发 ${chosen.name}] ${input.text || '按画布规格实现'}` },
1218
+ ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1219
+ );
1220
+ session.liveStatus = `${chosen.name} 已完成`;
1221
+ if (meta.rtInfo.stateDir) {
1222
+ saveSessionRecord(meta.rtInfo.stateDir, {
1223
+ id: session.key,
1224
+ title: session.title || chosen.name,
1225
+ persona: session.persona,
1226
+ pal: 'teal',
1227
+ mode: session.mode,
1228
+ execMode: session.execMode,
1229
+ archived: false,
1230
+ liveStatus: session.liveStatus,
1231
+ uiMessages: session.uiMessages,
1232
+ });
1233
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1234
+ }
498
1235
  return response;
499
1236
  }
500
1237
 
501
- // 默认 ACP 对话模式(完全兼容既有行为)
1238
+ // 默认 ACP 对话模式
502
1239
  if (!session.agent) await connectAcp(session);
503
1240
  if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
1241
+ if (!session.title) session.title = (input.title || input.text || 'ACP 会话').slice(0, 48);
1242
+ session.liveStatus = '正在生成…';
1243
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
504
1244
  emit({ type: 'status', text: '正在生成' });
505
1245
  const prompt = promptBlocks(session.workspace, input);
506
1246
  if (!session.started && session.hasMcp) {
507
1247
  prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
508
1248
  session.started = true;
509
1249
  }
510
- return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1250
+ const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1251
+ session.uiMessages.push(
1252
+ { role: 'human', text: input.text },
1253
+ ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1254
+ );
1255
+ session.liveStatus = '已完成';
1256
+ if (meta.rtInfo.stateDir) {
1257
+ saveSessionRecord(meta.rtInfo.stateDir, {
1258
+ id: session.key,
1259
+ title: session.title,
1260
+ persona: session.persona,
1261
+ pal: session.pal,
1262
+ mode: session.mode,
1263
+ execMode: session.execMode,
1264
+ archived: false,
1265
+ liveStatus: session.liveStatus,
1266
+ uiMessages: session.uiMessages,
1267
+ });
1268
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1269
+ }
1270
+ return response;
511
1271
  };
512
1272
 
513
1273
  try {
@@ -527,14 +1287,22 @@ export function createAgentHandler({
527
1287
  session.stopTimer = undefined;
528
1288
  session.abortController = undefined;
529
1289
  session.running = false;
1290
+ session.activeCardTarget = '';
530
1291
  session.emit = session.fail = undefined;
531
1292
  res.off('close', onDisconnect);
532
1293
  res.end();
1294
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
533
1295
  if (sessions.get(session.key) === session) {
534
1296
  session.idle = setTimeout(() => close(session), idleMs);
535
1297
  session.idle.unref();
536
1298
  }
537
1299
  }
538
1300
  }
539
- return { handle, handleMeta, handleSessions, close: () => { for (const session of sessions.values()) close(session); } };
1301
+ return {
1302
+ handle,
1303
+ handleMeta,
1304
+ handleSessions,
1305
+ handleConfig,
1306
+ close: () => { for (const session of sessions.values()) close(session); },
1307
+ };
540
1308
  }