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.
@@ -1,32 +1,71 @@
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
- import { resolveProviderCredentials } from '../agent/providers/index.js';
11
20
  import {
12
- BUILTIN_PERSONAS, deleteSessionRecord, listSessionRecords, loadSessionRecord, saveSessionRecord,
21
+ PROVIDER_PRESETS,
22
+ fetchProviderModels,
23
+ getProviderPreset,
24
+ listConfiguredModels,
25
+ maskApiKey,
26
+ resolveProviderCredentials,
27
+ } from '../agent/providers/index.js';
28
+ import {
29
+ archiveSessionRecord,
30
+ BUILTIN_PERSONAS,
31
+ compactMessages,
32
+ deleteSessionRecord,
33
+ listSessionRecords,
34
+ loadSessionRecord,
35
+ paletteForPersona,
36
+ PERSONA_TEMPLATES,
37
+ resolvePersona,
38
+ safeSessionId,
39
+ saveSessionRecord,
13
40
  } from '../agent/sessions.js';
14
41
  import { runVerticalAgent } from '../agent/runtime.js';
15
42
 
16
43
  const idleMs = 15 * 60_000;
17
44
  const turnMs = 5 * 60_000;
18
- const sessionId = z.uuid();
19
- const personaSchema = z.enum(['architect', 'qa', 'auditor', 'custom']);
45
+ const MAX_PEER_HOPS = 8;
46
+ const sessionId = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
47
+ const personaSchema = z.enum(['architect', 'coder', 'qa', 'auditor', 'custom']);
48
+ const execModeSchema = z.enum(['plan', 'act']);
49
+ const canvasObjectItemSchema = z.strictObject({
50
+ id: z.string().min(1).max(120),
51
+ kind: z.string().min(1).max(60),
52
+ title: z.string().max(160),
53
+ pluginId: z.string().max(120).optional(),
54
+ subtarget: z.string().max(160).optional(),
55
+ });
20
56
  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),
57
+ file: z.string().max(1500).optional(),
58
+ revision: z.string().regex(/^[a-f0-9]{64}$/).optional(),
59
+ selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200).default([]),
60
+ objectSelection: z.array(canvasObjectItemSchema).max(100).optional(),
24
61
  });
25
62
  const requestSchema = z.discriminatedUnion('action', [
26
63
  z.strictObject({
27
64
  action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
65
+ title: z.string().max(60).optional(),
28
66
  viewId: z.uuid().optional(),
29
67
  mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
68
+ execMode: execModeSchema.optional(),
30
69
  persona: personaSchema.optional(),
31
70
  engine: z.enum(['auto', 'builtin', 'acp']).optional(),
32
71
  canvas: canvasSchema.optional(),
@@ -38,9 +77,24 @@ const requestSchema = z.discriminatedUnion('action', [
38
77
  answer: z.string().trim().min(1).max(12_000),
39
78
  viewId: z.uuid().optional(),
40
79
  mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
80
+ execMode: execModeSchema.optional(),
41
81
  persona: personaSchema.optional(),
42
82
  canvas: canvasSchema.optional(),
43
83
  }),
84
+ z.strictObject({
85
+ action: z.literal('command_decision'), session: sessionId,
86
+ commandId: z.string().min(1).max(128),
87
+ decision: z.enum(['allow', 'session_allow', 'deny']),
88
+ viewId: z.uuid().optional(),
89
+ mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
90
+ execMode: execModeSchema.optional(),
91
+ persona: personaSchema.optional(),
92
+ canvas: canvasSchema.optional(),
93
+ }),
94
+ z.strictObject({
95
+ action: z.literal('steer'), session: sessionId,
96
+ text: z.string().trim().min(1).max(4_000),
97
+ }),
44
98
  z.strictObject({
45
99
  action: z.literal('dispatch'), session: sessionId,
46
100
  executorId: z.string().min(1).max(128).optional(),
@@ -51,15 +105,20 @@ const requestSchema = z.discriminatedUnion('action', [
51
105
  z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
52
106
  ]);
53
107
 
54
- async function readRequest(req) {
108
+ async function readJsonBody(req, maxBytes = 96 * 1024) {
55
109
  const chunks = [];
56
110
  let bytes = 0;
57
111
  for await (const chunk of req) {
58
112
  bytes += chunk.length;
59
- if (bytes > 96 * 1024) throw new DocumentError('发送内容过长。', 413);
113
+ if (bytes > maxBytes) throw new DocumentError('发送内容过长。', 413);
60
114
  chunks.push(chunk);
61
115
  }
62
- const parsed = requestSchema.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
116
+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
117
+ }
118
+
119
+ async function readRequest(req) {
120
+ const raw = await readJsonBody(req, 96 * 1024);
121
+ const parsed = requestSchema.safeParse(raw);
63
122
  if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
64
123
  return parsed.data;
65
124
  }
@@ -68,10 +127,15 @@ function promptBlocks(workspace, input) {
68
127
  const context = {
69
128
  workspace,
70
129
  ...(input.viewId && { viewId: input.viewId }),
71
- ...(input.canvas && { file: input.canvas.file, revision: input.canvas.revision, selection: input.canvas.selection }),
130
+ ...(input.canvas && {
131
+ file: input.canvas.file,
132
+ revision: input.canvas.revision,
133
+ selection: input.canvas.selection,
134
+ ...(input.canvas.objectSelection?.length ? { objectSelection: input.canvas.objectSelection } : {}),
135
+ }),
72
136
  };
73
137
  return [
74
- { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径。' },
138
+ { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径,objectSelection 是选中的多实例画布组件或子区域靶点。' },
75
139
  { type: 'text', text: JSON.stringify(context) },
76
140
  { type: 'text', text: '用户指令:\n' + input.text },
77
141
  ];
@@ -95,8 +159,6 @@ function startAgent({ workspace, command, args, env, mcpName, emit, closed }) {
95
159
  proc.on('exit', code => closed(new Error('ACP 进程已退出' + (code ? '(退出码 ' + code + ')' : '') + '。请检查启动命令和登录状态。')));
96
160
  const connection = client()
97
161
  .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
162
  const option = params.options.find(option => option.kind === 'allow_once');
101
163
  if (option && params._meta?.is_mcp_tool_approval === true &&
102
164
  cladoCalls.get(params.toolCall.toolCallId) === params.sessionId) {
@@ -137,6 +199,7 @@ export function createAgentHandler({
137
199
  args = [],
138
200
  resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
139
201
  resolveSettings = null,
202
+ saveSettings = null,
140
203
  resolveRuntimeInfo = null,
141
204
  workspaceService = null,
142
205
  events = null,
@@ -150,6 +213,71 @@ export function createAgentHandler({
150
213
  return { ...launch, ...base };
151
214
  };
152
215
 
216
+ function buildLlmState(settings = {}) {
217
+ const creds = resolveProviderCredentials(settings);
218
+ const profiles = {};
219
+ for (const preset of PROVIDER_PRESETS) {
220
+ const raw = settings.providers?.[preset.id] || {};
221
+ const isLegacyMatch = !settings.providers && (settings.providerId || 'openai') === preset.id;
222
+ const key = raw.apiKey ?? (isLegacyMatch ? settings.apiKey : '');
223
+ profiles[preset.id] = {
224
+ label: raw.label || preset.label,
225
+ protocol: raw.protocol || preset.protocol,
226
+ baseUrl: raw.baseUrl || (isLegacyMatch ? settings.baseUrl : '') || preset.defaultBaseUrl,
227
+ model: raw.model || (isLegacyMatch ? settings.model : '') || preset.defaultModel,
228
+ models: Array.isArray(raw.models) && raw.models.length ? raw.models : preset.models,
229
+ hasApiKey: Boolean(String(key || '').trim()),
230
+ maskedKey: maskApiKey(key),
231
+ requiresKey: preset.requiresKey !== false,
232
+ };
233
+ }
234
+ return {
235
+ configured: creds.configured,
236
+ providerId: creds.providerId,
237
+ providerLabel: creds.providerLabel,
238
+ protocol: creds.provider,
239
+ baseUrl: creds.baseUrl,
240
+ model: creds.model,
241
+ hasApiKey: creds.hasApiKey,
242
+ presets: PROVIDER_PRESETS,
243
+ profiles,
244
+ quickModels: listConfiguredModels(settings),
245
+ acpCommand: settings.command || 'zcode-acp-server',
246
+ acpArgs: Array.isArray(settings.args) ? settings.args : [],
247
+ };
248
+ }
249
+
250
+ function runningSessionIds(targetWorkspace) {
251
+ const set = new Set();
252
+ for (const s of sessions.values()) {
253
+ if (s.running && s.workspace === targetWorkspace) set.add(s.key);
254
+ }
255
+ return set;
256
+ }
257
+
258
+ function activePeerLocksFor(targetWorkspace, excludeSessionKey) {
259
+ const locks = [];
260
+ for (const s of sessions.values()) {
261
+ if (s.running && s.workspace === targetWorkspace && s.key !== excludeSessionKey && s.activeCardTarget) {
262
+ locks.push({ peerId: s.key, peerName: s.title || '同伴', target: s.activeCardTarget });
263
+ }
264
+ }
265
+ return locks;
266
+ }
267
+
268
+ function emitSessionSync(targetWorkspace, stateDir, autoArchiveHours = 24) {
269
+ if (!events || !stateDir) return;
270
+ try {
271
+ const list = listSessionRecords(stateDir, {
272
+ limit: 40,
273
+ includeArchived: false,
274
+ autoArchiveHours,
275
+ runningIds: runningSessionIds(targetWorkspace),
276
+ });
277
+ events.emit(targetWorkspace, 'agent.sessions', { sessions: list });
278
+ } catch {}
279
+ }
280
+
153
281
  function close(session, error) {
154
282
  if (sessions.get(session.key) !== session) return;
155
283
  sessions.delete(session.key);
@@ -188,32 +316,347 @@ export function createAgentHandler({
188
316
  function resolveMeta(targetWorkspace) {
189
317
  const settings = readSettings();
190
318
  const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
319
+ const debugBundle = readAgentDebugConfig(rtInfo.stateDir);
191
320
  const executors = discoverExecutors({
192
321
  stateDir: rtInfo.stateDir,
193
322
  settings,
194
323
  pluginDescriptors: rtInfo.pluginDescriptors || [],
195
324
  });
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');
325
+ const llm = buildLlmState(settings);
326
+ const builtinConfigured = Boolean(llm.configured);
327
+ // Clado 产品定位为原生 Agent 优先:只要挂载了工作区设置(resolveSettings),主引擎默认恒为 builtin,
328
+ // 仅当显式强制设为 acp(或纯 ACP 单元测试未提供 resolveSettings)时才退回 acp。
329
+ const activeEngine = !resolveSettings
330
+ ? (builtinConfigured ? 'builtin' : 'acp')
331
+ : (settings.mode === 'acp' ? 'acp' : 'builtin');
204
332
  return {
205
333
  settings,
334
+ llm,
335
+ debugConfig: debugBundle.config,
336
+ hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
206
337
  rtInfo,
207
338
  executors,
208
339
  builtinConfigured,
209
340
  activeEngine,
210
- provider: creds.provider,
211
- model: creds.model,
341
+ provider: llm.protocol,
342
+ providerId: llm.providerId,
343
+ providerLabel: llm.providerLabel,
344
+ model: llm.model,
212
345
  defaultPersona: settings.persona || 'architect',
213
346
  };
214
347
  }
215
348
 
216
- function handleMeta(req, res, targetWorkspace = workspace) {
349
+ function ensureMemorySession(targetWorkspace, meta, id, defaults = {}) {
350
+ let session = sessions.get(id);
351
+ if (!session) {
352
+ const saved = loadSessionRecord(meta.rtInfo.stateDir, id);
353
+ const persona = defaults.persona || saved?.persona || meta.defaultPersona;
354
+ session = {
355
+ key: id,
356
+ workspace: targetWorkspace,
357
+ title: defaults.title || saved?.title || '',
358
+ persona,
359
+ pal: saved?.pal || paletteForPersona(persona),
360
+ engine: (defaults.engine || saved?.engine) === 'acp' ? 'acp' : 'builtin',
361
+ mode: defaults.mode || saved?.mode || 'design',
362
+ execMode: defaults.execMode || saved?.execMode || 'act',
363
+ liveStatus: saved?.liveStatus || '',
364
+ todos: Array.isArray(saved?.todos) ? saved.todos : [],
365
+ calledBy: saved?.calledBy || null,
366
+ peerHopCount: saved?.peerHopCount || 0,
367
+ canvasBaseline: saved?.canvasBaseline || null,
368
+ checkpoints: Array.isArray(saved?.checkpoints) ? saved.checkpoints : [],
369
+ history: Array.isArray(saved?.messages) ? saved.messages : [],
370
+ uiMessages: Array.isArray(saved?.uiMessages) ? saved.uiMessages : [],
371
+ pendingQuestion: saved?.pendingQuestion || null,
372
+ pendingCommand: saved?.pendingCommand || null,
373
+ incomingPeerMessages: [],
374
+ steeringQueue: [],
375
+ commandAutoAllow: false,
376
+ };
377
+ sessions.set(id, session);
378
+ }
379
+ return session;
380
+ }
381
+
382
+ /**
383
+ * 后台异步唤醒平级同伴会话执行一轮任务(用于 spawn_peer / message_peer request)。
384
+ */
385
+ async function runBackgroundPeerTurn(targetWorkspace, peerSession, taskText, { hopCount = 1 } = {}) {
386
+ if (peerSession.running) return;
387
+ const meta = resolveMeta(targetWorkspace);
388
+ if (!meta.builtinConfigured) return;
389
+
390
+ peerSession.running = true;
391
+ peerSession.cancelled = false;
392
+ peerSession.peerHopCount = hopCount;
393
+ peerSession.abortController = new AbortController();
394
+ peerSession.liveStatus = '收到呼叫,正在处理…';
395
+
396
+ if (meta.rtInfo.stateDir) {
397
+ saveSessionRecord(meta.rtInfo.stateDir, {
398
+ id: peerSession.key,
399
+ title: peerSession.title,
400
+ persona: peerSession.persona,
401
+ pal: peerSession.pal,
402
+ mode: peerSession.mode,
403
+ execMode: peerSession.execMode,
404
+ archived: false,
405
+ liveStatus: peerSession.liveStatus,
406
+ todos: peerSession.todos,
407
+ calledBy: peerSession.calledBy,
408
+ peerHopCount: peerSession.peerHopCount,
409
+ messages: peerSession.history,
410
+ uiMessages: peerSession.uiMessages,
411
+ });
412
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
413
+ }
414
+
415
+ let thinkingBuf = '';
416
+ let textBuf = '';
417
+ let changesBuf = [];
418
+ const peerCoord = createPeerCoordinator(targetWorkspace, meta, peerSession);
419
+
420
+ try {
421
+ const incoming = peerSession.incomingPeerMessages.splice(0);
422
+ const result = await runVerticalAgent({
423
+ workspace: targetWorkspace,
424
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
425
+ documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
426
+ stateDir: meta.rtInfo.stateDir,
427
+ workspaceService,
428
+ events,
429
+ config: meta.settings,
430
+ debugConfig: meta.debugConfig,
431
+ history: peerSession.history,
432
+ canvasBaseline: peerSession.canvasBaseline,
433
+ activePeerLocks: activePeerLocksFor(targetWorkspace, peerSession.key),
434
+ incomingPeerMessages: incoming,
435
+ peerCoordinator: peerCoord,
436
+ sessionCommandAutoAllow: peerSession.commandAutoAllow,
437
+ drainSteering: () => peerSession.steeringQueue.splice(0),
438
+ input: { text: taskText },
439
+ mode: peerSession.mode,
440
+ execMode: peerSession.execMode,
441
+ persona: peerSession.persona,
442
+ todos: peerSession.todos,
443
+ signal: peerSession.abortController.signal,
444
+ fetchImpl,
445
+ emit: ev => {
446
+ if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
447
+ else if (ev.type === 'text' && ev.text) textBuf += ev.text;
448
+ else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
449
+ else if (ev.type === 'todos' && Array.isArray(ev.todos)) peerSession.todos = ev.todos;
450
+ else if (ev.type === 'status' && ev.text) {
451
+ peerSession.liveStatus = ev.text;
452
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
453
+ }
454
+ },
455
+ });
456
+
457
+ peerSession.history = Array.isArray(result.conversation) ? result.conversation : peerSession.history;
458
+ peerSession.todos = Array.isArray(result.todos) ? result.todos : peerSession.todos;
459
+ peerSession.canvasBaseline = result.nextBaseline || peerSession.canvasBaseline;
460
+ peerSession.pendingQuestion = result.pendingQuestion || null;
461
+ peerSession.pendingCommand = result.pendingCommand || null;
462
+ if (result.checkpoint) peerSession.checkpoints.push(result.checkpoint);
463
+
464
+ if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
465
+ peerSession.uiMessages.push({
466
+ role: 'assistant',
467
+ thinking: thinkingBuf,
468
+ text: textBuf,
469
+ changes: changesBuf,
470
+ checkpointId: result.checkpoint?.id || null,
471
+ question: result.pendingQuestion || null,
472
+ commandApproval: result.pendingCommand || null,
473
+ });
474
+ }
475
+ peerSession.liveStatus = result.pendingCommand
476
+ ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
477
+ : result.pendingQuestion
478
+ ? '等待确认方案…'
479
+ : '已完成协作任务';
480
+ } catch (err) {
481
+ peerSession.liveStatus = '任务中断';
482
+ peerSession.uiMessages.push({ role: 'assistant', text: `执行异常:${err.message || '失败'}` });
483
+ } finally {
484
+ peerSession.running = false;
485
+ peerSession.abortController = undefined;
486
+ if (meta.rtInfo.stateDir) {
487
+ saveSessionRecord(meta.rtInfo.stateDir, {
488
+ id: peerSession.key,
489
+ title: peerSession.title,
490
+ persona: peerSession.persona,
491
+ pal: peerSession.pal,
492
+ mode: peerSession.mode,
493
+ execMode: peerSession.execMode,
494
+ archived: false,
495
+ liveStatus: peerSession.liveStatus,
496
+ todos: peerSession.todos,
497
+ calledBy: peerSession.calledBy,
498
+ peerHopCount: peerSession.peerHopCount,
499
+ canvasBaseline: peerSession.canvasBaseline,
500
+ checkpoints: peerSession.checkpoints,
501
+ messages: peerSession.history,
502
+ uiMessages: peerSession.uiMessages,
503
+ pendingQuestion: peerSession.pendingQuestion,
504
+ pendingCommand: peerSession.pendingCommand,
505
+ });
506
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
507
+ }
508
+ }
509
+ }
510
+
511
+ function createPeerCoordinator(targetWorkspace, meta, callerSession) {
512
+ const stateDir = meta.rtInfo.stateDir;
513
+ if (!stateDir) return null;
514
+
515
+ return {
516
+ async spawnPeer({ name, persona = 'qa', task = '' }) {
517
+ const cleanName = String(name || '协作分身').trim().slice(0, 32);
518
+ const id = randomUUID();
519
+ const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
520
+ const peer = ensureMemorySession(targetWorkspace, meta, id, {
521
+ title: cleanName,
522
+ persona: resolved.id,
523
+ mode: persona === 'qa' ? 'qa' : persona === 'auditor' ? 'audit' : 'design',
524
+ execMode: persona === 'auditor' ? 'plan' : 'act',
525
+ });
526
+ peer.title = cleanName;
527
+ peer.pal = resolved.pal || paletteForPersona(persona);
528
+ peer.calledBy = {
529
+ fromId: callerSession.key,
530
+ fromName: callerSession.title || '主会话',
531
+ pal: callerSession.pal || 'blue',
532
+ at: Date.now(),
533
+ };
534
+ const fullTask = [
535
+ resolved.initContext ? `【角色初始上下文】${resolved.initContext}` : '',
536
+ `来自同伴「${callerSession.title || '上游会话'}」的委派任务:\n${task}`,
537
+ ].filter(Boolean).join('\n\n');
538
+
539
+ peer.uiMessages.push({
540
+ role: 'peer_in',
541
+ fromName: callerSession.title || '上游会话',
542
+ fromPal: callerSession.pal || 'blue',
543
+ kind: 'request',
544
+ text: task,
545
+ });
546
+ callerSession.uiMessages.push({
547
+ role: 'peer_out',
548
+ toName: cleanName,
549
+ kind: 'request',
550
+ text: task,
551
+ });
552
+
553
+ saveSessionRecord(stateDir, {
554
+ id: peer.key,
555
+ title: peer.title,
556
+ persona: peer.persona,
557
+ pal: peer.pal,
558
+ mode: peer.mode,
559
+ execMode: peer.execMode,
560
+ archived: false,
561
+ liveStatus: '已就绪,启动中…',
562
+ calledBy: peer.calledBy,
563
+ messages: peer.history,
564
+ uiMessages: peer.uiMessages,
565
+ });
566
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
567
+
568
+ const nextHop = (callerSession.peerHopCount || 0) + 1;
569
+ if (nextHop <= MAX_PEER_HOPS) {
570
+ setImmediate(() => {
571
+ runBackgroundPeerTurn(targetWorkspace, peer, fullTask, { hopCount: nextHop }).catch(() => {});
572
+ });
573
+ }
574
+ return { spawned: true, peerId: id, name: cleanName, persona: resolved.id };
575
+ },
576
+
577
+ async messagePeer({ target, message, kind = 'request' }) {
578
+ const q = String(target || '').trim();
579
+ const msgText = String(message || '').trim().slice(0, 4000);
580
+ if (!q || !msgText) throw new Error('target 与 message 必填。');
581
+
582
+ const all = listSessionRecords(stateDir, { limit: 60, includeArchived: true, autoArchiveHours: 0 });
583
+ const hit = all.find(s => s.id === q || s.title === q || s.title.includes(q));
584
+ if (!hit) {
585
+ return { delivered: false, error: `未找到名为「${q}」的同伴会话,请先使用 spawn_peer 创建。` };
586
+ }
587
+ if (hit.id === callerSession.key) {
588
+ return { delivered: false, error: '不能向当前会话自身发送同伴消息。' };
589
+ }
590
+
591
+ const peer = ensureMemorySession(targetWorkspace, meta, hit.id);
592
+ peer.calledBy = {
593
+ fromId: callerSession.key,
594
+ fromName: callerSession.title || '同伴',
595
+ pal: callerSession.pal || 'blue',
596
+ at: Date.now(),
597
+ };
598
+ peer.incomingPeerMessages.push({
599
+ fromId: callerSession.key,
600
+ fromName: callerSession.title || '同伴',
601
+ kind: kind === 'notify' ? 'notify' : 'request',
602
+ text: msgText,
603
+ });
604
+ peer.uiMessages.push({
605
+ role: 'peer_in',
606
+ fromName: callerSession.title || '同伴',
607
+ fromPal: callerSession.pal || 'blue',
608
+ kind: kind === 'notify' ? 'notify' : 'request',
609
+ text: msgText,
610
+ });
611
+ callerSession.uiMessages.push({
612
+ role: 'peer_out',
613
+ toName: peer.title || hit.title,
614
+ kind: kind === 'notify' ? 'notify' : 'request',
615
+ text: msgText,
616
+ });
617
+
618
+ const nextHop = (callerSession.peerHopCount || 0) + 1;
619
+ const circuitBroken = nextHop > MAX_PEER_HOPS;
620
+ peer.liveStatus = kind === 'notify'
621
+ ? `收到「${callerSession.title || '同伴'}」通知`
622
+ : circuitBroken
623
+ ? `已达 ${MAX_PEER_HOPS} 跳上限,转入静息待命`
624
+ : `收到「${callerSession.title || '同伴'}」呼叫…`;
625
+
626
+ saveSessionRecord(stateDir, {
627
+ id: peer.key,
628
+ title: peer.title || hit.title,
629
+ persona: peer.persona,
630
+ pal: peer.pal,
631
+ mode: peer.mode,
632
+ execMode: peer.execMode,
633
+ archived: false,
634
+ liveStatus: peer.liveStatus,
635
+ calledBy: peer.calledBy,
636
+ peerHopCount: nextHop,
637
+ messages: peer.history,
638
+ uiMessages: peer.uiMessages,
639
+ });
640
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
641
+
642
+ if (kind !== 'notify' && !circuitBroken && !peer.running) {
643
+ setImmediate(() => {
644
+ runBackgroundPeerTurn(targetWorkspace, peer, `请处理同伴「${callerSession.title || '同伴'}」发来的协作请求:\n${msgText}`, { hopCount: nextHop }).catch(() => {});
645
+ });
646
+ }
647
+
648
+ return {
649
+ delivered: true,
650
+ peerId: peer.key,
651
+ peerName: peer.title || hit.title,
652
+ kind,
653
+ circuitBroken,
654
+ };
655
+ },
656
+ };
657
+ }
658
+
659
+ function handleMeta(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
217
660
  const host = req.headers.host || '';
218
661
  if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
219
662
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
@@ -226,22 +669,33 @@ export function createAgentHandler({
226
669
  res.end(JSON.stringify({
227
670
  engine: meta.activeEngine,
228
671
  provider: meta.provider,
672
+ providerId: meta.providerId,
673
+ providerLabel: meta.providerLabel,
229
674
  builtinConfigured: meta.builtinConfigured,
230
675
  model: meta.model,
676
+ llm: meta.llm,
677
+ mcpUrl: mcpUrl(),
231
678
  defaultPersona: meta.defaultPersona,
232
679
  personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
680
+ personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
233
681
  executors: publicExecutorList(meta.executors),
234
682
  runs: listRunRecords(meta.rtInfo.stateDir, 10),
235
- sessions: listSessionRecords(meta.rtInfo.stateDir, 20),
683
+ sessions: listSessionRecords(meta.rtInfo.stateDir, {
684
+ limit: 30,
685
+ includeArchived: false,
686
+ autoArchiveHours: meta.debugConfig.autoArchiveHours,
687
+ runningIds: runningSessionIds(targetWorkspace),
688
+ }),
236
689
  }));
237
690
  }
238
691
 
239
- function handleSessions(req, res, url, targetWorkspace = workspace) {
692
+ function handleSessions(req, res, url, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
240
693
  const host = req.headers.host || '';
241
694
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
242
695
  const meta = resolveMeta(targetWorkspace);
243
696
  const stateDir = meta.rtInfo.stateDir;
244
697
  const id = url.searchParams.get('id');
698
+ const includeArchived = url.searchParams.get('includeArchived') === '1' || url.searchParams.get('includeArchived') === 'true';
245
699
  const sendJson = (status, data) => {
246
700
  res.writeHead(status, {
247
701
  'content-type': 'application/json; charset=utf-8',
@@ -250,6 +704,7 @@ export function createAgentHandler({
250
704
  });
251
705
  res.end(JSON.stringify(data));
252
706
  };
707
+
253
708
  if (req.method === 'GET') {
254
709
  if (id) {
255
710
  const record = loadSessionRecord(stateDir, id);
@@ -257,9 +712,159 @@ export function createAgentHandler({
257
712
  sendJson(200, { session: record });
258
713
  return;
259
714
  }
260
- sendJson(200, { sessions: listSessionRecords(stateDir, 30) });
715
+ sendJson(200, {
716
+ sessions: listSessionRecords(stateDir, {
717
+ limit: 50,
718
+ includeArchived,
719
+ autoArchiveHours: meta.debugConfig.autoArchiveHours,
720
+ runningIds: runningSessionIds(targetWorkspace),
721
+ }),
722
+ });
261
723
  return;
262
724
  }
725
+
726
+ if (req.method === 'POST') {
727
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
728
+ throw new DocumentError('会话操作只接受本机同源页面请求。', 403);
729
+ }
730
+ return (async () => {
731
+ const body = await readJsonBody(req, 32 * 1024);
732
+ const act = body?.action;
733
+
734
+ if (act === 'create') {
735
+ const newId = safeSessionId(body.id) || randomUUID();
736
+ const isAcpSub = body.engine === 'acp';
737
+ const persona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : meta.defaultPersona;
738
+ const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
739
+ const defaultTitle = isAcpSub ? 'ACP 子代理' : (resolved.name || '新会话');
740
+ const title = String(body.title || defaultTitle).trim().slice(0, 48);
741
+ const saved = saveSessionRecord(stateDir, {
742
+ id: newId,
743
+ title,
744
+ persona,
745
+ pal: body.pal || (isAcpSub ? 'cyan' : (resolved.pal || paletteForPersona(persona))),
746
+ engine: isAcpSub ? 'acp' : 'builtin',
747
+ mode: ['general', 'design', 'qa', 'audit'].includes(body.mode) ? body.mode : 'design',
748
+ execMode: body.execMode === 'plan' ? 'plan' : 'act',
749
+ archived: false,
750
+ liveStatus: isAcpSub ? 'ACP 外部子代理待命…' : '等待指令…',
751
+ messages: [],
752
+ uiMessages: [],
753
+ });
754
+ ensureMemorySession(targetWorkspace, meta, newId, saved);
755
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
756
+ sendJson(201, { session: saved });
757
+ return;
758
+ }
759
+
760
+ if (act === 'rename') {
761
+ const targetId = safeSessionId(body.id);
762
+ const nextTitle = String(body.title || '').trim().slice(0, 48);
763
+ if (!targetId || !nextTitle) throw new DocumentError('缺少会话 id 或新名称。', 400);
764
+ const existing = loadSessionRecord(stateDir, targetId);
765
+ const mem = sessions.get(targetId);
766
+ if (mem) mem.title = nextTitle;
767
+ const updated = saveSessionRecord(stateDir, {
768
+ ...(existing || { id: targetId, persona: mem?.persona || meta.defaultPersona }),
769
+ id: targetId,
770
+ title: nextTitle,
771
+ touchActivity: false,
772
+ });
773
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
774
+ sendJson(200, { session: updated });
775
+ return;
776
+ }
777
+
778
+ if (act === 'set_persona') {
779
+ const targetId = safeSessionId(body.id);
780
+ const nextPersona = ['architect', 'coder', 'qa', 'auditor', 'custom'].includes(body.persona) ? body.persona : 'architect';
781
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
782
+ const nextPal = paletteForPersona(nextPersona);
783
+ const mem = sessions.get(targetId);
784
+ if (mem) {
785
+ mem.persona = nextPersona;
786
+ mem.pal = nextPal;
787
+ }
788
+ const existing = loadSessionRecord(stateDir, targetId);
789
+ const updated = saveSessionRecord(stateDir, {
790
+ ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona).name }),
791
+ id: targetId,
792
+ persona: nextPersona,
793
+ pal: nextPal,
794
+ touchActivity: false,
795
+ });
796
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
797
+ sendJson(200, { session: updated });
798
+ return;
799
+ }
800
+
801
+ if (act === 'archive' || act === 'unarchive') {
802
+ const targetId = safeSessionId(body.id);
803
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
804
+ const updated = archiveSessionRecord(stateDir, targetId, act === 'archive');
805
+ if (!updated) throw new DocumentError('未找到该会话。', 404);
806
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
807
+ sendJson(200, { session: updated });
808
+ return;
809
+ }
810
+
811
+ if (act === 'exec_mode') {
812
+ const targetId = safeSessionId(body.id);
813
+ const nextExec = body.execMode === 'plan' ? 'plan' : 'act';
814
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
815
+ const mem = sessions.get(targetId);
816
+ if (mem) mem.execMode = nextExec;
817
+ const existing = loadSessionRecord(stateDir, targetId);
818
+ if (existing) {
819
+ const updated = saveSessionRecord(stateDir, { ...existing, execMode: nextExec, touchActivity: false });
820
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
821
+ sendJson(200, { session: updated });
822
+ return;
823
+ }
824
+ sendJson(200, { ok: true, execMode: nextExec });
825
+ return;
826
+ }
827
+
828
+ if (act === 'rollback') {
829
+ const targetId = safeSessionId(body.id);
830
+ if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
831
+ const record = loadSessionRecord(stateDir, targetId);
832
+ if (!record || !Array.isArray(record.checkpoints) || !record.checkpoints.length) {
833
+ throw new DocumentError('当前会话暂无可回退的画布快照。', 404);
834
+ }
835
+ const cp = body.checkpointId
836
+ ? record.checkpoints.find(c => c.id === body.checkpointId)
837
+ : record.checkpoints.at(-1);
838
+ if (!cp || !cp.files) throw new DocumentError('未找到指定轮次快照。', 404);
839
+
840
+ const docRoot = meta.rtInfo.documentRoot || targetWorkspace;
841
+ const restoredFiles = [];
842
+ for (const [relFile, snap] of Object.entries(cp.files)) {
843
+ try {
844
+ const full = workspacePath(docRoot, relFile, true);
845
+ if (snap.existed) {
846
+ writeFileSync(full, snap.content, 'utf8');
847
+ } else if (existsSync(full)) {
848
+ unlinkSync(full);
849
+ }
850
+ restoredFiles.push(relFile);
851
+ events?.emit(targetWorkspace, 'doc.updated', { file: relFile, action: 'rollback', label: '已回退上轮画布修改' });
852
+ } catch {}
853
+ }
854
+ if (restoredFiles.length) events?.emit(targetWorkspace, 'workspace.updated', { action: 'rollback' });
855
+ cp.rolledBack = true;
856
+ const mem = sessions.get(targetId);
857
+ if (mem) mem.checkpoints = record.checkpoints;
858
+ saveSessionRecord(stateDir, { ...record, checkpoints: record.checkpoints, liveStatus: '已回退上轮修改' });
859
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
860
+ sendJson(200, { ok: true, restoredFiles, checkpointId: cp.id });
861
+ return;
862
+ }
863
+
864
+ throw new DocumentError('不支持的会话管理动作。', 400);
865
+ })();
866
+ }
867
+
263
868
  if (req.method === 'DELETE') {
264
869
  if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
265
870
  if (!id) throw new DocumentError('缺少会话 id。', 400);
@@ -267,13 +872,237 @@ export function createAgentHandler({
267
872
  if (active) close(active);
268
873
  const deleted = deleteSessionRecord(stateDir, id);
269
874
  if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
875
+ emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
270
876
  sendJson(200, { deleted: true });
271
877
  return;
272
878
  }
273
- throw new DocumentError('会话接口仅支持 GET / DELETE。', 405);
879
+ throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
274
880
  }
275
881
 
276
- async function handle(req, res, targetWorkspace = workspace) {
882
+ async function handleConfig(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
883
+ const host = req.headers.host || '';
884
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
885
+ const rootWs = typeof workspace === 'function' ? workspace() : workspace;
886
+ const meta = resolveMeta(targetWorkspace);
887
+ const stateDir = meta.rtInfo.stateDir;
888
+ const sendJson = (status, data) => {
889
+ res.writeHead(status, {
890
+ 'content-type': 'application/json; charset=utf-8',
891
+ 'cache-control': 'no-store',
892
+ 'x-content-type-options': 'nosniff',
893
+ });
894
+ res.end(JSON.stringify(data));
895
+ };
896
+
897
+ const computeSampleTelemetry = cfg => {
898
+ const sample = buildSegmentedPromptContext({
899
+ workspace: targetWorkspace,
900
+ rootWorkspace: rootWs,
901
+ documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
902
+ stateDir,
903
+ debugConfig: cfg,
904
+ baseSystemPrompt: resolvePersona('architect', '', cfg.personas).prompt,
905
+ history: [{ role: 'user', content: '示例历史上下文' }, { role: 'assistant', content: '已核对架构契约与幂等锚点。' }],
906
+ userInstruction: '继续推进',
907
+ });
908
+ return sample.telemetry;
909
+ };
910
+
911
+ if (req.method === 'GET') {
912
+ const memory = readWorkspaceMemory(stateDir, rootWs);
913
+ sendJson(200, {
914
+ llm: meta.llm,
915
+ mcpUrl: mcpUrl(),
916
+ config: meta.debugConfig,
917
+ hasWorkspaceOverride: meta.hasWorkspaceOverride,
918
+ memory,
919
+ telemetry: computeSampleTelemetry(meta.debugConfig),
920
+ });
921
+ return;
922
+ }
923
+
924
+ if (req.method === 'POST') {
925
+ if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
926
+ throw new DocumentError('配置修改只接受本机同源页面请求。', 403);
927
+ }
928
+ const body = await readJsonBody(req, 64 * 1024);
929
+
930
+ if (body.action === 'save_llm') {
931
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
932
+ const providerId = String(body.providerId || 'openai').trim().toLowerCase().slice(0, 64);
933
+ const preset = getProviderPreset(providerId);
934
+ const protocol = body.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
935
+ const baseUrl = String(body.baseUrl || preset?.defaultBaseUrl || 'https://api.openai.com/v1').trim().slice(0, 512);
936
+ const model = String(body.model || preset?.defaultModel || 'gpt-4.1-mini').trim().slice(0, 128);
937
+ const updated = saveSettings(prev => {
938
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
939
+ const prevProf = prevProviders[providerId] || {};
940
+ const typedKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
941
+ const finalKey = body.clearKey
942
+ ? ''
943
+ : (typedKey ? typedKey.slice(0, 512) : (prevProf.apiKey ?? ((prev.providerId === providerId ? prev.apiKey : '') || '')));
944
+ const mergedModels = Array.isArray(body.models) && body.models.length
945
+ ? [...new Set([model, ...body.models.map(m => String(m).trim()).filter(Boolean)])].slice(0, 60)
946
+ : [...new Set([model, ...(prevProf.models || preset?.models || [])].filter(Boolean))].slice(0, 60);
947
+ prevProviders[providerId] = {
948
+ label: String(body.label || prevProf.label || preset?.label || providerId).slice(0, 80),
949
+ protocol,
950
+ baseUrl,
951
+ ...(finalKey ? { apiKey: finalKey } : {}),
952
+ model,
953
+ enabled: true,
954
+ models: mergedModels,
955
+ };
956
+ const next = {
957
+ ...prev,
958
+ mode: 'builtin',
959
+ providerId,
960
+ provider: protocol,
961
+ baseUrl,
962
+ model,
963
+ providers: prevProviders,
964
+ };
965
+ if (finalKey) next.apiKey = finalKey;
966
+ else delete next.apiKey;
967
+ return next;
968
+ });
969
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
970
+ return;
971
+ }
972
+
973
+ if (body.action === 'switch_model') {
974
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
975
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
976
+ const model = String(body.model || '').trim().slice(0, 128);
977
+ if (!model) throw new DocumentError('请选择要切换的模型。', 400);
978
+ const preset = getProviderPreset(providerId);
979
+ const updated = saveSettings(prev => {
980
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
981
+ const prof = prevProviders[providerId] || {};
982
+ const protocol = prof.protocol || preset?.protocol || 'openai';
983
+ const baseUrl = prof.baseUrl || preset?.defaultBaseUrl || prev.baseUrl || 'https://api.openai.com/v1';
984
+ prevProviders[providerId] = {
985
+ ...prof,
986
+ protocol,
987
+ baseUrl,
988
+ model,
989
+ models: [...new Set([model, ...(prof.models || preset?.models || [])])].slice(0, 60),
990
+ };
991
+ const next = {
992
+ ...prev,
993
+ mode: 'builtin',
994
+ providerId,
995
+ provider: protocol,
996
+ baseUrl,
997
+ model,
998
+ providers: prevProviders,
999
+ };
1000
+ if (prof.apiKey) next.apiKey = prof.apiKey;
1001
+ return next;
1002
+ });
1003
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1004
+ return;
1005
+ }
1006
+
1007
+ if (body.action === 'fetch_models') {
1008
+ const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1009
+ const preset = getProviderPreset(providerId);
1010
+ const curSettings = readSettings();
1011
+ const savedProf = curSettings.providers?.[providerId] || {};
1012
+ const protocol = body.protocol === 'anthropic' || savedProf.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
1013
+ const baseUrl = String(body.baseUrl || savedProf.baseUrl || preset?.defaultBaseUrl || '').trim();
1014
+ const apiKey = String(body.apiKey || '').trim() || savedProf.apiKey || (curSettings.providerId === providerId ? curSettings.apiKey : '') || '';
1015
+ const models = await fetchProviderModels({ protocol, baseUrl, apiKey, fetchImpl });
1016
+ if (saveSettings && models.length) {
1017
+ saveSettings(prev => {
1018
+ const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1019
+ const prof = prevProviders[providerId] || {};
1020
+ prevProviders[providerId] = {
1021
+ ...prof,
1022
+ protocol,
1023
+ baseUrl: prof.baseUrl || baseUrl,
1024
+ models,
1025
+ };
1026
+ return { ...prev, providers: prevProviders };
1027
+ });
1028
+ }
1029
+ sendJson(200, { ok: true, models });
1030
+ return;
1031
+ }
1032
+
1033
+ if (body.action === 'save_acp') {
1034
+ if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1035
+ const cmd = String(body.command || '').trim().slice(0, 2048);
1036
+ if (!cmd) throw new DocumentError('ACP 命令不能为空。', 400);
1037
+ const argsList = Array.isArray(body.args)
1038
+ ? body.args.map(a => String(a).trim()).filter(Boolean).slice(0, 32)
1039
+ : String(body.args || '').split(/\s+/).map(a => a.trim()).filter(Boolean).slice(0, 32);
1040
+ const updated = saveSettings(prev => ({
1041
+ ...prev,
1042
+ command: cmd,
1043
+ args: argsList,
1044
+ }));
1045
+ sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1046
+ return;
1047
+ }
1048
+
1049
+ if (body.action === 'save_memory') {
1050
+ const text = saveWorkspaceMemory(stateDir, body.text || '');
1051
+ const latest = readAgentDebugConfig(stateDir).config;
1052
+ sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, rootWs), telemetry: computeSampleTelemetry(latest) });
1053
+ return;
1054
+ }
1055
+ if (body.action === 'save_config') {
1056
+ const saved = saveAgentDebugConfig(stateDir, body.patch || {}, { scope: body.scope === 'workspace' ? 'workspace' : 'global' });
1057
+ sendJson(200, {
1058
+ ok: true,
1059
+ config: saved.config,
1060
+ hasWorkspaceOverride: saved.hasWorkspaceOverride,
1061
+ telemetry: computeSampleTelemetry(saved.config),
1062
+ });
1063
+ return;
1064
+ }
1065
+ if (body.action === 'reset') {
1066
+ const saved = resetAgentDebugConfig(stateDir, body.section || 'all');
1067
+ sendJson(200, {
1068
+ ok: true,
1069
+ config: saved.config,
1070
+ hasWorkspaceOverride: saved.hasWorkspaceOverride,
1071
+ telemetry: computeSampleTelemetry(saved.config),
1072
+ });
1073
+ return;
1074
+ }
1075
+ if (body.action === 'test_compact') {
1076
+ const targetSess = body.sessionId ? loadSessionRecord(stateDir, body.sessionId) : null;
1077
+ const srcMsgs = Array.isArray(targetSess?.messages) && targetSess.messages.length
1078
+ ? targetSess.messages
1079
+ : Array.from({ length: 12 }, (_, idx) => ({
1080
+ role: idx % 2 === 0 ? 'user' : 'assistant',
1081
+ content: `示例第 ${idx + 1} 轮架构与代码对齐记录(幂等键 idempotencyKey、3000ms 超时重试与账务落库校验)。`.repeat(4),
1082
+ }));
1083
+ const beforeChars = JSON.stringify(srcMsgs).length;
1084
+ const after = compactMessages(srcMsgs, {
1085
+ maxChars: Math.max(600, Math.floor(beforeChars * 0.6)),
1086
+ thresholdPct: meta.debugConfig.compactThresholdPct,
1087
+ compactPrompt: meta.debugConfig.compactPrompt,
1088
+ });
1089
+ const afterChars = JSON.stringify(after).length;
1090
+ sendJson(200, {
1091
+ ok: true,
1092
+ beforeTurns: srcMsgs.length,
1093
+ afterTurns: after.length,
1094
+ beforeTokens: Math.ceil(beforeChars / 2.8),
1095
+ afterTokens: Math.ceil(afterChars / 2.8),
1096
+ });
1097
+ return;
1098
+ }
1099
+ throw new DocumentError('不支持的配置操作。', 400);
1100
+ }
1101
+
1102
+ throw new DocumentError('配置接口仅支持 GET / POST。', 405);
1103
+ }
1104
+
1105
+ async function handle(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
277
1106
  const host = req.headers.host || '';
278
1107
  if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
279
1108
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
@@ -283,6 +1112,7 @@ export function createAgentHandler({
283
1112
  }
284
1113
  const input = await readRequest(req);
285
1114
  let session = sessions.get(input.session);
1115
+
286
1116
  if (input.action === 'cancel' || input.action === 'close') {
287
1117
  if (input.action === 'close') {
288
1118
  close(session || { key: input.session });
@@ -299,26 +1129,35 @@ export function createAgentHandler({
299
1129
  return;
300
1130
  }
301
1131
 
1132
+ // 运行中实时插话纠偏(Steer):不打断已完成的工具步骤,排入下一步队首立即生效
1133
+ if (input.action === 'steer') {
1134
+ if (session?.running && Array.isArray(session.steeringQueue)) {
1135
+ session.steeringQueue.push(input.text);
1136
+ session.uiMessages.push({ role: 'human', text: input.text, isSteer: true });
1137
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
1138
+ res.end(JSON.stringify({ ok: true, mode: 'steered' }));
1139
+ return;
1140
+ }
1141
+ throw new DocumentError('当前会话未在运行中,请直接发送消息。', 409);
1142
+ }
1143
+
302
1144
  if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
303
1145
  if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
304
1146
  const meta = resolveMeta(targetWorkspace);
305
1147
  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);
1148
+ if (sessions.size >= 16) throw new DocumentError('Agent 并发会话过多,请归档或关闭部分会话后再试。', 429);
1149
+ session = ensureMemorySession(targetWorkspace, meta, input.session, {
1150
+ title: input.title,
1151
+ persona: input.persona,
1152
+ engine: input.engine === 'acp' ? 'acp' : 'builtin',
1153
+ mode: input.mode,
1154
+ execMode: input.execMode,
1155
+ });
319
1156
  }
1157
+ if (input.execMode) session.execMode = input.execMode;
320
1158
 
321
1159
  let resumeToolResult = null;
1160
+ let resumeCommandResult = null;
322
1161
  if (input.action === 'answer') {
323
1162
  const pending = session.pendingQuestion;
324
1163
  if (!pending || pending.id !== input.questionId) {
@@ -329,16 +1168,34 @@ export function createAgentHandler({
329
1168
  choiceId: input.choiceId || '',
330
1169
  answer: input.answer,
331
1170
  };
1171
+ } else if (input.action === 'command_decision') {
1172
+ const pendingCmd = session.pendingCommand;
1173
+ if (!pendingCmd || pendingCmd.id !== input.commandId) {
1174
+ throw new DocumentError('当前没有待审批的命令,或该请求已失效。', 409);
1175
+ }
1176
+ if (input.decision === 'session_allow') session.commandAutoAllow = true;
1177
+ resumeCommandResult = {
1178
+ toolCallId: pendingCmd.toolCallId,
1179
+ command: pendingCmd.command,
1180
+ decision: input.decision,
1181
+ };
332
1182
  }
333
1183
 
334
- const useBuiltin = input.action === 'answer' || (input.action === 'prompt' && (
335
- input.engine === 'builtin' ||
336
- ((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
337
- ));
1184
+ const sessionWantsAcp = session.engine === 'acp' || input.engine === 'acp';
1185
+ const useBuiltin = input.action === 'answer'
1186
+ || input.action === 'command_decision'
1187
+ || (input.action === 'prompt' && !sessionWantsAcp && (
1188
+ input.engine === 'builtin' || meta.activeEngine === 'builtin'
1189
+ ));
338
1190
 
339
1191
  session.running = true;
340
1192
  session.cancelled = false;
1193
+ session.peerHopCount = 0; // 人类主动交互立即清零连续互发计数
1194
+ session.activeCardTarget = input.canvas?.file
1195
+ ? `${input.canvas.file}${input.canvas.selection?.[0]?.[0] ? '#' + input.canvas.selection[0][0] : ''}`
1196
+ : '';
341
1197
  clearTimeout(session.idle);
1198
+
342
1199
  res.writeHead(200, {
343
1200
  'content-type': 'application/x-ndjson; charset=utf-8',
344
1201
  'cache-control': 'no-store, no-transform',
@@ -356,7 +1213,7 @@ export function createAgentHandler({
356
1213
  const run = async () => {
357
1214
  if (useBuiltin) {
358
1215
  session.abortController = new AbortController();
359
- // 若上一轮有未回答的 ask_user,但用户直接发起了新指令,补一条跳过回执避免协议报孤立 tool_call 错误
1216
+ // 若上一轮有未回答的 ask_user 或待审命令,但用户直接发起了新指令,自动补齐跳过回执保持消息配对合法
360
1217
  if (input.action === 'prompt' && session.pendingQuestion) {
361
1218
  session.history.push({
362
1219
  role: 'tool',
@@ -371,32 +1228,64 @@ export function createAgentHandler({
371
1228
  }
372
1229
  session.pendingQuestion = null;
373
1230
  }
1231
+ if (input.action === 'prompt' && session.pendingCommand) {
1232
+ session.history.push({
1233
+ role: 'tool',
1234
+ tool_call_id: session.pendingCommand.toolCallId,
1235
+ content: JSON.stringify({ approved: false, skipped: true, reason: '用户发起了新的指令' }),
1236
+ });
1237
+ session.pendingCommand = null;
1238
+ }
1239
+
374
1240
  const activeMode = input.mode || session.mode || 'general';
375
1241
  const activePersona = input.persona || session.persona || meta.defaultPersona;
1242
+ const activeExecMode = input.execMode || session.execMode || 'act';
376
1243
  let thinkingBuf = '';
377
1244
  let textBuf = '';
378
1245
  let changesBuf = [];
1246
+ const incomingPeers = session.incomingPeerMessages.splice(0);
1247
+ const peerCoord = createPeerCoordinator(targetWorkspace, meta, session);
1248
+
379
1249
  const emitBuiltin = ev => {
380
1250
  if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
381
1251
  else if (ev.type === 'text' && ev.text) textBuf += ev.text;
382
1252
  else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
1253
+ else if (ev.type === 'todos' && Array.isArray(ev.todos)) session.todos = ev.todos;
1254
+ else if (ev.type === 'status' && ev.text) {
1255
+ session.liveStatus = ev.text;
1256
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1257
+ }
383
1258
  emit(ev);
384
1259
  };
1260
+
385
1261
  const result = await runVerticalAgent({
386
1262
  workspace: session.workspace,
1263
+ rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
1264
+ documentRoot: meta.rtInfo.documentRoot || session.workspace,
387
1265
  stateDir: meta.rtInfo.stateDir,
388
1266
  workspaceService,
389
1267
  events,
390
1268
  config: meta.settings,
1269
+ debugConfig: meta.debugConfig,
391
1270
  history: session.history,
1271
+ canvasBaseline: session.canvasBaseline,
1272
+ activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
1273
+ incomingPeerMessages: incomingPeers,
1274
+ peerCoordinator: peerCoord,
392
1275
  resumeToolResult,
1276
+ resumeCommandResult,
1277
+ sessionCommandAutoAllow: session.commandAutoAllow,
1278
+ drainSteering: () => session.steeringQueue.splice(0),
393
1279
  input,
394
1280
  mode: activeMode,
1281
+ execMode: activeExecMode,
395
1282
  persona: activePersona,
1283
+ todos: session.todos,
396
1284
  emit: emitBuiltin,
397
1285
  signal: session.abortController.signal,
398
1286
  fetchImpl,
399
1287
  });
1288
+
400
1289
  if (input.action === 'answer') {
401
1290
  for (let i = session.uiMessages.length - 1; i >= 0; i--) {
402
1291
  if (session.uiMessages[i]?.question?.id === input.questionId) {
@@ -405,6 +1294,9 @@ export function createAgentHandler({
405
1294
  }
406
1295
  }
407
1296
  session.uiMessages.push({ role: 'human', text: input.answer, isAnswer: true });
1297
+ } else if (input.action === 'command_decision') {
1298
+ const labelMap = { allow: '已允许执行', session_allow: '本会话免审允许', deny: '已拒绝命令' };
1299
+ session.uiMessages.push({ role: 'human', text: `${labelMap[input.decision]}:${resumeCommandResult.command}`, isAnswer: true });
408
1300
  } else {
409
1301
  session.uiMessages.push({
410
1302
  role: 'human',
@@ -412,37 +1304,81 @@ export function createAgentHandler({
412
1304
  canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
413
1305
  });
414
1306
  }
415
- if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion) {
1307
+
1308
+ if (result.checkpoint) session.checkpoints.push(result.checkpoint);
1309
+ if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
416
1310
  session.uiMessages.push({
417
1311
  role: 'assistant',
418
1312
  thinking: thinkingBuf,
419
1313
  text: textBuf,
420
1314
  changes: changesBuf,
1315
+ checkpointId: result.checkpoint?.id || null,
421
1316
  question: result.pendingQuestion || null,
1317
+ commandApproval: result.pendingCommand || null,
422
1318
  });
423
1319
  }
1320
+
424
1321
  session.history = Array.isArray(result.conversation) ? result.conversation : session.history;
1322
+ session.todos = Array.isArray(result.todos) ? result.todos : session.todos;
1323
+ session.canvasBaseline = result.nextBaseline || session.canvasBaseline;
425
1324
  session.pendingQuestion = result.pendingQuestion || null;
1325
+ session.pendingCommand = result.pendingCommand || null;
426
1326
  session.persona = activePersona;
1327
+ session.pal = paletteForPersona(activePersona);
427
1328
  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
- });
1329
+ session.execMode = activeExecMode;
1330
+ if (!session.title) session.title = (input.title || input.text || input.answer || '新会话').slice(0, 48);
1331
+ session.liveStatus = result.pendingCommand
1332
+ ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
1333
+ : result.pendingQuestion
1334
+ ? '等待确认方案…'
1335
+ : (changesBuf[0]?.label || '已完成');
1336
+
1337
+ if (meta.rtInfo.stateDir) {
1338
+ saveSessionRecord(meta.rtInfo.stateDir, {
1339
+ id: session.key,
1340
+ title: session.title,
1341
+ persona: session.persona,
1342
+ pal: session.pal,
1343
+ mode: session.mode,
1344
+ execMode: session.execMode,
1345
+ archived: false,
1346
+ liveStatus: session.liveStatus,
1347
+ todos: session.todos,
1348
+ calledBy: null,
1349
+ canvasBaseline: session.canvasBaseline,
1350
+ checkpoints: session.checkpoints,
1351
+ messages: session.history,
1352
+ uiMessages: session.uiMessages,
1353
+ pendingQuestion: session.pendingQuestion,
1354
+ pendingCommand: session.pendingCommand,
1355
+ });
1356
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1357
+ }
438
1358
  return { stopReason: result.stopReason };
439
1359
  }
440
1360
 
1361
+ // 外部 ACP 执行器(dispatch / 默认 ACP 对话):同样接入底部会话胶囊持久化,但不接管其内部压缩
1362
+ let acpTextBuf = '';
1363
+ const prevEmit = session.emit;
1364
+ session.emit = ev => {
1365
+ if (ev.type === 'text' && ev.text) acpTextBuf += ev.text;
1366
+ else if (ev.type === 'tool' && ev.title) {
1367
+ session.liveStatus = `调用 ${String(ev.title).split('.').pop()}…`;
1368
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1369
+ }
1370
+ prevEmit?.(ev);
1371
+ };
1372
+
441
1373
  if (input.action === 'dispatch') {
442
1374
  const chosen = input.executorId
443
1375
  ? meta.executors.find(item => item.id === input.executorId)
444
1376
  : meta.executors[0];
445
1377
  if (!chosen) throw new Error('找不到指定的 ACP 执行器插件:' + (input.executorId || '默认'));
1378
+ if (!session.title) session.title = chosen.name;
1379
+ session.liveStatus = `${chosen.name} 执行中…`;
1380
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1381
+
446
1382
  const runRec = createRunRecord(meta.rtInfo.stateDir, {
447
1383
  kind: 'dispatch',
448
1384
  mode: 'implement',
@@ -460,7 +1396,6 @@ export function createAgentHandler({
460
1396
  label: `ACP 派发开发中 · ${chosen.name}`,
461
1397
  });
462
1398
 
463
- // 如果当前会话绑定的不是这个执行器,重新建立对应执行器的 ACP 连接
464
1399
  if (session.agent && session.executorId !== chosen.id) {
465
1400
  session.agent.dispose();
466
1401
  session.agent = null;
@@ -495,19 +1430,61 @@ export function createAgentHandler({
495
1430
  nodes: input.canvas?.selection || [],
496
1431
  label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
497
1432
  });
1433
+ session.uiMessages.push(
1434
+ { role: 'human', text: `[派发 ${chosen.name}] ${input.text || '按画布规格实现'}` },
1435
+ ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1436
+ );
1437
+ session.liveStatus = `${chosen.name} 已完成`;
1438
+ if (meta.rtInfo.stateDir) {
1439
+ saveSessionRecord(meta.rtInfo.stateDir, {
1440
+ id: session.key,
1441
+ title: session.title || chosen.name,
1442
+ persona: session.persona,
1443
+ pal: 'teal',
1444
+ mode: session.mode,
1445
+ execMode: session.execMode,
1446
+ archived: false,
1447
+ liveStatus: session.liveStatus,
1448
+ uiMessages: session.uiMessages,
1449
+ });
1450
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1451
+ }
498
1452
  return response;
499
1453
  }
500
1454
 
501
- // 默认 ACP 对话模式(完全兼容既有行为)
1455
+ // 默认 ACP 对话模式
502
1456
  if (!session.agent) await connectAcp(session);
503
1457
  if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
1458
+ if (!session.title) session.title = (input.title || input.text || 'ACP 会话').slice(0, 48);
1459
+ session.liveStatus = '正在生成…';
1460
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
504
1461
  emit({ type: 'status', text: '正在生成' });
505
1462
  const prompt = promptBlocks(session.workspace, input);
506
1463
  if (!session.started && session.hasMcp) {
507
1464
  prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
508
1465
  session.started = true;
509
1466
  }
510
- return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1467
+ const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1468
+ session.uiMessages.push(
1469
+ { role: 'human', text: input.text },
1470
+ ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1471
+ );
1472
+ session.liveStatus = '已完成';
1473
+ if (meta.rtInfo.stateDir) {
1474
+ saveSessionRecord(meta.rtInfo.stateDir, {
1475
+ id: session.key,
1476
+ title: session.title,
1477
+ persona: session.persona,
1478
+ pal: session.pal,
1479
+ mode: session.mode,
1480
+ execMode: session.execMode,
1481
+ archived: false,
1482
+ liveStatus: session.liveStatus,
1483
+ uiMessages: session.uiMessages,
1484
+ });
1485
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1486
+ }
1487
+ return response;
511
1488
  };
512
1489
 
513
1490
  try {
@@ -527,14 +1504,22 @@ export function createAgentHandler({
527
1504
  session.stopTimer = undefined;
528
1505
  session.abortController = undefined;
529
1506
  session.running = false;
1507
+ session.activeCardTarget = '';
530
1508
  session.emit = session.fail = undefined;
531
1509
  res.off('close', onDisconnect);
532
1510
  res.end();
1511
+ emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
533
1512
  if (sessions.get(session.key) === session) {
534
1513
  session.idle = setTimeout(() => close(session), idleMs);
535
1514
  session.idle.unref();
536
1515
  }
537
1516
  }
538
1517
  }
539
- return { handle, handleMeta, handleSessions, close: () => { for (const session of sessions.values()) close(session); } };
1518
+ return {
1519
+ handle,
1520
+ handleMeta,
1521
+ handleSessions,
1522
+ handleConfig,
1523
+ close: () => { for (const session of sessions.values()) close(session); },
1524
+ };
540
1525
  }