cladogram 0.5.5-beta.8 → 0.6.0-beta.1

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,1525 +1,433 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { spawn } from 'node:child_process';
3
- import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
4
- import { Readable, Writable } from 'node:stream';
5
- import { client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
1
+ /**
2
+ * Clado Agent HTTP & NDJSON Handler (Powered by Pi 1.x SDK)
3
+ *
4
+ * 极简薄层:
5
+ * - GET /library/agent/meta — Pi 运行时状态、模型与供应商、角色列表、扩展生态(Pi Packages/MCP/Skills/Prompts/画布组件)、AGENTS.md
6
+ * - GET/POST/DELETE /library/agent/sessions — 角色会话列表、创建、更新、归档、删除、画布快照回退
7
+ * - GET/POST /library/agent/config — 统一 5 页签设置中心写入(Pi auth/models/settings/mcp/skills/prompts/packages、角色、AGENTS.md、画布组件)
8
+ * - POST /library/agent — NDJSON 流式对话(prompt / handoff / answer / steer / cancel)
9
+ */
10
+
6
11
  import { z } from 'zod/v4';
7
12
  import { VERSION } from '../util/version.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';
13
+ import { DocumentError } from '../workspace/documents.js';
17
14
  import {
18
- buildDispatchPrompt, createRunRecord, discoverExecutors, listRunRecords, publicExecutorList, updateRunRecord,
19
- } from '../agent/executors.js';
15
+ deletePiMcpServer,
16
+ deletePiPrompt,
17
+ deletePiSkill,
18
+ deleteProviderConfig,
19
+ deleteRole,
20
+ importPiMcpJson,
21
+ inspectPiEcosystem,
22
+ installPiPackage,
23
+ listProvidersAndModels,
24
+ listRoles,
25
+ readAgentsMemory,
26
+ readCanvasComponentsConfig,
27
+ removePiPackage,
28
+ resolvePiAgentDir,
29
+ resolveRole,
30
+ saveAgentsMemory,
31
+ savePiMcpServer,
32
+ savePiPrompt,
33
+ savePiSkill,
34
+ saveProviderConfig,
35
+ saveRole,
36
+ setDefaultPiModel,
37
+ toggleCanvasComponent,
38
+ togglePiMcpServer,
39
+ } from '../agent/pi-config.js';
20
40
  import {
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,
41
+ archiveSession,
42
+ createPiBridge,
43
+ deleteSession,
44
+ getSessionMeta,
45
+ listSessions,
46
+ restoreCanvasSnapshot,
38
47
  safeSessionId,
39
- saveSessionRecord,
40
- } from '../agent/sessions.js';
41
- import { runVerticalAgent } from '../agent/runtime.js';
48
+ upsertSessionMeta,
49
+ } from '../agent/pi-bridge.js';
42
50
 
43
- const idleMs = 15 * 60_000;
44
- const turnMs = 5 * 60_000;
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({
51
+ const sessionIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
52
+ const canvasObjectSchema = z.object({
50
53
  id: z.string().min(1).max(120),
51
54
  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
+ title: z.string().max(160).default(''),
55
56
  });
56
- const canvasSchema = z.strictObject({
57
+ const canvasSchema = z.object({
57
58
  file: z.string().max(1500).optional(),
58
- revision: z.string().regex(/^[a-f0-9]{64}$/).optional(),
59
+ revision: z.string().max(128).optional(),
59
60
  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(),
61
+ objectSelection: z.array(canvasObjectSchema).max(100).optional(),
61
62
  });
62
- const requestSchema = z.discriminatedUnion('action', [
63
- z.strictObject({
64
- action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
65
- title: z.string().max(60).optional(),
66
- viewId: z.uuid().optional(),
67
- mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
68
- execMode: execModeSchema.optional(),
69
- persona: personaSchema.optional(),
70
- engine: z.enum(['auto', 'builtin', 'acp']).optional(),
63
+
64
+ const agentRequestSchema = z.discriminatedUnion('action', [
65
+ z.object({
66
+ action: z.literal('prompt'),
67
+ session: sessionIdSchema,
68
+ text: z.string().trim().min(1).max(16_000),
69
+ roleId: z.string().max(40).optional(),
70
+ model: z.string().max(160).optional(),
71
71
  canvas: canvasSchema.optional(),
72
72
  }),
73
- z.strictObject({
74
- action: z.literal('answer'), session: sessionId,
75
- questionId: z.string().min(1).max(128),
76
- choiceId: z.string().max(128).optional(),
77
- answer: z.string().trim().min(1).max(12_000),
78
- viewId: z.uuid().optional(),
79
- mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
80
- execMode: execModeSchema.optional(),
81
- persona: personaSchema.optional(),
73
+ z.object({
74
+ action: z.literal('handoff'),
75
+ fromSession: sessionIdSchema.optional(),
76
+ fromRoleName: z.string().max(60).optional(),
77
+ targetRoleId: z.string().min(1).max(40),
78
+ targetSession: sessionIdSchema.optional(),
79
+ text: z.string().trim().max(16_000).default(''),
82
80
  canvas: canvasSchema.optional(),
83
81
  }),
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(),
82
+ z.object({
83
+ action: z.literal('answer'),
84
+ session: sessionIdSchema,
85
+ questionId: z.string().min(1).max(128),
86
+ answer: z.string().trim().min(1).max(12_000),
93
87
  }),
94
- z.strictObject({
95
- action: z.literal('steer'), session: sessionId,
88
+ z.object({
89
+ action: z.literal('steer'),
90
+ session: sessionIdSchema,
96
91
  text: z.string().trim().min(1).max(4_000),
97
92
  }),
98
- z.strictObject({
99
- action: z.literal('dispatch'), session: sessionId,
100
- executorId: z.string().min(1).max(128).optional(),
101
- text: z.string().trim().max(12_000).default(''),
102
- viewId: z.uuid().optional(),
103
- canvas: canvasSchema.optional(),
93
+ z.object({
94
+ action: z.enum(['cancel', 'close']),
95
+ session: sessionIdSchema,
104
96
  }),
105
- z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
106
97
  ]);
107
98
 
108
- async function readJsonBody(req, maxBytes = 96 * 1024) {
99
+ async function readJsonBody(req, maxBytes = 128 * 1024) {
109
100
  const chunks = [];
110
101
  let bytes = 0;
111
102
  for await (const chunk of req) {
112
103
  bytes += chunk.length;
113
- if (bytes > maxBytes) throw new DocumentError('发送内容过长。', 413);
104
+ if (bytes > maxBytes) throw new DocumentError('请求体过大。', 413);
114
105
  chunks.push(chunk);
115
106
  }
116
107
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
117
108
  }
118
109
 
119
- async function readRequest(req) {
120
- const raw = await readJsonBody(req, 96 * 1024);
121
- const parsed = requestSchema.safeParse(raw);
122
- if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
123
- return parsed.data;
124
- }
125
-
126
- function promptBlocks(workspace, input) {
127
- const context = {
128
- workspace,
129
- ...(input.viewId && { viewId: input.viewId }),
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
- }),
136
- };
137
- return [
138
- { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径,objectSelection 是选中的多实例画布组件或子区域靶点。' },
139
- { type: 'text', text: JSON.stringify(context) },
140
- { type: 'text', text: '用户指令:\n' + input.text },
141
- ];
110
+ function sendJson(res, status, data) {
111
+ res.writeHead(status, {
112
+ 'content-type': 'application/json; charset=utf-8',
113
+ 'cache-control': 'no-store',
114
+ 'x-content-type-options': 'nosniff',
115
+ });
116
+ res.end(JSON.stringify(data));
142
117
  }
143
118
 
144
- function startAgent({ workspace, command, args, env, mcpName, emit, closed }) {
145
- const proc = spawn(command, args, {
146
- cwd: workspace,
147
- stdio: ['pipe', 'pipe', 'pipe'],
148
- windowsHide: true,
149
- env: { ...process.env, ...env },
150
- });
151
- proc.stderr.resume();
152
- const cladoCalls = new Map();
153
- proc.on('error', cause => {
154
- const message = cause.code === 'ENOENT'
155
- ? '找不到 ACP 启动命令。请安装适配器或在「灵感」插件设置里填写其路径。'
156
- : '无法启动 ACP 进程。';
157
- closed(new Error(message));
158
- });
159
- proc.on('exit', code => closed(new Error('ACP 进程已退出' + (code ? '(退出码 ' + code + ')' : '') + '。请检查启动命令和登录状态。')));
160
- const connection = client()
161
- .onRequest('session/request_permission', ({ params }) => {
162
- const option = params.options.find(option => option.kind === 'allow_once');
163
- if (option && params._meta?.is_mcp_tool_approval === true &&
164
- cladoCalls.get(params.toolCall.toolCallId) === params.sessionId) {
165
- return { outcome: { outcome: 'selected', optionId: option.optionId } };
166
- }
167
- emit({ type: 'status', text: '已拒绝额外的本机执行权限' });
168
- return { outcome: { outcome: 'cancelled' } };
169
- })
170
- .onNotification('session/update', ({ params }) => {
171
- const update = params.update;
172
- const kind = update.sessionUpdate;
173
- if (kind === 'agent_message_chunk' && update.content?.type === 'text') {
174
- emit({ type: 'text', text: update.content.text });
175
- } else if (kind === 'tool_call' || kind === 'tool_call_update') {
176
- const title = update.title?.slice(0, 160);
177
- if (kind === 'tool_call' && title?.startsWith('mcp.' + mcpName + '.clado_')) {
178
- cladoCalls.set(update.toolCallId, params.sessionId);
179
- }
180
- if (update.status === 'completed' || update.status === 'failed') cladoCalls.delete(update.toolCallId);
181
- emit({ type: 'tool', id: update.toolCallId, title, status: update.status });
182
- }
183
- })
184
- .connect(ndJsonStream(Writable.toWeb(proc.stdin), Readable.toWeb(proc.stdout)));
185
- connection.closed.then(() => closed(new Error('ACP 已断开。请检查适配器或重新发送。')));
186
- return {
187
- rpc: connection.agent,
188
- dispose() {
189
- connection.close();
190
- proc.stdin.destroy();
191
- if (proc.exitCode === null && proc.signalCode === null) proc.kill();
192
- },
193
- };
119
+ function assertSameOriginPost(req) {
120
+ const host = req.headers.host;
121
+ if (req.headers.origin && req.headers.origin !== 'http://' + host) {
122
+ throw new DocumentError('来源不匹配。', 403);
123
+ }
194
124
  }
195
125
 
196
126
  export function createAgentHandler({
197
- workspace, mcpUrl,
198
- command = process.env.CLADO_CODEX_ACP_PATH || 'codex-acp',
199
- args = [],
200
- resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
201
- resolveSettings = null,
202
- saveSettings = null,
127
+ workspace,
128
+ mcpUrl,
203
129
  resolveRuntimeInfo = null,
204
130
  workspaceService = null,
205
131
  events = null,
206
- fetchImpl = fetch,
132
+ sessionFactory = null,
207
133
  }) {
208
- const sessions = new Map();
209
- const mcpName = () => 'clado_canvas_' + new URL(mcpUrl()).port;
210
- const readSettings = () => {
211
- const base = resolveSettings ? resolveSettings() : {};
212
- const launch = resolveLaunch();
213
- return { ...launch, ...base };
214
- };
134
+ const bridge = createPiBridge({
135
+ workspaceService,
136
+ events,
137
+ sessionFactory,
138
+ });
215
139
 
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
- }
140
+ const getRuntime = targetWorkspace => {
141
+ const ws = targetWorkspace || (typeof workspace === 'function' ? workspace() : workspace);
142
+ const info = resolveRuntimeInfo ? resolveRuntimeInfo(ws) : null;
234
143
  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 : [],
144
+ workspace: ws,
145
+ stateDir: info?.stateDir || (ws + '/.clado'),
146
+ documentRoot: info?.documentRoot || ws,
147
+ pluginDescriptors: info?.pluginDescriptors || [],
247
148
  };
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
- }
149
+ };
280
150
 
281
- function close(session, error) {
282
- if (sessions.get(session.key) !== session) return;
283
- sessions.delete(session.key);
284
- clearTimeout(session.idle);
285
- session.abortController?.abort();
286
- session.fail?.(error || new Error('Agent 会话已关闭。'));
287
- session.agent?.dispose();
288
- }
151
+ async function buildFullMeta(targetWorkspace) {
152
+ const rt = getRuntime(targetWorkspace);
153
+ const agentDir = resolvePiAgentDir();
154
+ const [modelsInfo, ecosystem] = await Promise.all([
155
+ listProvidersAndModels(rt.workspace, agentDir),
156
+ inspectPiEcosystem(rt.workspace, agentDir),
157
+ ]);
158
+ const roles = listRoles(agentDir);
159
+ const memory = readAgentsMemory(rt.workspace);
160
+ const canvasComponents = readCanvasComponentsConfig(agentDir);
161
+ const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
289
162
 
290
- async function connectAcp(session, launchOverride = null) {
291
- const launch = launchOverride || resolveLaunch();
292
- session.agent = startAgent({
293
- workspace: session.workspace,
294
- command: launch.command,
295
- args: launch.args || [],
296
- env: launch.env || {},
297
- mcpName: mcpName(),
298
- emit: event => session.emit?.(event),
299
- closed: error => close(session, error),
300
- });
301
- const { rpc } = session.agent;
302
- const init = await rpc.request('initialize', {
303
- protocolVersion: PROTOCOL_VERSION,
304
- clientInfo: { name: 'clado', title: 'Clado', version: VERSION },
305
- clientCapabilities: {},
306
- });
307
- if (init.protocolVersion !== PROTOCOL_VERSION) throw new Error('当前适配器不支持 Clado 的 ACP 协议版本。');
308
- session.hasMcp = !!init.agentCapabilities?.mcpCapabilities?.http;
309
- const result = await rpc.request('session/new', {
310
- cwd: session.workspace,
311
- mcpServers: session.hasMcp ? [{ name: mcpName(), type: 'http', url: mcpUrl(), headers: [] }] : [],
312
- });
313
- session.id = result.sessionId;
314
- }
315
-
316
- function resolveMeta(targetWorkspace) {
317
- const settings = readSettings();
318
- const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
319
- const debugBundle = readAgentDebugConfig(rtInfo.stateDir);
320
- const executors = discoverExecutors({
321
- stateDir: rtInfo.stateDir,
322
- settings,
323
- pluginDescriptors: rtInfo.pluginDescriptors || [],
324
- });
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');
332
163
  return {
333
- settings,
334
- llm,
335
- debugConfig: debugBundle.config,
336
- hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
337
- rtInfo,
338
- executors,
339
- builtinConfigured,
340
- activeEngine,
341
- provider: llm.protocol,
342
- providerId: llm.providerId,
343
- providerLabel: llm.providerLabel,
344
- model: llm.model,
345
- defaultPersona: settings.persona || 'architect',
164
+ engine: 'pi',
165
+ version: VERSION,
166
+ workspace: rt.workspace,
167
+ mcpUrl: typeof mcpUrl === 'function' ? mcpUrl() : (mcpUrl || ''),
168
+ agentDir,
169
+ defaultProvider: modelsInfo.defaultProvider,
170
+ defaultModel: modelsInfo.defaultModel,
171
+ activeModelLabel: modelsInfo.activeModelLabel,
172
+ providers: modelsInfo.providers,
173
+ configuredModels: modelsInfo.configuredModels,
174
+ roles,
175
+ ecosystem,
176
+ canvasComponents,
177
+ workspacePlugins: rt.pluginDescriptors,
178
+ memory,
179
+ sessions,
346
180
  };
347
181
  }
348
182
 
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
- });
183
+ return {
184
+ async handleMeta(req, res, targetWorkspace) {
185
+ if (req.method !== 'GET') throw new DocumentError('仅支持 GET。', 405);
186
+ const data = await buildFullMeta(targetWorkspace);
187
+ sendJson(res, 200, data);
188
+ },
552
189
 
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);
190
+ async handleSessions(req, res, url, targetWorkspace) {
191
+ const rt = getRuntime(targetWorkspace);
192
+ const agentDir = resolvePiAgentDir();
567
193
 
568
- const nextHop = (callerSession.peerHopCount || 0) + 1;
569
- if (nextHop <= MAX_PEER_HOPS) {
570
- setImmediate(() => {
571
- runBackgroundPeerTurn(targetWorkspace, peer, fullTask, { hopCount: nextHop }).catch(() => {});
572
- });
194
+ if (req.method === 'GET') {
195
+ const id = url.searchParams.get('id');
196
+ if (id) {
197
+ const item = getSessionMeta(rt.stateDir, id, agentDir);
198
+ if (!item) throw new DocumentError('找不到该角色会话。', 404);
199
+ sendJson(res, 200, { session: item });
200
+ return;
573
201
  }
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 必填。');
202
+ const includeArchived = url.searchParams.get('archived') === '1';
203
+ sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, agentDir }) });
204
+ return;
205
+ }
581
206
 
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: '不能向当前会话自身发送同伴消息。' };
207
+ if (req.method === 'POST') {
208
+ assertSameOriginPost(req);
209
+ const body = await readJsonBody(req);
210
+ if (body?.action === 'archive') {
211
+ const updated = archiveSession(rt.stateDir, body.id, body.archived !== false, agentDir);
212
+ sendJson(res, 200, { ok: Boolean(updated), session: updated });
213
+ return;
589
214
  }
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
- });
215
+ if (body?.action === 'rollback') {
216
+ const result = restoreCanvasSnapshot(rt.documentRoot, rt.stateDir, body.id, body.snapshotId || '', events, rt.workspace);
217
+ sendJson(res, 200, result);
218
+ return;
646
219
  }
220
+ const created = upsertSessionMeta(rt.stateDir, {
221
+ id: body.id ? safeSessionId(body.id) : undefined,
222
+ title: body.title,
223
+ roleId: body.roleId || body.persona || 'architect',
224
+ model: body.model || '',
225
+ }, agentDir);
226
+ sendJson(res, 200, { ok: true, session: created });
227
+ return;
228
+ }
647
229
 
648
- return {
649
- delivered: true,
650
- peerId: peer.key,
651
- peerName: peer.title || hit.title,
652
- kind,
653
- circuitBroken,
654
- };
655
- },
656
- };
657
- }
230
+ if (req.method === 'DELETE') {
231
+ assertSameOriginPost(req);
232
+ const id = url.searchParams.get('id');
233
+ if (!id) throw new DocumentError('缺少会话 ID。', 400);
234
+ await bridge.cancel(rt.workspace, id);
235
+ sendJson(res, 200, deleteSession(rt.stateDir, id, agentDir));
236
+ return;
237
+ }
658
238
 
659
- function handleMeta(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
660
- const host = req.headers.host || '';
661
- if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
662
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
663
- const meta = resolveMeta(targetWorkspace);
664
- res.writeHead(200, {
665
- 'content-type': 'application/json; charset=utf-8',
666
- 'cache-control': 'no-store',
667
- 'x-content-type-options': 'nosniff',
668
- });
669
- res.end(JSON.stringify({
670
- engine: meta.activeEngine,
671
- provider: meta.provider,
672
- providerId: meta.providerId,
673
- providerLabel: meta.providerLabel,
674
- builtinConfigured: meta.builtinConfigured,
675
- model: meta.model,
676
- llm: meta.llm,
677
- mcpUrl: mcpUrl(),
678
- defaultPersona: meta.defaultPersona,
679
- personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
680
- personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
681
- executors: publicExecutorList(meta.executors),
682
- runs: listRunRecords(meta.rtInfo.stateDir, 10),
683
- sessions: listSessionRecords(meta.rtInfo.stateDir, {
684
- limit: 30,
685
- includeArchived: false,
686
- autoArchiveHours: meta.debugConfig.autoArchiveHours,
687
- runningIds: runningSessionIds(targetWorkspace),
688
- }),
689
- }));
690
- }
239
+ throw new DocumentError('不支持的请求方法。', 405);
240
+ },
691
241
 
692
- function handleSessions(req, res, url, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
693
- const host = req.headers.host || '';
694
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
695
- const meta = resolveMeta(targetWorkspace);
696
- const stateDir = meta.rtInfo.stateDir;
697
- const id = url.searchParams.get('id');
698
- const includeArchived = url.searchParams.get('includeArchived') === '1' || url.searchParams.get('includeArchived') === 'true';
699
- const sendJson = (status, data) => {
700
- res.writeHead(status, {
701
- 'content-type': 'application/json; charset=utf-8',
702
- 'cache-control': 'no-store',
703
- 'x-content-type-options': 'nosniff',
704
- });
705
- res.end(JSON.stringify(data));
706
- };
242
+ async handleConfig(req, res, targetWorkspace) {
243
+ const rt = getRuntime(targetWorkspace);
244
+ const agentDir = resolvePiAgentDir();
707
245
 
708
- if (req.method === 'GET') {
709
- if (id) {
710
- const record = loadSessionRecord(stateDir, id);
711
- if (!record) throw new DocumentError('未找到该历史会话。', 404);
712
- sendJson(200, { session: record });
246
+ if (req.method === 'GET') {
247
+ const data = await buildFullMeta(targetWorkspace);
248
+ sendJson(res, 200, data);
713
249
  return;
714
250
  }
715
- sendJson(200, {
716
- sessions: listSessionRecords(stateDir, {
717
- limit: 50,
718
- includeArchived,
719
- autoArchiveHours: meta.debugConfig.autoArchiveHours,
720
- runningIds: runningSessionIds(targetWorkspace),
721
- }),
722
- });
723
- return;
724
- }
725
251
 
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;
252
+ if (req.method !== 'POST') throw new DocumentError('仅支持 GET 或 POST。', 405);
253
+ assertSameOriginPost(req);
254
+ const body = await readJsonBody(req, 256 * 1024);
255
+ const action = String(body?.action || '').trim();
733
256
 
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 });
257
+ try {
258
+ if (action === 'save_provider') {
259
+ const result = saveProviderConfig(body, agentDir, rt.workspace);
260
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
757
261
  return;
758
262
  }
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 });
263
+ if (action === 'delete_provider') {
264
+ const result = deleteProviderConfig(body.providerId, agentDir);
265
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
775
266
  return;
776
267
  }
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 });
268
+ if (action === 'set_default_model') {
269
+ const result = await setDefaultPiModel(body.provider, body.model, agentDir, rt.workspace);
270
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
798
271
  return;
799
272
  }
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 });
273
+ if (action === 'save_role') {
274
+ const role = saveRole(body, agentDir);
275
+ sendJson(res, 200, { ok: true, role, meta: await buildFullMeta(targetWorkspace) });
808
276
  return;
809
277
  }
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 });
278
+ if (action === 'delete_role') {
279
+ const result = deleteRole(body.id, agentDir);
280
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
825
281
  return;
826
282
  }
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 });
283
+ if (action === 'save_mcp') {
284
+ const result = savePiMcpServer(body, rt.workspace, agentDir);
285
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
861
286
  return;
862
287
  }
863
-
864
- throw new DocumentError('不支持的会话管理动作。', 400);
865
- })();
866
- }
867
-
868
- if (req.method === 'DELETE') {
869
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
870
- if (!id) throw new DocumentError('缺少会话 id。', 400);
871
- const active = sessions.get(id);
872
- if (active) close(active);
873
- const deleted = deleteSessionRecord(stateDir, id);
874
- if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
875
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
876
- sendJson(200, { deleted: true });
877
- return;
878
- }
879
- throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
880
- }
881
-
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
- });
288
+ if (action === 'toggle_mcp') {
289
+ const result = togglePiMcpServer(body.name, body.enabled, rt.workspace, agentDir);
290
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
291
+ return;
1028
292
  }
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;
293
+ if (action === 'delete_mcp') {
294
+ const result = deletePiMcpServer(body.name, rt.workspace, agentDir);
295
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
296
+ return;
297
+ }
298
+ if (action === 'import_mcp_json') {
299
+ const result = importPiMcpJson(body.json, body.scope || 'user', rt.workspace, agentDir);
300
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
301
+ return;
302
+ }
303
+ if (action === 'save_skill') {
304
+ const result = savePiSkill(body, rt.workspace, agentDir);
305
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
306
+ return;
307
+ }
308
+ if (action === 'delete_skill') {
309
+ const result = deletePiSkill(body.name, rt.workspace, agentDir);
310
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
311
+ return;
312
+ }
313
+ if (action === 'save_command') {
314
+ const result = savePiPrompt(body, rt.workspace, agentDir);
315
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
316
+ return;
317
+ }
318
+ if (action === 'delete_command') {
319
+ const result = deletePiPrompt(body.name, rt.workspace, agentDir);
320
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
321
+ return;
322
+ }
323
+ if (action === 'install_pi_package') {
324
+ const result = await installPiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
325
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
326
+ return;
327
+ }
328
+ if (action === 'remove_pi_package') {
329
+ const result = await removePiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
330
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
331
+ return;
332
+ }
333
+ if (action === 'save_memory') {
334
+ const result = saveAgentsMemory(rt.workspace, body.content);
335
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
336
+ return;
337
+ }
338
+ if (action === 'toggle_canvas_component') {
339
+ const canvasComponents = toggleCanvasComponent(body.id, body.enabled, agentDir);
340
+ sendJson(res, 200, { ok: true, canvasComponents, meta: await buildFullMeta(targetWorkspace) });
341
+ return;
342
+ }
343
+ throw new DocumentError(`不支持的配置操作:${action}`, 400);
344
+ } catch (err) {
345
+ if (err instanceof DocumentError) throw err;
346
+ throw new DocumentError(err?.message || '配置更新失败', 400);
1047
347
  }
348
+ },
1048
349
 
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) });
350
+ async handle(req, res, targetWorkspace) {
351
+ if (req.method !== 'POST') throw new DocumentError('仅支持 POST。', 405);
352
+ assertSameOriginPost(req);
353
+ const raw = await readJsonBody(req);
354
+ const parsed = agentRequestSchema.safeParse(raw);
355
+ if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
356
+ const input = parsed.data;
357
+ const rt = getRuntime(targetWorkspace);
358
+ const agentDir = resolvePiAgentDir();
359
+
360
+ if (input.action === 'answer') {
361
+ const ok = bridge.answer(rt.workspace, input.session, input.questionId, input.answer);
362
+ sendJson(res, 200, { ok });
1053
363
  return;
1054
364
  }
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
- });
365
+ if (input.action === 'steer') {
366
+ const ok = await bridge.steer(rt.workspace, input.session, input.text);
367
+ sendJson(res, 200, { ok });
1073
368
  return;
1074
369
  }
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)) {
1106
- const host = req.headers.host || '';
1107
- if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
1108
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
1109
- req.headers.origin !== 'http://' + host ||
1110
- req.headers['content-type']?.split(';')[0] !== 'application/json') {
1111
- throw new DocumentError('Agent 只接受本机同源页面请求。', 403);
1112
- }
1113
- const input = await readRequest(req);
1114
- let session = sessions.get(input.session);
1115
-
1116
- if (input.action === 'cancel' || input.action === 'close') {
1117
- if (input.action === 'close') {
1118
- close(session || { key: input.session });
1119
- } else if (session?.running) {
1120
- session.cancelled = true;
1121
- if (session.abortController) {
1122
- session.abortController.abort();
1123
- } else if (session.id && session.agent) {
1124
- session.agent.rpc.notify('session/cancel', { sessionId: session.id }).catch(error => close(session, error));
1125
- session.stopTimer ||= setTimeout(() => close(session, new Error('Agent 停止超时,会话已关闭。')), 5000);
1126
- } else close(session, new Error('已停止连接。'));
1127
- }
1128
- res.writeHead(204).end();
1129
- return;
1130
- }
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' }));
370
+ if (input.action === 'cancel' || input.action === 'close') {
371
+ const ok = await bridge.cancel(rt.workspace, input.session);
372
+ sendJson(res, 200, { ok });
1139
373
  return;
1140
374
  }
1141
- throw new DocumentError('当前会话未在运行中,请直接发送消息。', 409);
1142
- }
1143
375
 
1144
- if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
1145
- if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
1146
- const meta = resolveMeta(targetWorkspace);
1147
- if (!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,
376
+ // Streaming NDJSON response for prompt & handoff
377
+ res.writeHead(200, {
378
+ 'content-type': 'application/x-ndjson; charset=utf-8',
379
+ 'cache-control': 'no-store',
380
+ 'x-content-type-options': 'nosniff',
1155
381
  });
1156
- }
1157
- if (input.execMode) session.execMode = input.execMode;
1158
-
1159
- let resumeToolResult = null;
1160
- let resumeCommandResult = null;
1161
- if (input.action === 'answer') {
1162
- const pending = session.pendingQuestion;
1163
- if (!pending || pending.id !== input.questionId) {
1164
- throw new DocumentError('当前没有待确认的提问,或该提问已失效。', 409);
1165
- }
1166
- resumeToolResult = {
1167
- toolCallId: pending.toolCallId,
1168
- choiceId: input.choiceId || '',
1169
- answer: input.answer,
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,
382
+ const emit = event => {
383
+ if (res.writableEnded || res.destroyed) return;
384
+ try { res.write(JSON.stringify(event) + '\n'); } catch {}
1181
385
  };
1182
- }
1183
-
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
- ));
1190
-
1191
- session.running = true;
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
- : '';
1197
- clearTimeout(session.idle);
1198
-
1199
- res.writeHead(200, {
1200
- 'content-type': 'application/x-ndjson; charset=utf-8',
1201
- 'cache-control': 'no-store, no-transform',
1202
- 'x-content-type-options': 'nosniff',
1203
- });
1204
- const emit = event => {
1205
- if (!res.destroyed && !res.writableEnded) res.write(JSON.stringify(event) + '\n');
1206
- };
1207
- session.emit = emit;
1208
- const abort = new Promise((_, reject) => { session.fail = reject; });
1209
- const onDisconnect = () => { if (!res.writableEnded) close(session); };
1210
- res.on('close', onDisconnect);
1211
- const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
1212
386
 
1213
- const run = async () => {
1214
- if (useBuiltin) {
1215
- session.abortController = new AbortController();
1216
- // 若上一轮有未回答的 ask_user 或待审命令,但用户直接发起了新指令,自动补齐跳过回执保持消息配对合法
1217
- if (input.action === 'prompt' && session.pendingQuestion) {
1218
- session.history.push({
1219
- role: 'tool',
1220
- tool_call_id: session.pendingQuestion.toolCallId,
1221
- content: JSON.stringify({ answered: false, skipped: true, reason: '用户发起了新的指令' }),
1222
- });
1223
- for (let i = session.uiMessages.length - 1; i >= 0; i--) {
1224
- if (session.uiMessages[i]?.question?.id === session.pendingQuestion.id) {
1225
- session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: '(已跳过,发起新指令)' };
1226
- break;
1227
- }
1228
- }
1229
- session.pendingQuestion = null;
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
-
1240
- const activeMode = input.mode || session.mode || 'general';
1241
- const activePersona = input.persona || session.persona || meta.defaultPersona;
1242
- const activeExecMode = input.execMode || session.execMode || 'act';
1243
- let thinkingBuf = '';
1244
- let textBuf = '';
1245
- let changesBuf = [];
1246
- const incomingPeers = session.incomingPeerMessages.splice(0);
1247
- const peerCoord = createPeerCoordinator(targetWorkspace, meta, session);
1248
-
1249
- const emitBuiltin = ev => {
1250
- if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
1251
- else if (ev.type === 'text' && ev.text) textBuf += ev.text;
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
- }
1258
- emit(ev);
1259
- };
1260
-
1261
- const result = await runVerticalAgent({
1262
- workspace: session.workspace,
1263
- rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
1264
- documentRoot: meta.rtInfo.documentRoot || session.workspace,
1265
- stateDir: meta.rtInfo.stateDir,
1266
- workspaceService,
1267
- events,
1268
- config: meta.settings,
1269
- debugConfig: meta.debugConfig,
1270
- history: session.history,
1271
- canvasBaseline: session.canvasBaseline,
1272
- activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
1273
- incomingPeerMessages: incomingPeers,
1274
- peerCoordinator: peerCoord,
1275
- resumeToolResult,
1276
- resumeCommandResult,
1277
- sessionCommandAutoAllow: session.commandAutoAllow,
1278
- drainSteering: () => session.steeringQueue.splice(0),
1279
- input,
1280
- mode: activeMode,
1281
- execMode: activeExecMode,
1282
- persona: activePersona,
1283
- todos: session.todos,
1284
- emit: emitBuiltin,
1285
- signal: session.abortController.signal,
1286
- fetchImpl,
387
+ if (input.action === 'handoff') {
388
+ const targetRole = resolveRole(input.targetRoleId, agentDir);
389
+ const existing = listSessions(rt.stateDir, { agentDir }).find(s => s.roleId === targetRole.id);
390
+ const targetSessionId = input.targetSession || existing?.id || ('role_' + targetRole.id);
391
+ const defaultTask = targetRole.id === 'developer'
392
+ ? '请依据上述画布设计契约落地代码实现,并在完成后运行校验命令汇报结果。'
393
+ : targetRole.id === 'tester'
394
+ ? '请依据上述画布契约补充单元测试与边界回归用例,并执行测试汇报结果。'
395
+ : targetRole.id === 'archivist'
396
+ ? '请将上述画布定稿内容整理为清晰的架构文档 / ADR 决策记录。'
397
+ : '请依据上述画布契约推进当前阶段工作。';
398
+
399
+ await bridge.runTurn({
400
+ workspace: rt.workspace,
401
+ stateDir: rt.stateDir,
402
+ documentRoot: rt.documentRoot,
403
+ sessionId: targetSessionId,
404
+ roleId: targetRole.id,
405
+ text: input.text || defaultTask,
406
+ canvas: input.canvas,
407
+ handoffFrom: input.fromRoleName || '画布定稿',
408
+ emit,
1287
409
  });
1288
-
1289
- if (input.action === 'answer') {
1290
- for (let i = session.uiMessages.length - 1; i >= 0; i--) {
1291
- if (session.uiMessages[i]?.question?.id === input.questionId) {
1292
- session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: input.answer };
1293
- break;
1294
- }
1295
- }
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 });
1300
- } else {
1301
- session.uiMessages.push({
1302
- role: 'human',
1303
- text: input.text,
1304
- canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
1305
- });
1306
- }
1307
-
1308
- if (result.checkpoint) session.checkpoints.push(result.checkpoint);
1309
- if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
1310
- session.uiMessages.push({
1311
- role: 'assistant',
1312
- thinking: thinkingBuf,
1313
- text: textBuf,
1314
- changes: changesBuf,
1315
- checkpointId: result.checkpoint?.id || null,
1316
- question: result.pendingQuestion || null,
1317
- commandApproval: result.pendingCommand || null,
1318
- });
1319
- }
1320
-
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;
1324
- session.pendingQuestion = result.pendingQuestion || null;
1325
- session.pendingCommand = result.pendingCommand || null;
1326
- session.persona = activePersona;
1327
- session.pal = paletteForPersona(activePersona);
1328
- session.mode = activeMode;
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
- }
1358
- return { stopReason: result.stopReason };
1359
- }
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
-
1373
- if (input.action === 'dispatch') {
1374
- const chosen = input.executorId
1375
- ? meta.executors.find(item => item.id === input.executorId)
1376
- : meta.executors[0];
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
-
1382
- const runRec = createRunRecord(meta.rtInfo.stateDir, {
1383
- kind: 'dispatch',
1384
- mode: 'implement',
1385
- executorId: chosen.id,
1386
- file: input.canvas?.file || '',
1387
- instruction: input.text || '按画布规格实施开发',
1388
- });
1389
- emit({ type: 'run', run: runRec });
1390
- emit({ type: 'status', text: `正在派发给执行器:${chosen.name}` });
1391
- events?.emit(session.workspace, 'agent.activity', {
1392
- file: input.canvas?.file || '',
1393
- action: 'dispatch',
1394
- kind: 'write',
1395
- nodes: input.canvas?.selection || [],
1396
- label: `ACP 派发开发中 · ${chosen.name}`,
1397
- });
1398
-
1399
- if (session.agent && session.executorId !== chosen.id) {
1400
- session.agent.dispose();
1401
- session.agent = null;
1402
- session.id = null;
1403
- session.started = false;
1404
- }
1405
- session.executorId = chosen.id;
1406
- if (!session.agent) await connectAcp(session, chosen);
1407
- if (session.cancelled || sessions.get(session.key) !== session) {
1408
- updateRunRecord(meta.rtInfo.stateDir, runRec, { status: 'cancelled' });
1409
- return { stopReason: 'cancelled' };
1410
- }
1411
- emit({ type: 'status', text: `${chosen.name} 执行中(无需切换窗口)…` });
1412
- const prompt = buildDispatchPrompt({
1413
- workspace: session.workspace,
1414
- documentRoot: meta.rtInfo.documentRoot,
1415
- file: input.canvas?.file || '',
1416
- selection: input.canvas?.selection || [],
1417
- instruction: input.text,
1418
- mcpName: session.hasMcp ? mcpName() : '',
1419
- });
1420
- const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1421
- const finished = updateRunRecord(meta.rtInfo.stateDir, runRec, {
1422
- status: session.cancelled ? 'cancelled' : 'completed',
1423
- summary: `执行器 ${chosen.name} 已完成(${response.stopReason})`,
1424
- });
1425
- emit({ type: 'run', run: finished });
1426
- events?.emit(session.workspace, 'agent.activity', {
1427
- file: input.canvas?.file || '',
1428
- action: 'dispatch.done',
1429
- kind: 'write',
1430
- nodes: input.canvas?.selection || [],
1431
- label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
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
- }
1452
- return response;
410
+ if (!res.writableEnded) res.end();
411
+ return;
1453
412
  }
1454
413
 
1455
- // 默认 ACP 对话模式
1456
- if (!session.agent) await connectAcp(session);
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);
1461
- emit({ type: 'status', text: '正在生成' });
1462
- const prompt = promptBlocks(session.workspace, input);
1463
- if (!session.started && session.hasMcp) {
1464
- prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
1465
- session.started = true;
1466
- }
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;
1488
- };
414
+ // action === 'prompt'
415
+ await bridge.runTurn({
416
+ workspace: rt.workspace,
417
+ stateDir: rt.stateDir,
418
+ documentRoot: rt.documentRoot,
419
+ sessionId: input.session,
420
+ roleId: input.roleId,
421
+ modelSpec: input.model,
422
+ text: input.text,
423
+ canvas: input.canvas,
424
+ emit,
425
+ });
426
+ if (!res.writableEnded) res.end();
427
+ },
1489
428
 
1490
- try {
1491
- emit({ type: 'status', text: useBuiltin ? '正在启动 Clado 独立 Agent' : (session.agent ? '正在发送' : '正在连接 Agent') });
1492
- const result = await Promise.race([run(), abort]);
1493
- emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
1494
- } catch (error) {
1495
- if (session.cancelled) emit({ type: 'done', reason: 'cancelled' });
1496
- else {
1497
- const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
1498
- emit({ type: 'error', text: message });
1499
- }
1500
- if (!useBuiltin) close(session, error);
1501
- } finally {
1502
- clearTimeout(timer);
1503
- clearTimeout(session.stopTimer);
1504
- session.stopTimer = undefined;
1505
- session.abortController = undefined;
1506
- session.running = false;
1507
- session.activeCardTarget = '';
1508
- session.emit = session.fail = undefined;
1509
- res.off('close', onDisconnect);
1510
- res.end();
1511
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1512
- if (sessions.get(session.key) === session) {
1513
- session.idle = setTimeout(() => close(session), idleMs);
1514
- session.idle.unref();
1515
- }
1516
- }
1517
- }
1518
- return {
1519
- handle,
1520
- handleMeta,
1521
- handleSessions,
1522
- handleConfig,
1523
- close: () => { for (const session of sessions.values()) close(session); },
429
+ close() {
430
+ return bridge.closeAll();
431
+ },
1524
432
  };
1525
433
  }