cladogram 0.5.5-beta.9 → 0.6.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +106 -80
  2. package/bin/clado.js +35 -3
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +123 -0
  6. package/package.json +5 -3
  7. package/plugins/agent/index.js +2485 -2982
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1441 -1315
  10. package/plugins/brand/index.js +84 -466
  11. package/plugins/brand/style.css +39 -172
  12. package/plugins/directory/index.js +10 -10
  13. package/plugins/view-controls/index.js +6 -1
  14. package/plugins/view-controls/style.css +41 -30
  15. package/skills/clado/SKILL.md +4 -2
  16. package/src/agent/automations.js +454 -0
  17. package/src/agent/clado-tools.js +792 -0
  18. package/src/agent/pi-bridge.js +2559 -0
  19. package/src/agent/pi-config.js +2411 -0
  20. package/src/agent/pi-hooks-perms.js +621 -0
  21. package/src/html/app-css.js +69 -1
  22. package/src/html/canvas-chain.js +32 -6
  23. package/src/html/canvas-focus.js +19 -13
  24. package/src/html/canvas-live-diff.js +1373 -0
  25. package/src/html/canvas-ui.css +503 -2
  26. package/src/html/canvas-wires.js +5 -1
  27. package/src/html/page.js +4 -2
  28. package/src/html/plugin-assets.js +5 -1
  29. package/src/html/plugin-ui.css +159 -134
  30. package/src/html/plugin-ui.js +3 -2
  31. package/src/html/runtime-api.js +152 -10
  32. package/src/html/runtime.js +546 -37
  33. package/src/server/agent.js +862 -1566
  34. package/src/server/assets/library-canvas.js +256 -9
  35. package/src/server/assets/library.css +951 -11
  36. package/src/server/assets/library.html +39 -4
  37. package/src/server/assets/library.js +1445 -224
  38. package/src/server/code-inspect.js +183 -0
  39. package/src/server/mcp.js +90 -22
  40. package/src/server/plugin-registry.js +671 -9
  41. package/src/server/plugins.js +1 -1
  42. package/src/server/workspace-hub.js +50 -0
  43. package/src/server/workspace.js +554 -39
  44. package/src/workspace/graph-snapshot.js +695 -0
  45. package/src/workspace/service.js +201 -9
  46. package/src/agent/commands.js +0 -204
  47. package/src/agent/context.js +0 -445
  48. package/src/agent/executors.js +0 -213
  49. package/src/agent/mcp-client.js +0 -308
  50. package/src/agent/probe.js +0 -234
  51. package/src/agent/providers/anthropic.js +0 -220
  52. package/src/agent/providers/index.js +0 -235
  53. package/src/agent/providers/openai.js +0 -146
  54. package/src/agent/runtime.js +0 -995
  55. package/src/agent/sessions.js +0 -336
  56. package/src/agent/skills.js +0 -190
@@ -1,1694 +1,990 @@
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
+ deletePluginParams,
19
+ deleteProjectRule,
20
+ deleteProviderConfig,
21
+ deleteRole,
22
+ ensureCladoPlatformDocs,
23
+ importPiMcpJson,
24
+ inspectPiEcosystem,
25
+ installPiPackage,
26
+ listPiMcpServers,
27
+ listProvidersAndModels,
28
+ listRoles,
29
+ readAgentsMemory,
30
+ readCanvasComponentsConfig,
31
+ readFullPiSettings,
32
+ readMemoryBundle,
33
+ readPiMcpRawJson,
34
+ readPluginParams,
35
+ readRawConfigTarget,
36
+ readRuntimeSettings,
37
+ readSkillOrPromptContent,
38
+ readWorkspacePrefs,
39
+ removePiPackage,
40
+ resetCladoPlatformDocs,
41
+ resolvePiAgentDir,
42
+ resolveRole,
43
+ restoreProviderPreset,
44
+ saveAgentsMemory,
45
+ saveCladoPlatformContext,
46
+ saveFullPiSettings,
47
+ saveGlobalAgentsMemory,
48
+ savePiMcpRawJson,
49
+ savePiMcpServer,
50
+ savePiPrompt,
51
+ savePiSkill,
52
+ savePluginParams,
53
+ saveProjectRule,
54
+ saveProviderConfig,
55
+ saveRawConfigTarget,
56
+ saveRole,
57
+ saveRuntimeSettings,
58
+ saveWorkspacePrefs,
59
+ scanExternalMcpConfigs,
60
+ setDefaultPiModel,
61
+ setProviderDisabled,
62
+ testProviderConnection,
63
+ toggleCanvasComponent,
64
+ togglePiMcpServer,
65
+ } from '../agent/pi-config.js';
20
66
  import {
21
- PROVIDER_PRESETS,
22
- fetchProviderModels,
23
- getProviderPreset,
24
- listConfiguredModels,
25
- maskApiKey,
26
- resolveProviderCredentials,
27
- } from '../agent/providers/index.js';
67
+ deleteHookRule,
68
+ readHooksConfig,
69
+ readPermissionsConfig,
70
+ saveHookRule,
71
+ savePermissionsConfig,
72
+ testHookRule,
73
+ } from '../agent/pi-hooks-perms.js';
74
+ import { listInstalledWorkspacePlugins } from './plugin-registry.js';
28
75
  import {
29
- archiveSessionRecord,
30
- BUILTIN_PERSONAS,
31
- compactMessages,
32
- deleteSessionRecord,
33
- listSessionRecords,
34
- loadSessionRecord,
35
- paletteForPersona,
36
- PERSONA_TEMPLATES,
37
- resolvePersona,
76
+ archiveSession,
77
+ clearArchivedSessions,
78
+ createPiBridge,
79
+ deleteSession,
80
+ exportSessionTranscript,
81
+ getSessionMeta,
82
+ listSessions,
83
+ readSessionMessagesPage,
84
+ renameSession,
85
+ restoreCanvasSnapshot,
38
86
  safeSessionId,
39
- saveSessionRecord,
40
- } from '../agent/sessions.js';
41
- import { runVerticalAgent } from '../agent/runtime.js';
87
+ upsertSessionMeta,
88
+ } from '../agent/pi-bridge.js';
42
89
  import {
43
- deleteMcpServer,
44
- importMcpJson,
45
- listMcpServers,
46
- saveMcpServer,
47
- testMcpServer,
48
- toggleMcpServer,
49
- } from '../agent/mcp-client.js';
50
- import { deleteSkill, listSkills, readSkill, saveSkill } from '../agent/skills.js';
51
- import { deleteCommand, expandSlashCommand, listCommands, saveCommand } from '../agent/commands.js';
52
-
53
- const idleMs = 15 * 60_000;
54
- const turnMs = 5 * 60_000;
55
- const MAX_PEER_HOPS = 8;
56
- const sessionId = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
57
- const personaSchema = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/);
58
- const execModeSchema = z.enum(['plan', 'act']);
59
- const canvasObjectItemSchema = z.strictObject({
90
+ createAutomationEngine,
91
+ deleteAutomationRule,
92
+ readAutomationsState,
93
+ saveAutomationRule,
94
+ setAutomationsPaused,
95
+ SYSTEM_EVENT_CATALOG,
96
+ } from '../agent/automations.js';
97
+
98
+ const sessionIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
99
+ const canvasObjectSchema = z.object({
60
100
  id: z.string().min(1).max(120),
61
101
  kind: z.string().min(1).max(60),
62
- title: z.string().max(160),
63
- pluginId: z.string().max(120).optional(),
64
- subtarget: z.string().max(160).optional(),
102
+ title: z.string().max(160).default(''),
65
103
  });
66
- const canvasSchema = z.strictObject({
104
+ const canvasSchema = z.object({
67
105
  file: z.string().max(1500).optional(),
68
- revision: z.string().regex(/^[a-f0-9]{64}$/).optional(),
106
+ revision: z.string().max(128).optional(),
69
107
  selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200).default([]),
70
- objectSelection: z.array(canvasObjectItemSchema).max(100).optional(),
108
+ objectSelection: z.array(canvasObjectSchema).max(100).optional(),
71
109
  });
72
- const requestSchema = z.discriminatedUnion('action', [
73
- z.strictObject({
74
- action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
75
- title: z.string().max(60).optional(),
76
- viewId: z.uuid().optional(),
77
- mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
78
- execMode: execModeSchema.optional(),
79
- persona: personaSchema.optional(),
80
- engine: z.enum(['auto', 'builtin', 'acp']).optional(),
110
+
111
+ const agentRequestSchema = z.discriminatedUnion('action', [
112
+ z.object({
113
+ action: z.literal('prompt'),
114
+ session: sessionIdSchema,
115
+ text: z.string().trim().min(1).max(16_000),
116
+ roleId: z.string().max(40).optional(),
117
+ model: z.string().max(160).optional(),
81
118
  canvas: canvasSchema.optional(),
82
119
  }),
83
- z.strictObject({
84
- action: z.literal('answer'), session: sessionId,
85
- questionId: z.string().min(1).max(128),
86
- choiceId: z.string().max(128).optional(),
87
- answer: z.string().trim().min(1).max(12_000),
88
- viewId: z.uuid().optional(),
89
- mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
90
- execMode: execModeSchema.optional(),
91
- persona: personaSchema.optional(),
120
+ z.object({
121
+ action: z.literal('handoff'),
122
+ fromSession: sessionIdSchema.optional(),
123
+ fromRoleName: z.string().max(60).optional(),
124
+ targetRoleId: z.string().min(1).max(40),
125
+ targetSession: sessionIdSchema.optional(),
126
+ text: z.string().trim().max(16_000).default(''),
92
127
  canvas: canvasSchema.optional(),
93
128
  }),
94
- z.strictObject({
95
- action: z.literal('command_decision'), session: sessionId,
96
- commandId: z.string().min(1).max(128),
97
- decision: z.enum(['allow', 'session_allow', 'deny']),
98
- viewId: z.uuid().optional(),
99
- mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
100
- execMode: execModeSchema.optional(),
101
- persona: personaSchema.optional(),
102
- canvas: canvasSchema.optional(),
129
+ z.object({
130
+ action: z.literal('answer'),
131
+ session: sessionIdSchema,
132
+ questionId: z.string().min(1).max(128),
133
+ answer: z.string().trim().min(1).max(12_000),
103
134
  }),
104
- z.strictObject({
105
- action: z.literal('steer'), session: sessionId,
135
+ z.object({
136
+ action: z.literal('steer'),
137
+ session: sessionIdSchema,
106
138
  text: z.string().trim().min(1).max(4_000),
107
139
  }),
108
- z.strictObject({
109
- action: z.literal('dispatch'), session: sessionId,
110
- executorId: z.string().min(1).max(128).optional(),
111
- text: z.string().trim().max(12_000).default(''),
112
- viewId: z.uuid().optional(),
113
- canvas: canvasSchema.optional(),
140
+ z.object({
141
+ action: z.enum(['cancel', 'close']),
142
+ session: sessionIdSchema,
114
143
  }),
115
- z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
116
144
  ]);
117
145
 
118
- async function readJsonBody(req, maxBytes = 96 * 1024) {
146
+ async function readJsonBody(req, maxBytes = 128 * 1024) {
119
147
  const chunks = [];
120
148
  let bytes = 0;
121
149
  for await (const chunk of req) {
122
150
  bytes += chunk.length;
123
- if (bytes > maxBytes) throw new DocumentError('发送内容过长。', 413);
151
+ if (bytes > maxBytes) throw new DocumentError('请求体过大。', 413);
124
152
  chunks.push(chunk);
125
153
  }
126
154
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
127
155
  }
128
156
 
129
- async function readRequest(req) {
130
- const raw = await readJsonBody(req, 96 * 1024);
131
- const parsed = requestSchema.safeParse(raw);
132
- if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
133
- return parsed.data;
134
- }
135
-
136
- function promptBlocks(workspace, input) {
137
- const context = {
138
- workspace,
139
- ...(input.viewId && { viewId: input.viewId }),
140
- ...(input.canvas && {
141
- file: input.canvas.file,
142
- revision: input.canvas.revision,
143
- selection: input.canvas.selection,
144
- ...(input.canvas.objectSelection?.length ? { objectSelection: input.canvas.objectSelection } : {}),
145
- }),
146
- };
147
- return [
148
- { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径,objectSelection 是选中的多实例画布组件或子区域靶点。' },
149
- { type: 'text', text: JSON.stringify(context) },
150
- { type: 'text', text: '用户指令:\n' + input.text },
151
- ];
157
+ function sendJson(res, status, data) {
158
+ res.writeHead(status, {
159
+ 'content-type': 'application/json; charset=utf-8',
160
+ 'cache-control': 'no-store',
161
+ 'x-content-type-options': 'nosniff',
162
+ });
163
+ res.end(JSON.stringify(data));
152
164
  }
153
165
 
154
- function startAgent({ workspace, command, args, env, mcpName, emit, closed }) {
155
- const proc = spawn(command, args, {
156
- cwd: workspace,
157
- stdio: ['pipe', 'pipe', 'pipe'],
158
- windowsHide: true,
159
- env: { ...process.env, ...env },
160
- });
161
- proc.stderr.resume();
162
- const cladoCalls = new Map();
163
- proc.on('error', cause => {
164
- const message = cause.code === 'ENOENT'
165
- ? '找不到 ACP 启动命令。请安装适配器或在「灵感」插件设置里填写其路径。'
166
- : '无法启动 ACP 进程。';
167
- closed(new Error(message));
168
- });
169
- proc.on('exit', code => closed(new Error('ACP 进程已退出' + (code ? '(退出码 ' + code + ')' : '') + '。请检查启动命令和登录状态。')));
170
- const connection = client()
171
- .onRequest('session/request_permission', ({ params }) => {
172
- const option = params.options.find(option => option.kind === 'allow_once');
173
- if (option && params._meta?.is_mcp_tool_approval === true &&
174
- cladoCalls.get(params.toolCall.toolCallId) === params.sessionId) {
175
- return { outcome: { outcome: 'selected', optionId: option.optionId } };
176
- }
177
- emit({ type: 'status', text: '已拒绝额外的本机执行权限' });
178
- return { outcome: { outcome: 'cancelled' } };
179
- })
180
- .onNotification('session/update', ({ params }) => {
181
- const update = params.update;
182
- const kind = update.sessionUpdate;
183
- if (kind === 'agent_message_chunk' && update.content?.type === 'text') {
184
- emit({ type: 'text', text: update.content.text });
185
- } else if (kind === 'tool_call' || kind === 'tool_call_update') {
186
- const title = update.title?.slice(0, 160);
187
- if (kind === 'tool_call' && title?.startsWith('mcp.' + mcpName + '.clado_')) {
188
- cladoCalls.set(update.toolCallId, params.sessionId);
189
- }
190
- if (update.status === 'completed' || update.status === 'failed') cladoCalls.delete(update.toolCallId);
191
- emit({ type: 'tool', id: update.toolCallId, title, status: update.status });
192
- }
193
- })
194
- .connect(ndJsonStream(Writable.toWeb(proc.stdin), Readable.toWeb(proc.stdout)));
195
- connection.closed.then(() => closed(new Error('ACP 已断开。请检查适配器或重新发送。')));
196
- return {
197
- rpc: connection.agent,
198
- dispose() {
199
- connection.close();
200
- proc.stdin.destroy();
201
- if (proc.exitCode === null && proc.signalCode === null) proc.kill();
202
- },
203
- };
166
+ function assertSameOriginPost(req, remote = false) {
167
+ const origin = req.headers.origin;
168
+ if (!origin) return;
169
+ const host = String(req.headers.host || '').trim();
170
+ if (origin === 'http://' + host) return;
171
+ if (remote) {
172
+ const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
173
+ const allowed = new Set([host]);
174
+ if (forwardedHost) allowed.add(forwardedHost);
175
+ for (const h of allowed) {
176
+ if (h && (origin === 'http://' + h || origin === 'https://' + h)) return;
177
+ }
178
+ }
179
+ throw new DocumentError('来源不匹配。', 403);
204
180
  }
205
181
 
206
182
  export function createAgentHandler({
207
- workspace, mcpUrl,
208
- command = process.env.CLADO_CODEX_ACP_PATH || 'codex-acp',
209
- args = [],
210
- resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
211
- resolveSettings = null,
212
- saveSettings = null,
183
+ workspace,
184
+ mcpUrl,
213
185
  resolveRuntimeInfo = null,
214
186
  workspaceService = null,
215
187
  events = null,
216
- fetchImpl = fetch,
188
+ sessionFactory = null,
189
+ remote = false,
190
+ autoStartScheduler = true,
217
191
  }) {
218
- const sessions = new Map();
219
- const mcpName = () => 'clado_canvas_' + new URL(mcpUrl()).port;
220
- const readSettings = () => {
221
- const base = resolveSettings ? resolveSettings() : {};
222
- const launch = resolveLaunch();
223
- return { ...launch, ...base };
224
- };
225
-
226
- function buildLlmState(settings = {}) {
227
- const creds = resolveProviderCredentials(settings);
228
- const profiles = {};
229
- for (const preset of PROVIDER_PRESETS) {
230
- const raw = settings.providers?.[preset.id] || {};
231
- const isLegacyMatch = !settings.providers && (settings.providerId || 'openai') === preset.id;
232
- const key = raw.apiKey ?? (isLegacyMatch ? settings.apiKey : '');
233
- profiles[preset.id] = {
234
- label: raw.label || preset.label,
235
- protocol: raw.protocol || preset.protocol,
236
- baseUrl: raw.baseUrl || (isLegacyMatch ? settings.baseUrl : '') || preset.defaultBaseUrl,
237
- model: raw.model || (isLegacyMatch ? settings.model : '') || preset.defaultModel,
238
- models: Array.isArray(raw.models) && raw.models.length ? raw.models : preset.models,
239
- hasApiKey: Boolean(String(key || '').trim()),
240
- maskedKey: maskApiKey(key),
241
- requiresKey: preset.requiresKey !== false,
242
- };
243
- }
192
+ const getRuntime = targetWorkspace => {
193
+ const ws = targetWorkspace || (typeof workspace === 'function' ? workspace() : workspace);
194
+ const info = resolveRuntimeInfo ? resolveRuntimeInfo(ws) : null;
244
195
  return {
245
- configured: creds.configured,
246
- providerId: creds.providerId,
247
- providerLabel: creds.providerLabel,
248
- protocol: creds.provider,
249
- baseUrl: creds.baseUrl,
250
- model: creds.model,
251
- hasApiKey: creds.hasApiKey,
252
- presets: PROVIDER_PRESETS,
253
- profiles,
254
- quickModels: listConfiguredModels(settings),
255
- acpCommand: settings.command || 'zcode-acp-server',
256
- acpArgs: Array.isArray(settings.args) ? settings.args : [],
196
+ workspace: ws,
197
+ stateDir: info?.stateDir || (ws + '/.clado'),
198
+ documentRoot: info?.documentRoot || ws,
199
+ pluginDescriptors: info?.pluginDescriptors || [],
257
200
  };
258
- }
201
+ };
259
202
 
260
- function runningSessionIds(targetWorkspace) {
261
- const set = new Set();
262
- for (const s of sessions.values()) {
263
- if (s.running && s.workspace === targetWorkspace) set.add(s.key);
264
- }
265
- return set;
266
- }
203
+ let bridge = null;
204
+
205
+ const automationEngine = createAutomationEngine({
206
+ resolveStateDir: ws => getRuntime(ws).stateDir,
207
+ listSessionsForStateDir: stateDir => listSessions(stateDir, { includeArchived: false, includeMessages: false }),
208
+ events,
209
+ autoStartTimer: autoStartScheduler,
210
+ onTrigger: async ({ workspace: ws, stateDir, rule, triggerMeta }) => {
211
+ if (!bridge) return;
212
+ const rt = getRuntime(ws);
213
+ const agentDir = resolvePiAgentDir();
214
+ const eventLines = Array.isArray(triggerMeta?.events) && triggerMeta.events.length
215
+ ? '\n\n触发事件摘要:\n' + triggerMeta.events.slice(-8).map(e => `- [${e.type}] ${JSON.stringify(e.payload || {}).slice(0, 220)}`).join('\n')
216
+ : (triggerMeta?.reason === 'schedule'
217
+ ? `\n\n触发方式:定时巡检(窗口:最近 ${triggerMeta.activeWindowMinutes || 20} 分钟${Array.isArray(triggerMeta.activeSessions) && triggerMeta.activeSessions.length ? `,活跃会话:${triggerMeta.activeSessions.map(s => `${s.title}(${s.id})`).join('、')}` : ''})`
218
+ : '');
219
+ const fullMessage = `${rule.target.prompt}${eventLines}`;
220
+ await bridge.sendCrossSessionMessage({
221
+ workspace: rt.workspace,
222
+ stateDir,
223
+ documentRoot: rt.documentRoot,
224
+ fromRoleName: `自动化 · ${rule.name}`,
225
+ targetSessionId: rule.target.sessionId || '',
226
+ targetRoleId: rule.target.roleId || 'archivist',
227
+ message: fullMessage,
228
+ wait: false,
229
+ automationRuleId: rule.id,
230
+ });
231
+ events?.emit(rt.workspace, 'agent.sessions', { action: 'automation_triggered', ruleId: rule.id });
232
+ },
233
+ });
267
234
 
268
- function activePeerLocksFor(targetWorkspace, excludeSessionKey) {
269
- const locks = [];
270
- for (const s of sessions.values()) {
271
- if (s.running && s.workspace === targetWorkspace && s.key !== excludeSessionKey && s.activeCardTarget) {
272
- locks.push({ peerId: s.key, peerName: s.title || '同伴', target: s.activeCardTarget });
273
- }
235
+ const handleAutomationOp = async (ws, params = {}) => {
236
+ const rt = getRuntime(ws);
237
+ automationEngine.registerWorkspace(rt.workspace);
238
+ const act = String(params.action || 'list').trim();
239
+ if (act === 'events_catalog') {
240
+ return { ok: true, catalog: SYSTEM_EVENT_CATALOG };
274
241
  }
275
- return locks;
276
- }
277
-
278
- function emitSessionSync(targetWorkspace, stateDir, autoArchiveHours = 24) {
279
- if (!events || !stateDir) return;
280
- try {
281
- const list = listSessionRecords(stateDir, {
282
- limit: 40,
283
- includeArchived: false,
284
- autoArchiveHours,
285
- runningIds: runningSessionIds(targetWorkspace),
286
- });
287
- events.emit(targetWorkspace, 'agent.sessions', { sessions: list });
288
- } catch {}
289
- }
242
+ if (act === 'list') {
243
+ return { ok: true, ...readAutomationsState(rt.stateDir) };
244
+ }
245
+ if (act === 'save') {
246
+ const saved = saveAutomationRule(rt.stateDir, params.rule || params);
247
+ return { ok: true, ...saved };
248
+ }
249
+ if (act === 'delete') {
250
+ const removed = deleteAutomationRule(rt.stateDir, params.ruleId || params.id);
251
+ return { ok: true, ...removed };
252
+ }
253
+ if (act === 'pause' || act === 'resume') {
254
+ const state = setAutomationsPaused(rt.stateDir, act === 'pause');
255
+ return { ok: true, ...state };
256
+ }
257
+ if (act === 'run_now') {
258
+ return await automationEngine.runRuleNow(rt.workspace, params.ruleId || params.id);
259
+ }
260
+ throw new DocumentError(`不支持的自动化操作:${act}`, 400);
261
+ };
290
262
 
291
- function close(session, error) {
292
- if (sessions.get(session.key) !== session) return;
293
- sessions.delete(session.key);
294
- clearTimeout(session.idle);
295
- session.abortController?.abort();
296
- session.fail?.(error || new Error('Agent 会话已关闭。'));
297
- session.agent?.dispose();
298
- }
263
+ bridge = createPiBridge({
264
+ workspaceService,
265
+ events,
266
+ sessionFactory,
267
+ onSystemEvent: (ws, eventType, payload) => {
268
+ automationEngine.notifyEvent(ws, eventType, payload);
269
+ },
270
+ automationOps: {
271
+ handle: params => handleAutomationOp(params?.workspace || null, params),
272
+ },
273
+ });
299
274
 
300
- async function connectAcp(session, launchOverride = null) {
301
- const launch = launchOverride || resolveLaunch();
302
- session.agent = startAgent({
303
- workspace: session.workspace,
304
- command: launch.command,
305
- args: launch.args || [],
306
- env: launch.env || {},
307
- mcpName: mcpName(),
308
- emit: event => session.emit?.(event),
309
- closed: error => close(session, error),
310
- });
311
- const { rpc } = session.agent;
312
- const init = await rpc.request('initialize', {
313
- protocolVersion: PROTOCOL_VERSION,
314
- clientInfo: { name: 'clado', title: 'Clado', version: VERSION },
315
- clientCapabilities: {},
316
- });
317
- if (init.protocolVersion !== PROTOCOL_VERSION) throw new Error('当前适配器不支持 Clado 的 ACP 协议版本。');
318
- session.hasMcp = !!init.agentCapabilities?.mcpCapabilities?.http;
319
- const result = await rpc.request('session/new', {
320
- cwd: session.workspace,
321
- mcpServers: session.hasMcp ? [{ name: mcpName(), type: 'http', url: mcpUrl(), headers: [] }] : [],
275
+ async function buildFullMeta(targetWorkspace) {
276
+ const rt = getRuntime(targetWorkspace);
277
+ automationEngine.registerWorkspace(rt.workspace);
278
+ const agentDir = resolvePiAgentDir();
279
+ const [modelsInfo, ecosystem] = await Promise.all([
280
+ listProvidersAndModels(rt.workspace, agentDir),
281
+ inspectPiEcosystem(rt.workspace, agentDir),
282
+ ]);
283
+ const runtimeSettings = readRuntimeSettings(rt.workspace, agentDir, modelsInfo.activeContextWindow);
284
+ const piSettings = readFullPiSettings(rt.workspace, agentDir, modelsInfo.activeContextWindow);
285
+ const workspacePrefs = readWorkspacePrefs(rt.workspace);
286
+ const roles = listRoles(agentDir, rt.workspace);
287
+ const memory = readAgentsMemory(rt.workspace);
288
+ const memoryBundle = readMemoryBundle(rt.workspace, agentDir);
289
+ const hooksConfig = readHooksConfig(rt.workspace, agentDir);
290
+ const permissionsConfig = readPermissionsConfig(rt.workspace, agentDir);
291
+ const platformDocs = ensureCladoPlatformDocs(agentDir);
292
+ const canvasComponents = readCanvasComponentsConfig(agentDir);
293
+ const rawSessions = listSessions(rt.stateDir, { includeArchived: true, messageLimit: 30, agentDir });
294
+ const sessions = bridge.overlayLiveSessions(rt.workspace, rawSessions);
295
+ const automations = readAutomationsState(rt.stateDir);
296
+ const mcpRawJson = readPiMcpRawJson(rt.workspace, agentDir);
297
+ const pluginParams = readPluginParams(rt.workspace, rt.stateDir, agentDir);
298
+ const liveRuntime = bridge.inspectRuntime(rt.workspace);
299
+ const enrichedMcpServers = listPiMcpServers(rt.workspace, agentDir, {
300
+ runtimeServers: liveRuntime?.runtimeServers || [],
301
+ liveMcpTools: liveRuntime?.mcpTools || [],
322
302
  });
323
- session.id = result.sessionId;
324
- }
303
+ const enrichedEcosystem = { ...ecosystem, mcpServers: enrichedMcpServers };
304
+ const installedWsPlugins = listInstalledWorkspacePlugins(rt.stateDir);
305
+ const descriptorById = new Map((rt.pluginDescriptors || []).map(p => [p.id, p]));
306
+ const workspacePluginsMap = new Map();
307
+ for (const p of rt.pluginDescriptors || []) workspacePluginsMap.set(p.id, { ...p });
308
+ for (const inst of installedWsPlugins) {
309
+ const prev = workspacePluginsMap.get(inst.id) || {};
310
+ workspacePluginsMap.set(inst.id, {
311
+ ...prev,
312
+ ...inst,
313
+ active: descriptorById.has(inst.id),
314
+ });
315
+ }
325
316
 
326
- function resolveMeta(targetWorkspace) {
327
- const settings = readSettings();
328
- const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
329
- const debugBundle = readAgentDebugConfig(rtInfo.stateDir);
330
- const executors = discoverExecutors({
331
- stateDir: rtInfo.stateDir,
332
- settings,
333
- pluginDescriptors: rtInfo.pluginDescriptors || [],
334
- });
335
- const llm = buildLlmState(settings);
336
- const builtinConfigured = Boolean(llm.configured);
337
- // Clado 产品定位为原生 Agent 优先:只要挂载了工作区设置(resolveSettings),主引擎默认恒为 builtin,
338
- // 仅当显式强制设为 acp(或纯 ACP 单元测试未提供 resolveSettings)时才退回 acp。
339
- const activeEngine = !resolveSettings
340
- ? (builtinConfigured ? 'builtin' : 'acp')
341
- : (settings.mode === 'acp' ? 'acp' : 'builtin');
342
317
  return {
343
- settings,
344
- llm,
345
- debugConfig: debugBundle.config,
346
- hasWorkspaceOverride: debugBundle.hasWorkspaceOverride,
347
- rtInfo,
348
- executors,
349
- builtinConfigured,
350
- activeEngine,
351
- provider: llm.protocol,
352
- providerId: llm.providerId,
353
- providerLabel: llm.providerLabel,
354
- model: llm.model,
355
- defaultPersona: settings.persona || 'architect',
318
+ engine: 'pi',
319
+ version: VERSION,
320
+ workspace: rt.workspace,
321
+ stateDir: rt.stateDir,
322
+ documentRoot: rt.documentRoot,
323
+ remote: Boolean(remote),
324
+ mcpUrl: typeof mcpUrl === 'function' ? mcpUrl() : (mcpUrl || ''),
325
+ agentDir,
326
+ defaultProvider: modelsInfo.defaultProvider,
327
+ defaultModel: modelsInfo.defaultModel,
328
+ activeModelLabel: modelsInfo.activeModelLabel,
329
+ activeContextWindow: modelsInfo.activeContextWindow,
330
+ activeMaxTokens: modelsInfo.activeMaxTokens,
331
+ runtimeSettings,
332
+ piSettings,
333
+ workspacePrefs,
334
+ providers: modelsInfo.providers,
335
+ hiddenPresets: modelsInfo.hiddenPresets || [],
336
+ configuredModels: modelsInfo.configuredModels,
337
+ roles,
338
+ ecosystem: enrichedEcosystem,
339
+ mcpRawJson,
340
+ pluginParams,
341
+ canvasComponents,
342
+ workspacePlugins: [...workspacePluginsMap.values()],
343
+ memory,
344
+ memoryBundle,
345
+ hooksConfig,
346
+ permissionsConfig,
347
+ platformDocs,
348
+ automations,
349
+ eventCatalog: SYSTEM_EVENT_CATALOG,
350
+ activeRuns: bridge.listActiveRuns(rt.workspace),
351
+ liveRuntime,
352
+ sessions,
356
353
  };
357
354
  }
358
355
 
359
- function ensureMemorySession(targetWorkspace, meta, id, defaults = {}) {
360
- let session = sessions.get(id);
361
- if (!session) {
362
- const saved = loadSessionRecord(meta.rtInfo.stateDir, id);
363
- const persona = defaults.persona || saved?.persona || meta.defaultPersona;
364
- session = {
365
- key: id,
366
- workspace: targetWorkspace,
367
- title: defaults.title || saved?.title || '',
368
- persona,
369
- pal: saved?.pal || paletteForPersona(persona),
370
- engine: (defaults.engine || saved?.engine) === 'acp' ? 'acp' : 'builtin',
371
- mode: defaults.mode || saved?.mode || 'design',
372
- execMode: defaults.execMode || saved?.execMode || 'act',
373
- liveStatus: saved?.liveStatus || '',
374
- todos: Array.isArray(saved?.todos) ? saved.todos : [],
375
- calledBy: saved?.calledBy || null,
376
- peerHopCount: saved?.peerHopCount || 0,
377
- canvasBaseline: saved?.canvasBaseline || null,
378
- checkpoints: Array.isArray(saved?.checkpoints) ? saved.checkpoints : [],
379
- history: Array.isArray(saved?.messages) ? saved.messages : [],
380
- uiMessages: Array.isArray(saved?.uiMessages) ? saved.uiMessages : [],
381
- pendingQuestion: saved?.pendingQuestion || null,
382
- pendingCommand: saved?.pendingCommand || null,
383
- incomingPeerMessages: [],
384
- steeringQueue: [],
385
- commandAutoAllow: false,
386
- };
387
- sessions.set(id, session);
388
- }
389
- return session;
390
- }
391
-
392
- /**
393
- * 后台异步唤醒平级同伴会话执行一轮任务(用于 spawn_peer / message_peer request)。
394
- */
395
- async function runBackgroundPeerTurn(targetWorkspace, peerSession, taskText, { hopCount = 1 } = {}) {
396
- if (peerSession.running) return;
397
- const meta = resolveMeta(targetWorkspace);
398
- if (!meta.builtinConfigured) return;
399
-
400
- peerSession.running = true;
401
- peerSession.cancelled = false;
402
- peerSession.peerHopCount = hopCount;
403
- peerSession.abortController = new AbortController();
404
- peerSession.liveStatus = '收到呼叫,正在处理…';
405
-
406
- if (meta.rtInfo.stateDir) {
407
- saveSessionRecord(meta.rtInfo.stateDir, {
408
- id: peerSession.key,
409
- title: peerSession.title,
410
- persona: peerSession.persona,
411
- pal: peerSession.pal,
412
- mode: peerSession.mode,
413
- execMode: peerSession.execMode,
414
- archived: false,
415
- liveStatus: peerSession.liveStatus,
416
- todos: peerSession.todos,
417
- calledBy: peerSession.calledBy,
418
- peerHopCount: peerSession.peerHopCount,
419
- messages: peerSession.history,
420
- uiMessages: peerSession.uiMessages,
421
- });
422
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
423
- }
424
-
425
- let thinkingBuf = '';
426
- let textBuf = '';
427
- let changesBuf = [];
428
- const peerCoord = createPeerCoordinator(targetWorkspace, meta, peerSession);
429
-
430
- try {
431
- const incoming = peerSession.incomingPeerMessages.splice(0);
432
- const result = await runVerticalAgent({
433
- workspace: targetWorkspace,
434
- rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
435
- documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
436
- stateDir: meta.rtInfo.stateDir,
437
- workspaceService,
438
- events,
439
- config: meta.settings,
440
- debugConfig: meta.debugConfig,
441
- history: peerSession.history,
442
- canvasBaseline: peerSession.canvasBaseline,
443
- activePeerLocks: activePeerLocksFor(targetWorkspace, peerSession.key),
444
- incomingPeerMessages: incoming,
445
- peerCoordinator: peerCoord,
446
- sessionCommandAutoAllow: peerSession.commandAutoAllow,
447
- drainSteering: () => peerSession.steeringQueue.splice(0),
448
- input: { text: taskText },
449
- mode: peerSession.mode,
450
- execMode: peerSession.execMode,
451
- persona: peerSession.persona,
452
- todos: peerSession.todos,
453
- signal: peerSession.abortController.signal,
454
- fetchImpl,
455
- emit: ev => {
456
- if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
457
- else if (ev.type === 'text' && ev.text) textBuf += ev.text;
458
- else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
459
- else if (ev.type === 'todos' && Array.isArray(ev.todos)) peerSession.todos = ev.todos;
460
- else if (ev.type === 'status' && ev.text) {
461
- peerSession.liveStatus = ev.text;
462
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
463
- }
464
- },
465
- });
466
-
467
- peerSession.history = Array.isArray(result.conversation) ? result.conversation : peerSession.history;
468
- peerSession.todos = Array.isArray(result.todos) ? result.todos : peerSession.todos;
469
- peerSession.canvasBaseline = result.nextBaseline || peerSession.canvasBaseline;
470
- peerSession.pendingQuestion = result.pendingQuestion || null;
471
- peerSession.pendingCommand = result.pendingCommand || null;
472
- if (result.checkpoint) peerSession.checkpoints.push(result.checkpoint);
356
+ return {
357
+ automationEngine,
358
+ async reloadWorkspace(targetWorkspace) {
359
+ const rt = getRuntime(targetWorkspace);
360
+ return await bridge.reloadWorkspaceSessions(rt.workspace);
361
+ },
362
+ notifySystemEvent(targetWorkspace, eventType, payload = {}) {
363
+ const rt = getRuntime(targetWorkspace);
364
+ automationEngine.notifyEvent(rt.workspace, eventType, payload);
365
+ },
473
366
 
474
- if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
475
- peerSession.uiMessages.push({
476
- role: 'assistant',
477
- thinking: thinkingBuf,
478
- text: textBuf,
479
- changes: changesBuf,
480
- checkpointId: result.checkpoint?.id || null,
481
- question: result.pendingQuestion || null,
482
- commandApproval: result.pendingCommand || null,
483
- });
484
- }
485
- peerSession.liveStatus = result.pendingCommand
486
- ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
487
- : result.pendingQuestion
488
- ? '等待确认方案…'
489
- : '已完成协作任务';
490
- } catch (err) {
491
- peerSession.liveStatus = '任务中断';
492
- peerSession.uiMessages.push({ role: 'assistant', text: `执行异常:${err.message || '失败'}` });
493
- } finally {
494
- peerSession.running = false;
495
- peerSession.abortController = undefined;
496
- if (meta.rtInfo.stateDir) {
497
- saveSessionRecord(meta.rtInfo.stateDir, {
498
- id: peerSession.key,
499
- title: peerSession.title,
500
- persona: peerSession.persona,
501
- pal: peerSession.pal,
502
- mode: peerSession.mode,
503
- execMode: peerSession.execMode,
504
- archived: false,
505
- liveStatus: peerSession.liveStatus,
506
- todos: peerSession.todos,
507
- calledBy: peerSession.calledBy,
508
- peerHopCount: peerSession.peerHopCount,
509
- canvasBaseline: peerSession.canvasBaseline,
510
- checkpoints: peerSession.checkpoints,
511
- messages: peerSession.history,
512
- uiMessages: peerSession.uiMessages,
513
- pendingQuestion: peerSession.pendingQuestion,
514
- pendingCommand: peerSession.pendingCommand,
367
+ async handleMcpSessions(args = {}) {
368
+ const rt = getRuntime(args.workspace);
369
+ automationEngine.registerWorkspace(rt.workspace);
370
+ const agentDir = resolvePiAgentDir();
371
+ const act = String(args.action || 'list').trim();
372
+ if (act === 'list') {
373
+ const list = listSessions(rt.stateDir, {
374
+ includeArchived: Boolean(args.includeArchived),
375
+ includeMessages: false,
376
+ sinceMinutes: Number(args.sinceMinutes) || 0,
377
+ agentDir,
515
378
  });
516
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
379
+ return { ok: true, workspace: rt.workspace, count: list.length, sessions: list };
517
380
  }
518
- }
519
- }
520
-
521
- function createPeerCoordinator(targetWorkspace, meta, callerSession) {
522
- const stateDir = meta.rtInfo.stateDir;
523
- if (!stateDir) return null;
524
-
525
- return {
526
- async spawnPeer({ name, persona = 'qa', task = '' }) {
527
- const cleanName = String(name || '协作分身').trim().slice(0, 32);
528
- const id = randomUUID();
529
- const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
530
- const peer = ensureMemorySession(targetWorkspace, meta, id, {
531
- title: cleanName,
532
- persona: resolved.id,
533
- mode: persona === 'qa' ? 'qa' : persona === 'auditor' ? 'audit' : 'design',
534
- execMode: persona === 'auditor' ? 'plan' : 'act',
381
+ if (act === 'read') {
382
+ const transcript = bridge.readSessionTranscript(rt.stateDir, args.sessionId, {
383
+ limit: Number(args.limit) || 12,
384
+ agentDir,
535
385
  });
536
- peer.title = cleanName;
537
- peer.pal = resolved.pal || paletteForPersona(persona);
538
- peer.calledBy = {
539
- fromId: callerSession.key,
540
- fromName: callerSession.title || '主会话',
541
- pal: callerSession.pal || 'blue',
542
- at: Date.now(),
543
- };
544
- const fullTask = [
545
- resolved.initContext ? `【角色初始上下文】${resolved.initContext}` : '',
546
- `来自同伴「${callerSession.title || '上游会话'}」的委派任务:\n${task}`,
547
- ].filter(Boolean).join('\n\n');
548
-
549
- peer.uiMessages.push({
550
- role: 'peer_in',
551
- fromName: callerSession.title || '上游会话',
552
- fromPal: callerSession.pal || 'blue',
553
- kind: 'request',
554
- text: task,
555
- });
556
- callerSession.uiMessages.push({
557
- role: 'peer_out',
558
- toName: cleanName,
559
- kind: 'request',
560
- text: task,
386
+ if (!transcript) throw new DocumentError(`找不到会话:${args.sessionId}`, 404);
387
+ return { ok: true, workspace: rt.workspace, ...transcript };
388
+ }
389
+ if (act === 'open') {
390
+ const opened = bridge.openOrCreatePeerSession(rt.stateDir, {
391
+ roleId: args.roleId || 'architect',
392
+ title: args.title || '',
393
+ reuseLatest: args.reuseLatest !== false,
394
+ workspace: rt.workspace,
395
+ agentDir,
561
396
  });
562
-
563
- saveSessionRecord(stateDir, {
564
- id: peer.key,
565
- title: peer.title,
566
- persona: peer.persona,
567
- pal: peer.pal,
568
- mode: peer.mode,
569
- execMode: peer.execMode,
570
- archived: false,
571
- liveStatus: '已就绪,启动中…',
572
- calledBy: peer.calledBy,
573
- messages: peer.history,
574
- uiMessages: peer.uiMessages,
397
+ return { ok: true, workspace: rt.workspace, ...opened };
398
+ }
399
+ if (act === 'send') {
400
+ const res = await bridge.sendCrossSessionMessage({
401
+ workspace: rt.workspace,
402
+ stateDir: rt.stateDir,
403
+ documentRoot: rt.documentRoot,
404
+ fromSessionId: args.fromSessionId || '',
405
+ fromRoleName: args.fromRoleName || '外部 MCP',
406
+ targetSessionId: args.targetSessionId || '',
407
+ targetRoleId: args.targetRoleId || '',
408
+ message: args.message || '',
409
+ wait: Boolean(args.wait),
575
410
  });
576
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
577
-
578
- const nextHop = (callerSession.peerHopCount || 0) + 1;
579
- if (nextHop <= MAX_PEER_HOPS) {
580
- setImmediate(() => {
581
- runBackgroundPeerTurn(targetWorkspace, peer, fullTask, { hopCount: nextHop }).catch(() => {});
582
- });
583
- }
584
- return { spawned: true, peerId: id, name: cleanName, persona: resolved.id };
585
- },
586
-
587
- async messagePeer({ target, message, kind = 'request' }) {
588
- const q = String(target || '').trim();
589
- const msgText = String(message || '').trim().slice(0, 4000);
590
- if (!q || !msgText) throw new Error('target 与 message 必填。');
591
-
592
- const all = listSessionRecords(stateDir, { limit: 60, includeArchived: true, autoArchiveHours: 0 });
593
- const hit = all.find(s => s.id === q || s.title === q || s.title.includes(q));
594
- if (!hit) {
595
- return { delivered: false, error: `未找到名为「${q}」的同伴会话,请先使用 spawn_peer 创建。` };
596
- }
597
- if (hit.id === callerSession.key) {
598
- return { delivered: false, error: '不能向当前会话自身发送同伴消息。' };
599
- }
411
+ return { workspace: rt.workspace, ...res };
412
+ }
413
+ throw new DocumentError(`不支持的会话操作:${act}`, 400);
414
+ },
600
415
 
601
- const peer = ensureMemorySession(targetWorkspace, meta, hit.id);
602
- peer.calledBy = {
603
- fromId: callerSession.key,
604
- fromName: callerSession.title || '同伴',
605
- pal: callerSession.pal || 'blue',
606
- at: Date.now(),
607
- };
608
- peer.incomingPeerMessages.push({
609
- fromId: callerSession.key,
610
- fromName: callerSession.title || '同伴',
611
- kind: kind === 'notify' ? 'notify' : 'request',
612
- text: msgText,
613
- });
614
- peer.uiMessages.push({
615
- role: 'peer_in',
616
- fromName: callerSession.title || '同伴',
617
- fromPal: callerSession.pal || 'blue',
618
- kind: kind === 'notify' ? 'notify' : 'request',
619
- text: msgText,
620
- });
621
- callerSession.uiMessages.push({
622
- role: 'peer_out',
623
- toName: peer.title || hit.title,
624
- kind: kind === 'notify' ? 'notify' : 'request',
625
- text: msgText,
626
- });
416
+ async handleMcpAutomations(args = {}) {
417
+ return await handleAutomationOp(args.workspace, args);
418
+ },
627
419
 
628
- const nextHop = (callerSession.peerHopCount || 0) + 1;
629
- const circuitBroken = nextHop > MAX_PEER_HOPS;
630
- peer.liveStatus = kind === 'notify'
631
- ? `收到「${callerSession.title || '同伴'}」通知`
632
- : circuitBroken
633
- ? `已达 ${MAX_PEER_HOPS} 跳上限,转入静息待命`
634
- : `收到「${callerSession.title || '同伴'}」呼叫…`;
420
+ async handleMeta(req, res, targetWorkspace) {
421
+ if (req.method !== 'GET') throw new DocumentError('仅支持 GET。', 405);
422
+ const data = await buildFullMeta(targetWorkspace);
423
+ sendJson(res, 200, data);
424
+ },
635
425
 
636
- saveSessionRecord(stateDir, {
637
- id: peer.key,
638
- title: peer.title || hit.title,
639
- persona: peer.persona,
640
- pal: peer.pal,
641
- mode: peer.mode,
642
- execMode: peer.execMode,
643
- archived: false,
644
- liveStatus: peer.liveStatus,
645
- calledBy: peer.calledBy,
646
- peerHopCount: nextHop,
647
- messages: peer.history,
648
- uiMessages: peer.uiMessages,
426
+ async handleAutomations(req, res, url, targetWorkspace) {
427
+ const rt = getRuntime(targetWorkspace);
428
+ automationEngine.registerWorkspace(rt.workspace);
429
+ if (req.method === 'GET') {
430
+ const state = readAutomationsState(rt.stateDir);
431
+ sendJson(res, 200, {
432
+ ok: true,
433
+ ...state,
434
+ eventCatalog: SYSTEM_EVENT_CATALOG,
649
435
  });
650
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
651
-
652
- if (kind !== 'notify' && !circuitBroken && !peer.running) {
653
- setImmediate(() => {
654
- runBackgroundPeerTurn(targetWorkspace, peer, `请处理同伴「${callerSession.title || '同伴'}」发来的协作请求:\n${msgText}`, { hopCount: nextHop }).catch(() => {});
655
- });
656
- }
657
-
658
- return {
659
- delivered: true,
660
- peerId: peer.key,
661
- peerName: peer.title || hit.title,
662
- kind,
663
- circuitBroken,
664
- };
665
- },
666
- };
667
- }
668
-
669
- function handleMeta(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
670
- const host = req.headers.host || '';
671
- if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
672
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
673
- const meta = resolveMeta(targetWorkspace);
674
- const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
675
- const pluginMcp = Array.isArray(meta.rtInfo.pluginMcp) ? meta.rtInfo.pluginMcp : [];
676
- const pluginPersonas = Array.isArray(meta.rtInfo.pluginPersonas) ? meta.rtInfo.pluginPersonas : [];
677
- const customPersonasMap = meta.debugConfig?.personas || {};
678
- const mergedPersonas = new Map(BUILTIN_PERSONAS.map(p => [p.id, { id: p.id, name: p.name, summary: p.summary, builtin: true }]));
679
- for (const p of pluginPersonas) {
680
- mergedPersonas.set(p.id, { id: p.id, name: p.name, summary: (p.prompt || '').slice(0, 48), pluginId: p.pluginId });
681
- }
682
- for (const [k, v] of Object.entries(customPersonasMap)) {
683
- if (!v || typeof v !== 'object' || !v.custom) continue;
684
- if (!mergedPersonas.has(k)) {
685
- mergedPersonas.set(k, { id: k, name: v.name || k, summary: (v.prompt || '').slice(0, 48), custom: true });
436
+ return;
686
437
  }
687
- }
688
- res.writeHead(200, {
689
- 'content-type': 'application/json; charset=utf-8',
690
- 'cache-control': 'no-store',
691
- 'x-content-type-options': 'nosniff',
692
- });
693
- res.end(JSON.stringify({
694
- engine: meta.activeEngine,
695
- provider: meta.provider,
696
- providerId: meta.providerId,
697
- providerLabel: meta.providerLabel,
698
- builtinConfigured: meta.builtinConfigured,
699
- model: meta.model,
700
- llm: meta.llm,
701
- mcpUrl: mcpUrl(),
702
- mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
703
- skills: listSkills(targetWorkspace, { pluginDirs }),
704
- commands: listCommands(targetWorkspace, { pluginDirs }),
705
- defaultPersona: meta.defaultPersona,
706
- personas: [...mergedPersonas.values()],
707
- personaTemplates: PERSONA_TEMPLATES.map(({ id, name, pal, summary }) => ({ id, name, pal, summary })),
708
- executors: publicExecutorList(meta.executors),
709
- runs: listRunRecords(meta.rtInfo.stateDir, 10),
710
- sessions: listSessionRecords(meta.rtInfo.stateDir, {
711
- limit: 30,
712
- includeArchived: false,
713
- autoArchiveHours: meta.debugConfig.autoArchiveHours,
714
- runningIds: runningSessionIds(targetWorkspace),
715
- }),
716
- }));
717
- }
718
-
719
- function handleSessions(req, res, url, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
720
- const host = req.headers.host || '';
721
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
722
- const meta = resolveMeta(targetWorkspace);
723
- const stateDir = meta.rtInfo.stateDir;
724
- const id = url.searchParams.get('id');
725
- const includeArchived = url.searchParams.get('includeArchived') === '1' || url.searchParams.get('includeArchived') === 'true';
726
- const sendJson = (status, data) => {
727
- res.writeHead(status, {
728
- 'content-type': 'application/json; charset=utf-8',
729
- 'cache-control': 'no-store',
730
- 'x-content-type-options': 'nosniff',
731
- });
732
- res.end(JSON.stringify(data));
733
- };
734
-
735
- if (req.method === 'GET') {
736
- if (id) {
737
- const record = loadSessionRecord(stateDir, id);
738
- if (!record) throw new DocumentError('未找到该历史会话。', 404);
739
- sendJson(200, { session: record });
438
+ if (req.method === 'POST') {
439
+ assertSameOriginPost(req, remote);
440
+ const body = await readJsonBody(req);
441
+ const result = await handleAutomationOp(rt.workspace, body);
442
+ sendJson(res, 200, { ...result, automations: readAutomationsState(rt.stateDir) });
740
443
  return;
741
444
  }
742
- sendJson(200, {
743
- sessions: listSessionRecords(stateDir, {
744
- limit: 50,
745
- includeArchived,
746
- autoArchiveHours: meta.debugConfig.autoArchiveHours,
747
- runningIds: runningSessionIds(targetWorkspace),
748
- }),
749
- });
750
- return;
751
- }
445
+ throw new DocumentError('不支持的请求方法。', 405);
446
+ },
752
447
 
753
- if (req.method === 'POST') {
754
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
755
- throw new DocumentError('会话操作只接受本机同源页面请求。', 403);
448
+ async handleSessions(req, res, url, targetWorkspace) {
449
+ const rt = getRuntime(targetWorkspace);
450
+ automationEngine.registerWorkspace(rt.workspace);
451
+ const agentDir = resolvePiAgentDir();
452
+
453
+ if (req.method === 'GET') {
454
+ const id = url.searchParams.get('id');
455
+ if (id) {
456
+ const limitParam = url.searchParams.get('limit');
457
+ const beforeParam = url.searchParams.get('before');
458
+ const limit = limitParam !== null ? Number(limitParam) : 30;
459
+ const item = getSessionMeta(rt.stateDir, id, agentDir, { messageLimit: limit });
460
+ if (!item) throw new DocumentError('找不到该角色会话。', 404);
461
+ if (beforeParam !== null || limitParam !== null) {
462
+ const page = readSessionMessagesPage(rt.stateDir, id, {
463
+ limit,
464
+ before: beforeParam !== null ? Number(beforeParam) : null,
465
+ });
466
+ const merged = beforeParam !== null
467
+ ? { ...item, messages: page.messages, totalMessages: page.totalMessages, oldestIndex: page.oldestIndex, hasMoreBefore: page.hasMoreBefore }
468
+ : bridge.overlayLiveSession(rt.workspace, { ...item, messages: page.messages, totalMessages: page.totalMessages, oldestIndex: page.oldestIndex, hasMoreBefore: page.hasMoreBefore });
469
+ sendJson(res, 200, {
470
+ session: merged,
471
+ ...page,
472
+ });
473
+ return;
474
+ }
475
+ sendJson(res, 200, { session: bridge.overlayLiveSession(rt.workspace, item) });
476
+ return;
477
+ }
478
+ const includeArchived = url.searchParams.get('archived') === '1';
479
+ const sinceMinutes = Number(url.searchParams.get('sinceMinutes') || 0);
480
+ const list = listSessions(rt.stateDir, { includeArchived, sinceMinutes, messageLimit: 30, agentDir });
481
+ sendJson(res, 200, { sessions: bridge.overlayLiveSessions(rt.workspace, list) });
482
+ return;
756
483
  }
757
- return (async () => {
758
- const body = await readJsonBody(req, 32 * 1024);
759
- const act = body?.action;
760
484
 
761
- if (act === 'create') {
762
- const newId = safeSessionId(body.id) || randomUUID();
763
- const isAcpSub = body.engine === 'acp';
764
- const persona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : meta.defaultPersona;
765
- const resolved = resolvePersona(persona, '', meta.debugConfig.personas);
766
- const defaultTitle = isAcpSub ? 'ACP 子代理' : (resolved.name || '新会话');
767
- const title = String(body.title || defaultTitle).trim().slice(0, 48);
768
- const saved = saveSessionRecord(stateDir, {
769
- id: newId,
770
- title,
771
- persona,
772
- pal: body.pal || (isAcpSub ? 'cyan' : (resolved.pal || paletteForPersona(persona))),
773
- engine: isAcpSub ? 'acp' : 'builtin',
774
- mode: ['general', 'design', 'qa', 'audit'].includes(body.mode) ? body.mode : 'design',
775
- execMode: body.execMode === 'plan' ? 'plan' : 'act',
776
- archived: false,
777
- liveStatus: isAcpSub ? 'ACP 外部子代理待命…' : '等待指令…',
778
- messages: [],
779
- uiMessages: [],
780
- });
781
- ensureMemorySession(targetWorkspace, meta, newId, saved);
782
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
783
- sendJson(201, { session: saved });
485
+ if (req.method === 'POST') {
486
+ assertSameOriginPost(req, remote);
487
+ const body = await readJsonBody(req);
488
+ if (body?.action === 'rename') {
489
+ const updated = renameSession(rt.stateDir, body.id, body.title, agentDir);
490
+ sendJson(res, 200, { ok: true, session: updated });
784
491
  return;
785
492
  }
786
-
787
- if (act === 'rename') {
788
- const targetId = safeSessionId(body.id);
789
- const nextTitle = String(body.title || '').trim().slice(0, 48);
790
- if (!targetId || !nextTitle) throw new DocumentError('缺少会话 id 或新名称。', 400);
791
- const existing = loadSessionRecord(stateDir, targetId);
792
- const mem = sessions.get(targetId);
793
- if (mem) mem.title = nextTitle;
794
- const updated = saveSessionRecord(stateDir, {
795
- ...(existing || { id: targetId, persona: mem?.persona || meta.defaultPersona }),
796
- id: targetId,
797
- title: nextTitle,
798
- touchActivity: false,
799
- });
800
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
801
- sendJson(200, { session: updated });
493
+ if (body?.action === 'archive') {
494
+ const updated = archiveSession(rt.stateDir, body.id, body.archived !== false, agentDir);
495
+ if (updated) automationEngine.notifyEvent(rt.workspace, 'session.archived', { originSessionId: updated.id, originRoleId: updated.roleId });
496
+ sendJson(res, 200, { ok: Boolean(updated), session: updated });
802
497
  return;
803
498
  }
804
-
805
- if (act === 'set_persona') {
806
- const targetId = safeSessionId(body.id);
807
- const nextPersona = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(String(body.persona || '')) ? String(body.persona) : 'architect';
808
- if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
809
- const nextPal = paletteForPersona(nextPersona);
810
- const mem = sessions.get(targetId);
811
- if (mem) {
812
- mem.persona = nextPersona;
813
- mem.pal = nextPal;
814
- }
815
- const existing = loadSessionRecord(stateDir, targetId);
816
- const updated = saveSessionRecord(stateDir, {
817
- ...(existing || { id: targetId, title: mem?.title || resolvePersona(nextPersona, '', meta.debugConfig.personas).name }),
818
- id: targetId,
819
- persona: nextPersona,
820
- pal: nextPal,
821
- touchActivity: false,
499
+ if (body?.action === 'rollback') {
500
+ const result = restoreCanvasSnapshot(rt.documentRoot, rt.stateDir, body.id, body.snapshotId || '', events, rt.workspace);
501
+ automationEngine.notifyEvent(rt.workspace, 'human.rollback', { file: result.file, sessionId: body.id });
502
+ sendJson(res, 200, result);
503
+ return;
504
+ }
505
+ if (body?.action === 'compact') {
506
+ const result = await bridge.compactSession({
507
+ workspace: rt.workspace,
508
+ stateDir: rt.stateDir,
509
+ sessionId: body.id,
510
+ customInstructions: body.instructions || '',
822
511
  });
823
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
824
- sendJson(200, { session: updated });
512
+ sendJson(res, 200, result);
825
513
  return;
826
514
  }
827
-
828
- if (act === 'archive' || act === 'unarchive') {
829
- const targetId = safeSessionId(body.id);
830
- if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
831
- const updated = archiveSessionRecord(stateDir, targetId, act === 'archive');
832
- if (!updated) throw new DocumentError('未找到该会话。', 404);
833
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
834
- sendJson(200, { session: updated });
515
+ if (body?.action === 'reload') {
516
+ const result = await bridge.reloadSession({
517
+ workspace: rt.workspace,
518
+ stateDir: rt.stateDir,
519
+ sessionId: body.id || '',
520
+ });
521
+ sendJson(res, 200, result);
835
522
  return;
836
523
  }
837
-
838
- if (act === 'exec_mode') {
839
- const targetId = safeSessionId(body.id);
840
- const nextExec = body.execMode === 'plan' ? 'plan' : 'act';
841
- if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
842
- const mem = sessions.get(targetId);
843
- if (mem) mem.execMode = nextExec;
844
- const existing = loadSessionRecord(stateDir, targetId);
845
- if (existing) {
846
- const updated = saveSessionRecord(stateDir, { ...existing, execMode: nextExec, touchActivity: false });
847
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
848
- sendJson(200, { session: updated });
849
- return;
850
- }
851
- sendJson(200, { ok: true, execMode: nextExec });
524
+ if (body?.action === 'abort_all') {
525
+ const stoppedCount = await bridge.abortAllRuns(rt.workspace);
526
+ sendJson(res, 200, { ok: true, stoppedCount });
852
527
  return;
853
528
  }
854
-
855
- if (act === 'rollback') {
856
- const targetId = safeSessionId(body.id);
857
- if (!targetId) throw new DocumentError('缺少有效会话 id。', 400);
858
- const record = loadSessionRecord(stateDir, targetId);
859
- if (!record || !Array.isArray(record.checkpoints) || !record.checkpoints.length) {
860
- throw new DocumentError('当前会话暂无可回退的画布快照。', 404);
861
- }
862
- const cp = body.checkpointId
863
- ? record.checkpoints.find(c => c.id === body.checkpointId)
864
- : record.checkpoints.at(-1);
865
- if (!cp || !cp.files) throw new DocumentError('未找到指定轮次快照。', 404);
866
-
867
- const docRoot = meta.rtInfo.documentRoot || targetWorkspace;
868
- const restoredFiles = [];
869
- for (const [relFile, snap] of Object.entries(cp.files)) {
870
- try {
871
- const full = workspacePath(docRoot, relFile, true);
872
- if (snap.existed) {
873
- writeFileSync(full, snap.content, 'utf8');
874
- } else if (existsSync(full)) {
875
- unlinkSync(full);
876
- }
877
- restoredFiles.push(relFile);
878
- events?.emit(targetWorkspace, 'doc.updated', { file: relFile, action: 'rollback', label: '已回退上轮画布修改' });
879
- } catch {}
880
- }
881
- if (restoredFiles.length) events?.emit(targetWorkspace, 'workspace.updated', { action: 'rollback' });
882
- cp.rolledBack = true;
883
- const mem = sessions.get(targetId);
884
- if (mem) mem.checkpoints = record.checkpoints;
885
- saveSessionRecord(stateDir, { ...record, checkpoints: record.checkpoints, liveStatus: '已回退上轮修改' });
886
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
887
- sendJson(200, { ok: true, restoredFiles, checkpointId: cp.id });
529
+ if (body?.action === 'send_peer') {
530
+ const result = await bridge.sendCrossSessionMessage({
531
+ workspace: rt.workspace,
532
+ stateDir: rt.stateDir,
533
+ documentRoot: rt.documentRoot,
534
+ fromSessionId: body.fromSessionId || '',
535
+ fromRoleId: body.fromRoleId || '',
536
+ fromRoleName: body.fromRoleName || '同伴角色',
537
+ targetSessionId: body.targetSessionId || '',
538
+ targetRoleId: body.targetRoleId || '',
539
+ message: body.message || '',
540
+ wait: Boolean(body.wait),
541
+ });
542
+ sendJson(res, 200, result);
888
543
  return;
889
544
  }
890
-
891
- throw new DocumentError('不支持的会话管理动作。', 400);
892
- })();
893
- }
894
-
895
- if (req.method === 'DELETE') {
896
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
897
- if (!id) throw new DocumentError('缺少会话 id。', 400);
898
- const active = sessions.get(id);
899
- if (active) close(active);
900
- const deleted = deleteSessionRecord(stateDir, id);
901
- if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
902
- emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
903
- sendJson(200, { deleted: true });
904
- return;
905
- }
906
- throw new DocumentError('会话接口仅支持 GET / POST / DELETE。', 405);
907
- }
908
-
909
- async function handleConfig(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
910
- const host = req.headers.host || '';
911
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
912
- const rootWs = typeof workspace === 'function' ? workspace() : workspace;
913
- const meta = resolveMeta(targetWorkspace);
914
- const stateDir = meta.rtInfo.stateDir;
915
- const sendJson = (status, data) => {
916
- res.writeHead(status, {
917
- 'content-type': 'application/json; charset=utf-8',
918
- 'cache-control': 'no-store',
919
- 'x-content-type-options': 'nosniff',
920
- });
921
- res.end(JSON.stringify(data));
922
- };
923
-
924
- const computeSampleTelemetry = cfg => {
925
- const sample = buildSegmentedPromptContext({
926
- workspace: targetWorkspace,
927
- rootWorkspace: rootWs,
928
- documentRoot: meta.rtInfo.documentRoot || targetWorkspace,
929
- stateDir,
930
- debugConfig: cfg,
931
- baseSystemPrompt: resolvePersona('architect', '', cfg.personas).prompt,
932
- history: [{ role: 'user', content: '示例历史上下文' }, { role: 'assistant', content: '已核对架构契约与幂等锚点。' }],
933
- userInstruction: '继续推进',
934
- });
935
- return sample.telemetry;
936
- };
937
-
938
- const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
939
- const pluginMcp = Array.isArray(meta.rtInfo.pluginMcp) ? meta.rtInfo.pluginMcp : [];
940
- const pluginPersonas = Array.isArray(meta.rtInfo.pluginPersonas) ? meta.rtInfo.pluginPersonas : [];
941
-
942
- if (req.method === 'GET') {
943
- const memory = readWorkspaceMemory(stateDir, rootWs);
944
- sendJson(200, {
945
- llm: meta.llm,
946
- mcpUrl: mcpUrl(),
947
- mcpServers: listMcpServers(targetWorkspace, { pluginMcp }),
948
- skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }),
949
- commands: listCommands(targetWorkspace, { pluginDirs }),
950
- pluginPersonas,
951
- config: meta.debugConfig,
952
- hasWorkspaceOverride: meta.hasWorkspaceOverride,
953
- memory,
954
- telemetry: computeSampleTelemetry(meta.debugConfig),
955
- });
956
- return;
957
- }
958
-
959
- if (req.method === 'POST') {
960
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
961
- throw new DocumentError('配置修改只接受本机同源页面请求。', 403);
962
- }
963
- const body = await readJsonBody(req, 64 * 1024);
964
-
965
- if (body.action === 'save_llm') {
966
- if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
967
- const providerId = String(body.providerId || 'openai').trim().toLowerCase().slice(0, 64);
968
- const preset = getProviderPreset(providerId);
969
- const protocol = body.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
970
- const baseUrl = String(body.baseUrl || preset?.defaultBaseUrl || 'https://api.openai.com/v1').trim().slice(0, 512);
971
- const model = String(body.model || preset?.defaultModel || 'gpt-4.1-mini').trim().slice(0, 128);
972
- const updated = saveSettings(prev => {
973
- const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
974
- const prevProf = prevProviders[providerId] || {};
975
- const typedKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
976
- const finalKey = body.clearKey
977
- ? ''
978
- : (typedKey ? typedKey.slice(0, 512) : (prevProf.apiKey ?? ((prev.providerId === providerId ? prev.apiKey : '') || '')));
979
- const mergedModels = Array.isArray(body.models) && body.models.length
980
- ? [...new Set([model, ...body.models.map(m => String(m).trim()).filter(Boolean)])].slice(0, 60)
981
- : [...new Set([model, ...(prevProf.models || preset?.models || [])].filter(Boolean))].slice(0, 60);
982
- prevProviders[providerId] = {
983
- label: String(body.label || prevProf.label || preset?.label || providerId).slice(0, 80),
984
- protocol,
985
- baseUrl,
986
- ...(finalKey ? { apiKey: finalKey } : {}),
987
- model,
988
- enabled: true,
989
- models: mergedModels,
990
- };
991
- const next = {
992
- ...prev,
993
- mode: 'builtin',
994
- providerId,
995
- provider: protocol,
996
- baseUrl,
997
- model,
998
- providers: prevProviders,
999
- };
1000
- if (finalKey) next.apiKey = finalKey;
1001
- else delete next.apiKey;
1002
- return next;
1003
- });
1004
- sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
545
+ const explicitRole = body.roleId || body.persona || '';
546
+ const created = upsertSessionMeta(rt.stateDir, {
547
+ id: body.id ? safeSessionId(body.id) : undefined,
548
+ workspace: rt.workspace,
549
+ title: body.title,
550
+ roleId: explicitRole || 'architect',
551
+ strictRole: Boolean(explicitRole),
552
+ model: body.model || '',
553
+ }, agentDir);
554
+ automationEngine.notifyEvent(rt.workspace, 'session.created', { originSessionId: created.id, originRoleId: created.roleId, title: created.title });
555
+ sendJson(res, 200, { ok: true, session: created });
1005
556
  return;
1006
557
  }
1007
558
 
1008
- if (body.action === 'switch_model') {
1009
- if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1010
- const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1011
- const model = String(body.model || '').trim().slice(0, 128);
1012
- if (!model) throw new DocumentError('请选择要切换的模型。', 400);
1013
- const preset = getProviderPreset(providerId);
1014
- const updated = saveSettings(prev => {
1015
- const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1016
- const prof = prevProviders[providerId] || {};
1017
- const protocol = prof.protocol || preset?.protocol || 'openai';
1018
- const baseUrl = prof.baseUrl || preset?.defaultBaseUrl || prev.baseUrl || 'https://api.openai.com/v1';
1019
- prevProviders[providerId] = {
1020
- ...prof,
1021
- protocol,
1022
- baseUrl,
1023
- model,
1024
- models: [...new Set([model, ...(prof.models || preset?.models || [])])].slice(0, 60),
1025
- };
1026
- const next = {
1027
- ...prev,
1028
- mode: 'builtin',
1029
- providerId,
1030
- provider: protocol,
1031
- baseUrl,
1032
- model,
1033
- providers: prevProviders,
1034
- };
1035
- if (prof.apiKey) next.apiKey = prof.apiKey;
1036
- return next;
1037
- });
1038
- sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
559
+ if (req.method === 'DELETE') {
560
+ assertSameOriginPost(req, remote);
561
+ const id = url.searchParams.get('id');
562
+ if (!id) throw new DocumentError('缺少会话 ID。', 400);
563
+ await bridge.cancel(rt.workspace, id);
564
+ await bridge.disposeWarmSession(rt.workspace, id);
565
+ sendJson(res, 200, deleteSession(rt.stateDir, id, agentDir));
1039
566
  return;
1040
567
  }
1041
568
 
1042
- if (body.action === 'fetch_models') {
1043
- const providerId = String(body.providerId || meta.providerId || 'openai').trim().toLowerCase();
1044
- const preset = getProviderPreset(providerId);
1045
- const curSettings = readSettings();
1046
- const savedProf = curSettings.providers?.[providerId] || {};
1047
- const protocol = body.protocol === 'anthropic' || savedProf.protocol === 'anthropic' || preset?.protocol === 'anthropic' ? 'anthropic' : 'openai';
1048
- const baseUrl = String(body.baseUrl || savedProf.baseUrl || preset?.defaultBaseUrl || '').trim();
1049
- const apiKey = String(body.apiKey || '').trim() || savedProf.apiKey || (curSettings.providerId === providerId ? curSettings.apiKey : '') || '';
1050
- const models = await fetchProviderModels({ protocol, baseUrl, apiKey, fetchImpl });
1051
- if (saveSettings && models.length) {
1052
- saveSettings(prev => {
1053
- const prevProviders = (prev.providers && typeof prev.providers === 'object') ? { ...prev.providers } : {};
1054
- const prof = prevProviders[providerId] || {};
1055
- prevProviders[providerId] = {
1056
- ...prof,
1057
- protocol,
1058
- baseUrl: prof.baseUrl || baseUrl,
1059
- models,
1060
- };
1061
- return { ...prev, providers: prevProviders };
1062
- });
1063
- }
1064
- sendJson(200, { ok: true, models });
1065
- return;
1066
- }
569
+ throw new DocumentError('不支持的请求方法。', 405);
570
+ },
1067
571
 
1068
- if (body.action === 'save_acp') {
1069
- if (!saveSettings) throw new DocumentError('当前环境未挂载全局设置存储。', 409);
1070
- const cmd = String(body.command || '').trim().slice(0, 2048);
1071
- if (!cmd) throw new DocumentError('ACP 命令不能为空。', 400);
1072
- const argsList = Array.isArray(body.args)
1073
- ? body.args.map(a => String(a).trim()).filter(Boolean).slice(0, 32)
1074
- : String(body.args || '').split(/\s+/).map(a => a.trim()).filter(Boolean).slice(0, 32);
1075
- const updated = saveSettings(prev => ({
1076
- ...prev,
1077
- command: cmd,
1078
- args: argsList,
1079
- }));
1080
- sendJson(200, { ok: true, llm: buildLlmState({ ...readSettings(), ...updated }) });
1081
- return;
1082
- }
572
+ async handleConfig(req, res, targetWorkspace) {
573
+ const rt = getRuntime(targetWorkspace);
574
+ const agentDir = resolvePiAgentDir();
1083
575
 
1084
- if (body.action === 'save_memory') {
1085
- const text = saveWorkspaceMemory(stateDir, body.text || '');
1086
- const latest = readAgentDebugConfig(stateDir).config;
1087
- sendJson(200, { ok: true, memory: readWorkspaceMemory(stateDir, rootWs), telemetry: computeSampleTelemetry(latest) });
1088
- return;
1089
- }
1090
- if (body.action === 'save_config') {
1091
- const saved = saveAgentDebugConfig(stateDir, body.patch || {}, { scope: body.scope === 'workspace' ? 'workspace' : 'global' });
1092
- sendJson(200, {
1093
- ok: true,
1094
- config: saved.config,
1095
- hasWorkspaceOverride: saved.hasWorkspaceOverride,
1096
- telemetry: computeSampleTelemetry(saved.config),
1097
- });
576
+ if (req.method === 'GET') {
577
+ const data = await buildFullMeta(targetWorkspace);
578
+ sendJson(res, 200, data);
1098
579
  return;
1099
580
  }
1100
- if (body.action === 'reset') {
1101
- const saved = resetAgentDebugConfig(stateDir, body.section || 'all');
1102
- sendJson(200, {
1103
- ok: true,
1104
- config: saved.config,
1105
- hasWorkspaceOverride: saved.hasWorkspaceOverride,
1106
- telemetry: computeSampleTelemetry(saved.config),
1107
- });
1108
- return;
1109
- }
1110
- if (body.action === 'test_compact') {
1111
- const targetSess = body.sessionId ? loadSessionRecord(stateDir, body.sessionId) : null;
1112
- const srcMsgs = Array.isArray(targetSess?.messages) && targetSess.messages.length
1113
- ? targetSess.messages
1114
- : Array.from({ length: 12 }, (_, idx) => ({
1115
- role: idx % 2 === 0 ? 'user' : 'assistant',
1116
- content: `示例第 ${idx + 1} 轮架构与代码对齐记录(幂等键 idempotencyKey、3000ms 超时重试与账务落库校验)。`.repeat(4),
1117
- }));
1118
- const beforeChars = JSON.stringify(srcMsgs).length;
1119
- const after = compactMessages(srcMsgs, {
1120
- maxChars: Math.max(600, Math.floor(beforeChars * 0.6)),
1121
- thresholdPct: meta.debugConfig.compactThresholdPct,
1122
- compactPrompt: meta.debugConfig.compactPrompt,
1123
- });
1124
- const afterChars = JSON.stringify(after).length;
1125
- sendJson(200, {
1126
- ok: true,
1127
- beforeTurns: srcMsgs.length,
1128
- afterTurns: after.length,
1129
- beforeTokens: Math.ceil(beforeChars / 2.8),
1130
- afterTokens: Math.ceil(afterChars / 2.8),
1131
- });
1132
- return;
1133
- }
1134
- if (body.action === 'save_mcp') {
1135
- try {
1136
- const saved = saveMcpServer(targetWorkspace, {
1137
- name: body.name,
1138
- scope: body.scope === 'global' ? 'global' : 'workspace',
1139
- config: body.config || body,
1140
- });
1141
- sendJson(200, { ok: true, server: saved, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
581
+
582
+ if (req.method !== 'POST') throw new DocumentError('仅支持 GET 或 POST。', 405);
583
+ assertSameOriginPost(req, remote);
584
+ const body = await readJsonBody(req, 256 * 1024);
585
+ const action = String(body?.action || '').trim();
586
+
587
+ try {
588
+ if (action === 'save_provider') {
589
+ const result = await saveProviderConfig(body, agentDir, rt.workspace);
590
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
1142
591
  return;
1143
- } catch (err) {
1144
- throw new DocumentError(err.message || '保存 MCP 服务失败。', 400);
1145
592
  }
1146
- }
1147
- if (body.action === 'toggle_mcp') {
1148
- try {
1149
- const saved = toggleMcpServer(targetWorkspace, {
1150
- name: body.name,
1151
- scope: body.scope === 'global' ? 'global' : 'workspace',
1152
- enabled: body.enabled !== false,
1153
- });
1154
- sendJson(200, { ok: true, server: saved, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
593
+ if (action === 'toggle_provider') {
594
+ const result = setProviderDisabled(body.providerId, Boolean(body.disabled), agentDir);
595
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
1155
596
  return;
1156
- } catch (err) {
1157
- throw new DocumentError(err.message || '切换 MCP 状态失败。', 400);
1158
597
  }
1159
- }
1160
- if (body.action === 'delete_mcp') {
1161
- const deleted = deleteMcpServer(targetWorkspace, {
1162
- name: body.name,
1163
- scope: body.scope === 'global' ? 'global' : 'workspace',
1164
- });
1165
- sendJson(200, { ok: true, deleted, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
1166
- return;
1167
- }
1168
- if (body.action === 'import_mcp_json') {
1169
- try {
1170
- const imported = importMcpJson(targetWorkspace, {
1171
- scope: body.scope === 'global' ? 'global' : 'workspace',
1172
- jsonText: body.jsonText ?? body.json ?? '',
598
+ if (action === 'restore_provider') {
599
+ const result = restoreProviderPreset(body.providerId, agentDir);
600
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
601
+ return;
602
+ }
603
+ if (action === 'delete_provider') {
604
+ const result = deleteProviderConfig(body.providerId, agentDir, {
605
+ removeCard: Boolean(body.removeCard),
606
+ workspace: rt.workspace,
1173
607
  });
1174
- sendJson(200, { ok: true, imported, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
608
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
1175
609
  return;
1176
- } catch (err) {
1177
- throw new DocumentError(err.message || '导入 MCP JSON 失败。', 400);
1178
610
  }
1179
- }
1180
- if (body.action === 'test_mcp') {
1181
- let targetConfig = body.config;
1182
- if (!targetConfig && body.name) {
1183
- const found = listMcpServers(targetWorkspace, { pluginMcp, includeSecrets: true }).find(s => s.name === body.name);
1184
- if (!found) throw new DocumentError(`未找到 MCP 服务:${body.name}`, 404);
1185
- targetConfig = found.config;
611
+ if (action === 'set_default_model') {
612
+ const result = await setDefaultPiModel(body.provider, body.model, agentDir, rt.workspace);
613
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
614
+ return;
1186
615
  }
1187
- const report = await testMcpServer(targetWorkspace, targetConfig || {});
1188
- sendJson(200, report);
1189
- return;
1190
- }
1191
-
1192
- if (body.action === 'save_skill') {
1193
- try {
1194
- const saved = saveSkill(targetWorkspace, {
1195
- slug: body.slug,
1196
- name: body.name,
1197
- description: body.description,
1198
- tags: Array.isArray(body.tags) ? body.tags : [],
1199
- body: body.body,
1200
- scope: body.scope === 'global' ? 'global' : 'workspace',
1201
- });
1202
- sendJson(200, { ok: true, skill: saved, skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }) });
616
+ if (action === 'save_runtime_settings') {
617
+ const modelsInfo = await listProvidersAndModels(rt.workspace, agentDir);
618
+ const runtimeSettings = await saveRuntimeSettings(body, rt.workspace, agentDir, modelsInfo.activeContextWindow);
619
+ sendJson(res, 200, { ok: true, runtimeSettings, meta: await buildFullMeta(targetWorkspace) });
1203
620
  return;
1204
- } catch (err) {
1205
- throw new DocumentError(err.message || '保存技能失败。', 400);
1206
621
  }
1207
- }
1208
- if (body.action === 'delete_skill') {
1209
- const deleted = deleteSkill(targetWorkspace, {
1210
- slug: body.slug,
1211
- scope: body.scope === 'global' ? 'global' : 'workspace',
1212
- });
1213
- sendJson(200, { ok: true, deleted, skills: listSkills(targetWorkspace, { pluginDirs, includeBody: true }) });
1214
- return;
1215
- }
1216
-
1217
- if (body.action === 'save_command') {
1218
- try {
1219
- const saved = saveCommand(targetWorkspace, {
1220
- name: body.name,
1221
- description: body.description,
1222
- prompt: body.prompt,
1223
- skill: body.skill,
1224
- workflow: body.workflow,
1225
- persona: body.persona,
1226
- scope: body.scope === 'global' ? 'global' : 'workspace',
1227
- });
1228
- sendJson(200, { ok: true, command: saved, commands: listCommands(targetWorkspace, { pluginDirs }) });
622
+ if (action === 'save_role') {
623
+ const role = saveRole(body, agentDir, rt.workspace);
624
+ sendJson(res, 200, { ok: true, role, meta: await buildFullMeta(targetWorkspace) });
1229
625
  return;
1230
- } catch (err) {
1231
- throw new DocumentError(err.message || '保存斜杠命令失败。', 400);
1232
626
  }
1233
- }
1234
- if (body.action === 'delete_command') {
1235
- const deleted = deleteCommand(targetWorkspace, {
1236
- name: body.name,
1237
- scope: body.scope === 'global' ? 'global' : 'workspace',
1238
- });
1239
- sendJson(200, { ok: true, deleted, commands: listCommands(targetWorkspace, { pluginDirs }) });
1240
- return;
1241
- }
1242
-
1243
- if (body.action === 'delete_persona') {
1244
- const id = String(body.id || '').trim();
1245
- if (!id || ['architect', 'coder', 'qa', 'auditor'].includes(id)) {
1246
- throw new DocumentError('内置人设不可删除,仅可删除自定义人设。', 400);
627
+ if (action === 'delete_role') {
628
+ const result = deleteRole(body.id, agentDir, rt.workspace);
629
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
630
+ return;
1247
631
  }
1248
- const saved = saveAgentDebugConfig(stateDir, { personas: { [id]: null } }, { scope: 'global' });
1249
- sendJson(200, { ok: true, config: saved.config });
1250
- return;
1251
- }
1252
-
1253
- throw new DocumentError('不支持的配置操作。', 400);
1254
- }
1255
-
1256
- throw new DocumentError('配置接口仅支持 GET / POST。', 405);
1257
- }
1258
-
1259
- async function handle(req, res, targetWorkspace = (typeof workspace === 'function' ? workspace() : workspace)) {
1260
- const host = req.headers.host || '';
1261
- if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
1262
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
1263
- req.headers.origin !== 'http://' + host ||
1264
- req.headers['content-type']?.split(';')[0] !== 'application/json') {
1265
- throw new DocumentError('Agent 只接受本机同源页面请求。', 403);
1266
- }
1267
- const input = await readRequest(req);
1268
- let session = sessions.get(input.session);
1269
-
1270
- if (input.action === 'cancel' || input.action === 'close') {
1271
- if (input.action === 'close') {
1272
- close(session || { key: input.session });
1273
- } else if (session?.running) {
1274
- session.cancelled = true;
1275
- if (session.abortController) {
1276
- session.abortController.abort();
1277
- } else if (session.id && session.agent) {
1278
- session.agent.rpc.notify('session/cancel', { sessionId: session.id }).catch(error => close(session, error));
1279
- session.stopTimer ||= setTimeout(() => close(session, new Error('Agent 停止超时,会话已关闭。')), 5000);
1280
- } else close(session, new Error('已停止连接。'));
1281
- }
1282
- res.writeHead(204).end();
1283
- return;
1284
- }
1285
-
1286
- // 运行中实时插话纠偏(Steer):不打断已完成的工具步骤,排入下一步队首立即生效
1287
- if (input.action === 'steer') {
1288
- if (session?.running && Array.isArray(session.steeringQueue)) {
1289
- session.steeringQueue.push(input.text);
1290
- session.uiMessages.push({ role: 'human', text: input.text, isSteer: true });
1291
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
1292
- res.end(JSON.stringify({ ok: true, mode: 'steered' }));
1293
- return;
1294
- }
1295
- throw new DocumentError('当前会话未在运行中,请直接发送消息。', 409);
1296
- }
1297
-
1298
- if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
1299
- if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
1300
- const meta = resolveMeta(targetWorkspace);
1301
- if (!session) {
1302
- if (sessions.size >= 16) throw new DocumentError('Agent 并发会话过多,请归档或关闭部分会话后再试。', 429);
1303
- session = ensureMemorySession(targetWorkspace, meta, input.session, {
1304
- title: input.title,
1305
- persona: input.persona,
1306
- engine: input.engine === 'acp' ? 'acp' : 'builtin',
1307
- mode: input.mode,
1308
- execMode: input.execMode,
1309
- });
1310
- }
1311
- if (input.execMode) session.execMode = input.execMode;
1312
-
1313
- let resumeToolResult = null;
1314
- let resumeCommandResult = null;
1315
- if (input.action === 'answer') {
1316
- const pending = session.pendingQuestion;
1317
- if (!pending || pending.id !== input.questionId) {
1318
- throw new DocumentError('当前没有待确认的提问,或该提问已失效。', 409);
1319
- }
1320
- resumeToolResult = {
1321
- toolCallId: pending.toolCallId,
1322
- choiceId: input.choiceId || '',
1323
- answer: input.answer,
1324
- };
1325
- } else if (input.action === 'command_decision') {
1326
- const pendingCmd = session.pendingCommand;
1327
- if (!pendingCmd || pendingCmd.id !== input.commandId) {
1328
- throw new DocumentError('当前没有待审批的命令,或该请求已失效。', 409);
1329
- }
1330
- if (input.decision === 'session_allow') session.commandAutoAllow = true;
1331
- resumeCommandResult = {
1332
- toolCallId: pendingCmd.toolCallId,
1333
- command: pendingCmd.command,
1334
- decision: input.decision,
1335
- };
1336
- }
1337
-
1338
- const sessionWantsAcp = session.engine === 'acp' || input.engine === 'acp';
1339
- const useBuiltin = input.action === 'answer'
1340
- || input.action === 'command_decision'
1341
- || (input.action === 'prompt' && !sessionWantsAcp && (
1342
- input.engine === 'builtin' || meta.activeEngine === 'builtin'
1343
- ));
1344
-
1345
- session.running = true;
1346
- session.cancelled = false;
1347
- session.peerHopCount = 0; // 人类主动交互立即清零连续互发计数
1348
- session.activeCardTarget = input.canvas?.file
1349
- ? `${input.canvas.file}${input.canvas.selection?.[0]?.[0] ? '#' + input.canvas.selection[0][0] : ''}`
1350
- : '';
1351
- clearTimeout(session.idle);
1352
-
1353
- res.writeHead(200, {
1354
- 'content-type': 'application/x-ndjson; charset=utf-8',
1355
- 'cache-control': 'no-store, no-transform',
1356
- 'x-content-type-options': 'nosniff',
1357
- });
1358
- const emit = event => {
1359
- if (!res.destroyed && !res.writableEnded) res.write(JSON.stringify(event) + '\n');
1360
- };
1361
- session.emit = emit;
1362
- const abort = new Promise((_, reject) => { session.fail = reject; });
1363
- const onDisconnect = () => { if (!res.writableEnded) close(session); };
1364
- res.on('close', onDisconnect);
1365
- const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
1366
-
1367
- const run = async () => {
1368
- if (useBuiltin) {
1369
- session.abortController = new AbortController();
1370
- // 若上一轮有未回答的 ask_user 或待审命令,但用户直接发起了新指令,自动补齐跳过回执保持消息配对合法
1371
- if (input.action === 'prompt' && session.pendingQuestion) {
1372
- session.history.push({
1373
- role: 'tool',
1374
- tool_call_id: session.pendingQuestion.toolCallId,
1375
- content: JSON.stringify({ answered: false, skipped: true, reason: '用户发起了新的指令' }),
632
+ if (action === 'reload_pi') {
633
+ const result = await bridge.reloadSession({
634
+ workspace: rt.workspace,
635
+ stateDir: rt.stateDir,
636
+ sessionId: body.sessionId || '',
1376
637
  });
1377
- for (let i = session.uiMessages.length - 1; i >= 0; i--) {
1378
- if (session.uiMessages[i]?.question?.id === session.pendingQuestion.id) {
1379
- session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: '(已跳过,发起新指令)' };
1380
- break;
1381
- }
1382
- }
1383
- session.pendingQuestion = null;
638
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
639
+ return;
1384
640
  }
1385
- if (input.action === 'prompt' && session.pendingCommand) {
1386
- session.history.push({
1387
- role: 'tool',
1388
- tool_call_id: session.pendingCommand.toolCallId,
1389
- content: JSON.stringify({ approved: false, skipped: true, reason: '用户发起了新的指令' }),
1390
- });
1391
- session.pendingCommand = null;
641
+ if (action === 'save_mcp') {
642
+ const result = savePiMcpServer(body, rt.workspace, agentDir);
643
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
644
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
645
+ return;
1392
646
  }
1393
-
1394
- const pluginDirs = Array.isArray(meta.rtInfo.pluginDirs) ? meta.rtInfo.pluginDirs : [];
1395
- const slashExpanded = input.action === 'prompt'
1396
- ? expandSlashCommand(session.workspace, input.text, { pluginDirs })
1397
- : null;
1398
- const effectiveInput = slashExpanded
1399
- ? { ...input, text: slashExpanded.prompt }
1400
- : input;
1401
- const activeMode = (slashExpanded?.workflow && ['general', 'design', 'qa', 'audit'].includes(slashExpanded.workflow))
1402
- ? slashExpanded.workflow
1403
- : (input.mode || session.mode || 'general');
1404
- const activePersona = slashExpanded?.persona || input.persona || session.persona || meta.defaultPersona;
1405
- const activeExecMode = input.execMode || session.execMode || 'act';
1406
- let thinkingBuf = '';
1407
- let textBuf = '';
1408
- let changesBuf = [];
1409
- const incomingPeers = session.incomingPeerMessages.splice(0);
1410
- const peerCoord = createPeerCoordinator(targetWorkspace, meta, session);
1411
-
1412
- const emitBuiltin = ev => {
1413
- if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
1414
- else if (ev.type === 'text' && ev.text) textBuf += ev.text;
1415
- else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
1416
- else if (ev.type === 'todos' && Array.isArray(ev.todos)) session.todos = ev.todos;
1417
- else if (ev.type === 'status' && ev.text) {
1418
- session.liveStatus = ev.text;
1419
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1420
- }
1421
- emit(ev);
1422
- };
1423
-
1424
- const result = await runVerticalAgent({
1425
- workspace: session.workspace,
1426
- rootWorkspace: typeof workspace === 'function' ? workspace() : workspace,
1427
- documentRoot: meta.rtInfo.documentRoot || session.workspace,
1428
- stateDir: meta.rtInfo.stateDir,
1429
- workspaceService,
1430
- events,
1431
- config: meta.settings,
1432
- debugConfig: meta.debugConfig,
1433
- pluginMeta: {
1434
- pluginDirs,
1435
- pluginMcp: meta.rtInfo.pluginMcp || [],
1436
- pluginPersonas: meta.rtInfo.pluginPersonas || [],
1437
- },
1438
- preloadedSkill: slashExpanded?.skill || '',
1439
- history: session.history,
1440
- canvasBaseline: session.canvasBaseline,
1441
- activePeerLocks: activePeerLocksFor(targetWorkspace, session.key),
1442
- incomingPeerMessages: incomingPeers,
1443
- peerCoordinator: peerCoord,
1444
- resumeToolResult,
1445
- resumeCommandResult,
1446
- sessionCommandAutoAllow: session.commandAutoAllow,
1447
- drainSteering: () => session.steeringQueue.splice(0),
1448
- input: effectiveInput,
1449
- mode: activeMode,
1450
- execMode: activeExecMode,
1451
- persona: activePersona,
1452
- todos: session.todos,
1453
- emit: emitBuiltin,
1454
- signal: session.abortController.signal,
1455
- fetchImpl,
1456
- });
1457
-
1458
- if (input.action === 'answer') {
1459
- for (let i = session.uiMessages.length - 1; i >= 0; i--) {
1460
- if (session.uiMessages[i]?.question?.id === input.questionId) {
1461
- session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: input.answer };
1462
- break;
1463
- }
1464
- }
1465
- session.uiMessages.push({ role: 'human', text: input.answer, isAnswer: true });
1466
- } else if (input.action === 'command_decision') {
1467
- const labelMap = { allow: '已允许执行', session_allow: '本会话免审允许', deny: '已拒绝命令' };
1468
- session.uiMessages.push({ role: 'human', text: `${labelMap[input.decision]}:${resumeCommandResult.command}`, isAnswer: true });
1469
- } else {
1470
- session.uiMessages.push({
1471
- role: 'human',
1472
- text: input.text,
1473
- canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
647
+ if (action === 'toggle_mcp') {
648
+ const result = togglePiMcpServer(body.name, body.enabled, rt.workspace, agentDir);
649
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
650
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
651
+ return;
652
+ }
653
+ if (action === 'delete_mcp') {
654
+ const result = deletePiMcpServer(body.name, rt.workspace, agentDir);
655
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
656
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
657
+ return;
658
+ }
659
+ if (action === 'import_mcp_json') {
660
+ const result = importPiMcpJson(body.json, body.scope || 'user', rt.workspace, agentDir);
661
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
662
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
663
+ return;
664
+ }
665
+ if (action === 'save_mcp_raw') {
666
+ const result = savePiMcpRawJson(body.scope || 'user', body.json, rt.workspace, agentDir);
667
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
668
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
669
+ return;
670
+ }
671
+ if (action === 'save_plugin_params') {
672
+ const result = savePluginParams(body, rt.workspace, rt.stateDir, agentDir);
673
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
674
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
675
+ return;
676
+ }
677
+ if (action === 'delete_plugin_params') {
678
+ const result = deletePluginParams(body.pluginId || body.id, body.scope || 'all', rt.workspace, rt.stateDir, agentDir);
679
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
680
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
681
+ return;
682
+ }
683
+ if (action === 'save_skill') {
684
+ const result = savePiSkill(body, rt.workspace, agentDir);
685
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
686
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
687
+ return;
688
+ }
689
+ if (action === 'delete_skill') {
690
+ const result = deletePiSkill(body.name, rt.workspace, agentDir);
691
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
692
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
693
+ return;
694
+ }
695
+ if (action === 'save_command') {
696
+ const result = savePiPrompt(body, rt.workspace, agentDir);
697
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
698
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
699
+ return;
700
+ }
701
+ if (action === 'delete_command') {
702
+ const result = deletePiPrompt(body.name, rt.workspace, agentDir);
703
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
704
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
705
+ return;
706
+ }
707
+ if (action === 'install_pi_package') {
708
+ const result = await installPiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
709
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
710
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
711
+ return;
712
+ }
713
+ if (action === 'remove_pi_package') {
714
+ const result = await removePiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
715
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
716
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
717
+ return;
718
+ }
719
+ if (action === 'save_memory') {
720
+ const result = saveAgentsMemory(rt.workspace, body.content);
721
+ automationEngine.notifyEvent(rt.workspace, 'memory.updated', { file: 'AGENTS.md', source: 'settings' });
722
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
723
+ return;
724
+ }
725
+ if (action === 'save_automation') {
726
+ const result = saveAutomationRule(rt.stateDir, body.rule || body);
727
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
728
+ return;
729
+ }
730
+ if (action === 'delete_automation') {
731
+ const result = deleteAutomationRule(rt.stateDir, body.ruleId || body.id);
732
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
733
+ return;
734
+ }
735
+ if (action === 'toggle_automations_pause') {
736
+ const result = setAutomationsPaused(rt.stateDir, Boolean(body.paused));
737
+ sendJson(res, 200, { ok: true, automations: result, meta: await buildFullMeta(targetWorkspace) });
738
+ return;
739
+ }
740
+ if (action === 'run_automation_now') {
741
+ const result = await automationEngine.runRuleNow(rt.workspace, body.ruleId || body.id);
742
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
743
+ return;
744
+ }
745
+ if (action === 'save_platform_context') {
746
+ const result = saveCladoPlatformContext(body.content, agentDir);
747
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
748
+ return;
749
+ }
750
+ if (action === 'reset_platform_context') {
751
+ const result = resetCladoPlatformDocs(agentDir);
752
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
753
+ return;
754
+ }
755
+ if (action === 'toggle_canvas_component') {
756
+ const canvasComponents = toggleCanvasComponent(body.id, body.enabled, agentDir);
757
+ sendJson(res, 200, { ok: true, canvasComponents, meta: await buildFullMeta(targetWorkspace) });
758
+ return;
759
+ }
760
+ if (action === 'save_pi_settings') {
761
+ const modelsInfo = await listProvidersAndModels(rt.workspace, agentDir);
762
+ const result = await saveFullPiSettings(
763
+ body.patch || body,
764
+ body.scope || 'user',
765
+ rt.workspace,
766
+ agentDir,
767
+ modelsInfo.activeContextWindow,
768
+ );
769
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
770
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
771
+ return;
772
+ }
773
+ if (action === 'test_provider') {
774
+ const result = await testProviderConnection(body, agentDir);
775
+ sendJson(res, 200, result);
776
+ return;
777
+ }
778
+ if (action === 'save_workspace_prefs') {
779
+ const result = saveWorkspacePrefs(body, rt.workspace);
780
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
781
+ return;
782
+ }
783
+ if (action === 'save_global_memory') {
784
+ const result = saveGlobalAgentsMemory(body.content, agentDir);
785
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
786
+ return;
787
+ }
788
+ if (action === 'save_project_rule') {
789
+ const result = saveProjectRule({ name: body.name, content: body.content }, rt.workspace);
790
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
791
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
792
+ return;
793
+ }
794
+ if (action === 'delete_project_rule') {
795
+ const result = deleteProjectRule(body.name, rt.workspace);
796
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
797
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
798
+ return;
799
+ }
800
+ if (action === 'read_skill_or_prompt') {
801
+ const result = readSkillOrPromptContent(body.filePath, rt.workspace, agentDir);
802
+ sendJson(res, 200, result);
803
+ return;
804
+ }
805
+ if (action === 'scan_external_mcp') {
806
+ const result = scanExternalMcpConfigs(rt.workspace);
807
+ sendJson(res, 200, result);
808
+ return;
809
+ }
810
+ if (action === 'save_hook') {
811
+ const result = saveHookRule(body.hook || body, rt.workspace, agentDir);
812
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
813
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
814
+ return;
815
+ }
816
+ if (action === 'delete_hook') {
817
+ const result = deleteHookRule(body.id, body.scope || '', rt.workspace, agentDir);
818
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
819
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
820
+ return;
821
+ }
822
+ if (action === 'test_hook') {
823
+ const result = await testHookRule(body.hook || body, body.samplePayload || {}, rt.workspace, agentDir);
824
+ sendJson(res, 200, result);
825
+ return;
826
+ }
827
+ if (action === 'save_permissions') {
828
+ const result = savePermissionsConfig(body, rt.workspace, agentDir);
829
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
830
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
831
+ return;
832
+ }
833
+ if (action === 'read_raw_config') {
834
+ const result = readRawConfigTarget(body.target || 'settings', body.scope || 'user', rt.workspace, agentDir);
835
+ sendJson(res, 200, result);
836
+ return;
837
+ }
838
+ if (action === 'save_raw_config') {
839
+ const result = saveRawConfigTarget(body.target || 'settings', body.scope || 'user', body.content ?? body.json ?? '', rt.workspace, agentDir);
840
+ const reload = await bridge.reloadWorkspaceSessions(rt.workspace);
841
+ sendJson(res, 200, { ...result, reload, meta: await buildFullMeta(targetWorkspace) });
842
+ return;
843
+ }
844
+ if (action === 'abort_all_runs') {
845
+ const aborted = await bridge.abortAllRuns(rt.workspace);
846
+ sendJson(res, 200, { ok: true, aborted, meta: await buildFullMeta(targetWorkspace) });
847
+ return;
848
+ }
849
+ if (action === 'clear_archived_sessions') {
850
+ const result = clearArchivedSessions(rt.stateDir, agentDir);
851
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
852
+ return;
853
+ }
854
+ if (action === 'export_session') {
855
+ const result = exportSessionTranscript(rt.stateDir, body.sessionId || body.id, body.format === 'json' ? 'json' : 'md', agentDir);
856
+ sendJson(res, 200, result);
857
+ return;
858
+ }
859
+ if (action === 'create_canvas_doc' && workspaceService?.createDocument) {
860
+ const file = String(body.file || '').trim();
861
+ const title = String(body.title || '').trim() || file.replace(/\.mdc?$/i, '');
862
+ const result = await workspaceService.createDocument({
863
+ workspace: rt.workspace,
864
+ file,
865
+ title,
866
+ cards: [{ title: title || '概览', body: '在此开始构建你的结构化画布。' }],
1474
867
  });
868
+ sendJson(res, 200, { ok: true, result });
869
+ return;
1475
870
  }
1476
-
1477
- if (result.checkpoint) session.checkpoints.push(result.checkpoint);
1478
- if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion || result.pendingCommand) {
1479
- session.uiMessages.push({
1480
- role: 'assistant',
1481
- thinking: thinkingBuf,
1482
- text: textBuf,
1483
- changes: changesBuf,
1484
- checkpointId: result.checkpoint?.id || null,
1485
- question: result.pendingQuestion || null,
1486
- commandApproval: result.pendingCommand || null,
871
+ if (action === 'rename_canvas_doc' && workspaceService?.moveDocument) {
872
+ const result = await workspaceService.moveDocument({
873
+ workspace: rt.workspace,
874
+ from: String(body.from || '').trim(),
875
+ to: String(body.to || '').trim(),
1487
876
  });
877
+ sendJson(res, 200, { ok: true, result });
878
+ return;
1488
879
  }
1489
-
1490
- session.history = Array.isArray(result.conversation) ? result.conversation : session.history;
1491
- session.todos = Array.isArray(result.todos) ? result.todos : session.todos;
1492
- session.canvasBaseline = result.nextBaseline || session.canvasBaseline;
1493
- session.pendingQuestion = result.pendingQuestion || null;
1494
- session.pendingCommand = result.pendingCommand || null;
1495
- session.persona = activePersona;
1496
- session.pal = paletteForPersona(activePersona);
1497
- session.mode = activeMode;
1498
- session.execMode = activeExecMode;
1499
- if (!session.title) session.title = (input.title || input.text || input.answer || '新会话').slice(0, 48);
1500
- session.liveStatus = result.pendingCommand
1501
- ? `待审批:${result.pendingCommand.command.slice(0, 20)}`
1502
- : result.pendingQuestion
1503
- ? '等待确认方案…'
1504
- : (changesBuf[0]?.label || '已完成');
1505
-
1506
- if (meta.rtInfo.stateDir) {
1507
- saveSessionRecord(meta.rtInfo.stateDir, {
1508
- id: session.key,
1509
- title: session.title,
1510
- persona: session.persona,
1511
- pal: session.pal,
1512
- mode: session.mode,
1513
- execMode: session.execMode,
1514
- archived: false,
1515
- liveStatus: session.liveStatus,
1516
- todos: session.todos,
1517
- calledBy: null,
1518
- canvasBaseline: session.canvasBaseline,
1519
- checkpoints: session.checkpoints,
1520
- messages: session.history,
1521
- uiMessages: session.uiMessages,
1522
- pendingQuestion: session.pendingQuestion,
1523
- pendingCommand: session.pendingCommand,
880
+ if (action === 'delete_canvas_doc' && workspaceService?.deleteDocument) {
881
+ const result = await workspaceService.deleteDocument({
882
+ workspace: rt.workspace,
883
+ file: String(body.file || '').trim(),
1524
884
  });
1525
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
885
+ sendJson(res, 200, { ok: true, result });
886
+ return;
1526
887
  }
1527
- return { stopReason: result.stopReason };
888
+ throw new DocumentError(`不支持的配置操作:${action}`, 400);
889
+ } catch (err) {
890
+ if (err instanceof DocumentError) throw err;
891
+ throw new DocumentError(err?.message || '配置更新失败', 400);
1528
892
  }
893
+ },
1529
894
 
1530
- // 外部 ACP 执行器(dispatch / 默认 ACP 对话):同样接入底部会话胶囊持久化,但不接管其内部压缩
1531
- let acpTextBuf = '';
1532
- const prevEmit = session.emit;
1533
- session.emit = ev => {
1534
- if (ev.type === 'text' && ev.text) acpTextBuf += ev.text;
1535
- else if (ev.type === 'tool' && ev.title) {
1536
- session.liveStatus = `调用 ${String(ev.title).split('.').pop()}…`;
1537
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1538
- }
1539
- prevEmit?.(ev);
1540
- };
895
+ async handle(req, res, targetWorkspace) {
896
+ if (req.method !== 'POST') throw new DocumentError('仅支持 POST。', 405);
897
+ assertSameOriginPost(req, remote);
898
+ const raw = await readJsonBody(req);
899
+ const parsed = agentRequestSchema.safeParse(raw);
900
+ if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
901
+ const input = parsed.data;
902
+ const rt = getRuntime(targetWorkspace);
903
+ const agentDir = resolvePiAgentDir();
904
+
905
+ if (input.action === 'answer') {
906
+ const ok = bridge.answer(rt.workspace, input.session, input.questionId, input.answer);
907
+ sendJson(res, 200, { ok });
908
+ return;
909
+ }
910
+ if (input.action === 'steer') {
911
+ const ok = await bridge.steer(rt.workspace, input.session, input.text);
912
+ sendJson(res, 200, { ok });
913
+ return;
914
+ }
915
+ if (input.action === 'cancel' || input.action === 'close') {
916
+ const ok = await bridge.cancel(rt.workspace, input.session);
917
+ sendJson(res, 200, { ok });
918
+ return;
919
+ }
1541
920
 
1542
- if (input.action === 'dispatch') {
1543
- const chosen = input.executorId
1544
- ? meta.executors.find(item => item.id === input.executorId)
1545
- : meta.executors[0];
1546
- if (!chosen) throw new Error('找不到指定的 ACP 执行器插件:' + (input.executorId || '默认'));
1547
- if (!session.title) session.title = chosen.name;
1548
- session.liveStatus = `${chosen.name} 执行中…`;
1549
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
921
+ const handoffTargetRole = input.action === 'handoff'
922
+ ? resolveRole(input.targetRoleId, agentDir, { workspace: rt.workspace, strict: Boolean(input.targetRoleId) })
923
+ : null;
1550
924
 
1551
- const runRec = createRunRecord(meta.rtInfo.stateDir, {
1552
- kind: 'dispatch',
1553
- mode: 'implement',
1554
- executorId: chosen.id,
1555
- file: input.canvas?.file || '',
1556
- instruction: input.text || '按画布规格实施开发',
1557
- });
1558
- emit({ type: 'run', run: runRec });
1559
- emit({ type: 'status', text: `正在派发给执行器:${chosen.name}` });
1560
- events?.emit(session.workspace, 'agent.activity', {
1561
- file: input.canvas?.file || '',
1562
- action: 'dispatch',
1563
- kind: 'write',
1564
- nodes: input.canvas?.selection || [],
1565
- label: `ACP 派发开发中 · ${chosen.name}`,
1566
- });
925
+ // Streaming NDJSON response for prompt & handoff
926
+ res.writeHead(200, {
927
+ 'content-type': 'application/x-ndjson; charset=utf-8',
928
+ 'cache-control': 'no-store',
929
+ 'x-content-type-options': 'nosniff',
930
+ });
931
+ const emit = event => {
932
+ if (res.writableEnded || res.destroyed) return;
933
+ try { res.write(JSON.stringify(event) + '\n'); } catch {}
934
+ };
1567
935
 
1568
- if (session.agent && session.executorId !== chosen.id) {
1569
- session.agent.dispose();
1570
- session.agent = null;
1571
- session.id = null;
1572
- session.started = false;
1573
- }
1574
- session.executorId = chosen.id;
1575
- if (!session.agent) await connectAcp(session, chosen);
1576
- if (session.cancelled || sessions.get(session.key) !== session) {
1577
- updateRunRecord(meta.rtInfo.stateDir, runRec, { status: 'cancelled' });
1578
- return { stopReason: 'cancelled' };
1579
- }
1580
- emit({ type: 'status', text: `${chosen.name} 执行中(无需切换窗口)…` });
1581
- const prompt = buildDispatchPrompt({
1582
- workspace: session.workspace,
1583
- documentRoot: meta.rtInfo.documentRoot,
1584
- file: input.canvas?.file || '',
1585
- selection: input.canvas?.selection || [],
1586
- instruction: input.text,
1587
- mcpName: session.hasMcp ? mcpName() : '',
936
+ if (input.action === 'handoff') {
937
+ const targetRole = handoffTargetRole;
938
+ const existing = listSessions(rt.stateDir, { agentDir }).find(s => s.roleId === targetRole.id);
939
+ const targetSessionId = input.targetSession || existing?.id || ('role_' + targetRole.id);
940
+ const defaultTask = targetRole.id === 'developer'
941
+ ? '请依据上述画布设计契约落地代码实现,并在完成后运行校验命令汇报结果。'
942
+ : targetRole.id === 'tester'
943
+ ? '请依据上述画布契约补充单元测试与边界回归用例,并执行测试汇报结果。'
944
+ : targetRole.id === 'archivist'
945
+ ? '请将上述画布定稿内容整理为清晰的架构文档 / ADR 决策记录。'
946
+ : '请依据上述画布契约推进当前阶段工作。';
947
+
948
+ await bridge.runTurn({
949
+ workspace: rt.workspace,
950
+ stateDir: rt.stateDir,
951
+ documentRoot: rt.documentRoot,
952
+ sessionId: targetSessionId,
953
+ roleId: targetRole.id,
954
+ text: input.text || defaultTask,
955
+ canvas: input.canvas,
956
+ handoffFrom: input.fromRoleName || '画布定稿',
957
+ emit,
1588
958
  });
1589
- const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1590
- const finished = updateRunRecord(meta.rtInfo.stateDir, runRec, {
1591
- status: session.cancelled ? 'cancelled' : 'completed',
1592
- summary: `执行器 ${chosen.name} 已完成(${response.stopReason})`,
1593
- });
1594
- emit({ type: 'run', run: finished });
1595
- events?.emit(session.workspace, 'agent.activity', {
1596
- file: input.canvas?.file || '',
1597
- action: 'dispatch.done',
1598
- kind: 'write',
1599
- nodes: input.canvas?.selection || [],
1600
- label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
1601
- });
1602
- session.uiMessages.push(
1603
- { role: 'human', text: `[派发 ${chosen.name}] ${input.text || '按画布规格实现'}` },
1604
- ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1605
- );
1606
- session.liveStatus = `${chosen.name} 已完成`;
1607
- if (meta.rtInfo.stateDir) {
1608
- saveSessionRecord(meta.rtInfo.stateDir, {
1609
- id: session.key,
1610
- title: session.title || chosen.name,
1611
- persona: session.persona,
1612
- pal: 'teal',
1613
- mode: session.mode,
1614
- execMode: session.execMode,
1615
- archived: false,
1616
- liveStatus: session.liveStatus,
1617
- uiMessages: session.uiMessages,
1618
- });
1619
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1620
- }
1621
- return response;
959
+ if (!res.writableEnded) res.end();
960
+ return;
1622
961
  }
1623
962
 
1624
- // 默认 ACP 对话模式
1625
- if (!session.agent) await connectAcp(session);
1626
- if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
1627
- if (!session.title) session.title = (input.title || input.text || 'ACP 会话').slice(0, 48);
1628
- session.liveStatus = '正在生成…';
1629
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1630
- emit({ type: 'status', text: '正在生成' });
1631
- const prompt = promptBlocks(session.workspace, input);
1632
- if (!session.started && session.hasMcp) {
1633
- prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
1634
- session.started = true;
1635
- }
1636
- const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
1637
- session.uiMessages.push(
1638
- { role: 'human', text: input.text },
1639
- ...(acpTextBuf ? [{ role: 'assistant', text: acpTextBuf }] : []),
1640
- );
1641
- session.liveStatus = '已完成';
1642
- if (meta.rtInfo.stateDir) {
1643
- saveSessionRecord(meta.rtInfo.stateDir, {
1644
- id: session.key,
1645
- title: session.title,
1646
- persona: session.persona,
1647
- pal: session.pal,
1648
- mode: session.mode,
1649
- execMode: session.execMode,
1650
- archived: false,
1651
- liveStatus: session.liveStatus,
1652
- uiMessages: session.uiMessages,
963
+ // action === 'prompt'
964
+ if (input.canvas?.selection?.length || input.canvas?.textSnippet?.text) {
965
+ automationEngine.notifyEvent(rt.workspace, 'human.selection_sent', {
966
+ file: input.canvas?.file || '',
967
+ cards: (input.canvas?.selection || []).map(p => (Array.isArray(p) ? p[0] : String(p || ''))),
968
+ targetSessionId: input.session,
1653
969
  });
1654
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1655
970
  }
1656
- return response;
1657
- };
971
+ await bridge.runTurn({
972
+ workspace: rt.workspace,
973
+ stateDir: rt.stateDir,
974
+ documentRoot: rt.documentRoot,
975
+ sessionId: input.session,
976
+ roleId: input.roleId,
977
+ modelSpec: input.model,
978
+ text: input.text,
979
+ canvas: input.canvas,
980
+ emit,
981
+ });
982
+ if (!res.writableEnded) res.end();
983
+ },
1658
984
 
1659
- try {
1660
- emit({ type: 'status', text: useBuiltin ? '正在启动 Clado 独立 Agent' : (session.agent ? '正在发送' : '正在连接 Agent') });
1661
- const result = await Promise.race([run(), abort]);
1662
- emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
1663
- } catch (error) {
1664
- if (session.cancelled) emit({ type: 'done', reason: 'cancelled' });
1665
- else {
1666
- const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
1667
- emit({ type: 'error', text: message });
1668
- }
1669
- if (!useBuiltin) close(session, error);
1670
- } finally {
1671
- clearTimeout(timer);
1672
- clearTimeout(session.stopTimer);
1673
- session.stopTimer = undefined;
1674
- session.abortController = undefined;
1675
- session.running = false;
1676
- session.activeCardTarget = '';
1677
- session.emit = session.fail = undefined;
1678
- res.off('close', onDisconnect);
1679
- res.end();
1680
- emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
1681
- if (sessions.get(session.key) === session) {
1682
- session.idle = setTimeout(() => close(session), idleMs);
1683
- session.idle.unref();
1684
- }
1685
- }
1686
- }
1687
- return {
1688
- handle,
1689
- handleMeta,
1690
- handleSessions,
1691
- handleConfig,
1692
- close: () => { for (const session of sessions.values()) close(session); },
985
+ close() {
986
+ automationEngine.dispose();
987
+ return bridge.closeAll();
988
+ },
1693
989
  };
1694
990
  }