cladogram 0.5.5-beta.9 → 0.6.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -79
- package/bin/clado.js +1 -1
- package/docs/release.md +15 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +1575 -3081
- package/plugins/agent/style.css +724 -1438
- package/plugins/brand/index.js +84 -466
- package/plugins/brand/style.css +39 -172
- package/plugins/directory/index.js +10 -10
- package/plugins/view-controls/index.js +17 -1
- package/plugins/view-controls/style.css +47 -29
- package/src/agent/clado-tools.js +299 -0
- package/src/agent/pi-bridge.js +621 -0
- package/src/agent/pi-config.js +630 -0
- package/src/html/plugin-ui.css +159 -134
- package/src/html/plugin-ui.js +3 -2
- package/src/server/agent.js +334 -1589
- package/src/server/assets/library.css +396 -11
- package/src/server/assets/library.html +37 -4
- package/src/server/assets/library.js +428 -203
- package/src/server/plugin-registry.js +7 -7
- package/src/server/plugins.js +1 -1
- package/src/server/workspace-hub.js +50 -0
- package/src/server/workspace.js +4 -15
- package/src/agent/commands.js +0 -204
- package/src/agent/context.js +0 -445
- package/src/agent/executors.js +0 -213
- package/src/agent/mcp-client.js +0 -308
- package/src/agent/probe.js +0 -234
- package/src/agent/providers/anthropic.js +0 -220
- package/src/agent/providers/index.js +0 -235
- package/src/agent/providers/openai.js +0 -146
- package/src/agent/runtime.js +0 -995
- package/src/agent/sessions.js +0 -336
- package/src/agent/skills.js +0 -190
package/src/server/agent.js
CHANGED
|
@@ -1,1694 +1,439 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
|
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
|
-
|
|
19
|
-
|
|
15
|
+
deletePiMcpServer,
|
|
16
|
+
deletePiPrompt,
|
|
17
|
+
deletePiSkill,
|
|
18
|
+
deleteProviderConfig,
|
|
19
|
+
deleteRole,
|
|
20
|
+
importPiMcpJson,
|
|
21
|
+
inspectPiEcosystem,
|
|
22
|
+
installPiPackage,
|
|
23
|
+
listProvidersAndModels,
|
|
24
|
+
listRoles,
|
|
25
|
+
readAgentsMemory,
|
|
26
|
+
readCanvasComponentsConfig,
|
|
27
|
+
removePiPackage,
|
|
28
|
+
resolvePiAgentDir,
|
|
29
|
+
resolveRole,
|
|
30
|
+
saveAgentsMemory,
|
|
31
|
+
savePiMcpServer,
|
|
32
|
+
savePiPrompt,
|
|
33
|
+
savePiSkill,
|
|
34
|
+
saveProviderConfig,
|
|
35
|
+
saveRole,
|
|
36
|
+
setDefaultPiModel,
|
|
37
|
+
toggleCanvasComponent,
|
|
38
|
+
togglePiMcpServer,
|
|
39
|
+
} from '../agent/pi-config.js';
|
|
20
40
|
import {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
import {
|
|
29
|
-
archiveSessionRecord,
|
|
30
|
-
BUILTIN_PERSONAS,
|
|
31
|
-
compactMessages,
|
|
32
|
-
deleteSessionRecord,
|
|
33
|
-
listSessionRecords,
|
|
34
|
-
loadSessionRecord,
|
|
35
|
-
paletteForPersona,
|
|
36
|
-
PERSONA_TEMPLATES,
|
|
37
|
-
resolvePersona,
|
|
41
|
+
archiveSession,
|
|
42
|
+
createPiBridge,
|
|
43
|
+
deleteSession,
|
|
44
|
+
getSessionMeta,
|
|
45
|
+
listSessions,
|
|
46
|
+
renameSession,
|
|
47
|
+
restoreCanvasSnapshot,
|
|
38
48
|
safeSessionId,
|
|
39
|
-
|
|
40
|
-
} from '../agent/
|
|
41
|
-
import { runVerticalAgent } from '../agent/runtime.js';
|
|
42
|
-
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';
|
|
49
|
+
upsertSessionMeta,
|
|
50
|
+
} from '../agent/pi-bridge.js';
|
|
52
51
|
|
|
53
|
-
const
|
|
54
|
-
const
|
|
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({
|
|
52
|
+
const sessionIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
|
|
53
|
+
const canvasObjectSchema = z.object({
|
|
60
54
|
id: z.string().min(1).max(120),
|
|
61
55
|
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(),
|
|
56
|
+
title: z.string().max(160).default(''),
|
|
65
57
|
});
|
|
66
|
-
const canvasSchema = z.
|
|
58
|
+
const canvasSchema = z.object({
|
|
67
59
|
file: z.string().max(1500).optional(),
|
|
68
|
-
revision: z.string().
|
|
60
|
+
revision: z.string().max(128).optional(),
|
|
69
61
|
selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200).default([]),
|
|
70
|
-
objectSelection: z.array(
|
|
62
|
+
objectSelection: z.array(canvasObjectSchema).max(100).optional(),
|
|
71
63
|
});
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
engine: z.enum(['auto', 'builtin', 'acp']).optional(),
|
|
64
|
+
|
|
65
|
+
const agentRequestSchema = z.discriminatedUnion('action', [
|
|
66
|
+
z.object({
|
|
67
|
+
action: z.literal('prompt'),
|
|
68
|
+
session: sessionIdSchema,
|
|
69
|
+
text: z.string().trim().min(1).max(16_000),
|
|
70
|
+
roleId: z.string().max(40).optional(),
|
|
71
|
+
model: z.string().max(160).optional(),
|
|
81
72
|
canvas: canvasSchema.optional(),
|
|
82
73
|
}),
|
|
83
|
-
z.
|
|
84
|
-
action: z.literal('
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
execMode: execModeSchema.optional(),
|
|
91
|
-
persona: personaSchema.optional(),
|
|
74
|
+
z.object({
|
|
75
|
+
action: z.literal('handoff'),
|
|
76
|
+
fromSession: sessionIdSchema.optional(),
|
|
77
|
+
fromRoleName: z.string().max(60).optional(),
|
|
78
|
+
targetRoleId: z.string().min(1).max(40),
|
|
79
|
+
targetSession: sessionIdSchema.optional(),
|
|
80
|
+
text: z.string().trim().max(16_000).default(''),
|
|
92
81
|
canvas: canvasSchema.optional(),
|
|
93
82
|
}),
|
|
94
|
-
z.
|
|
95
|
-
action: z.literal('
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
|
|
100
|
-
execMode: execModeSchema.optional(),
|
|
101
|
-
persona: personaSchema.optional(),
|
|
102
|
-
canvas: canvasSchema.optional(),
|
|
83
|
+
z.object({
|
|
84
|
+
action: z.literal('answer'),
|
|
85
|
+
session: sessionIdSchema,
|
|
86
|
+
questionId: z.string().min(1).max(128),
|
|
87
|
+
answer: z.string().trim().min(1).max(12_000),
|
|
103
88
|
}),
|
|
104
|
-
z.
|
|
105
|
-
action: z.literal('steer'),
|
|
89
|
+
z.object({
|
|
90
|
+
action: z.literal('steer'),
|
|
91
|
+
session: sessionIdSchema,
|
|
106
92
|
text: z.string().trim().min(1).max(4_000),
|
|
107
93
|
}),
|
|
108
|
-
z.
|
|
109
|
-
action: z.
|
|
110
|
-
|
|
111
|
-
text: z.string().trim().max(12_000).default(''),
|
|
112
|
-
viewId: z.uuid().optional(),
|
|
113
|
-
canvas: canvasSchema.optional(),
|
|
94
|
+
z.object({
|
|
95
|
+
action: z.enum(['cancel', 'close']),
|
|
96
|
+
session: sessionIdSchema,
|
|
114
97
|
}),
|
|
115
|
-
z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
|
|
116
98
|
]);
|
|
117
99
|
|
|
118
|
-
async function readJsonBody(req, maxBytes =
|
|
100
|
+
async function readJsonBody(req, maxBytes = 128 * 1024) {
|
|
119
101
|
const chunks = [];
|
|
120
102
|
let bytes = 0;
|
|
121
103
|
for await (const chunk of req) {
|
|
122
104
|
bytes += chunk.length;
|
|
123
|
-
if (bytes > maxBytes) throw new DocumentError('
|
|
105
|
+
if (bytes > maxBytes) throw new DocumentError('请求体过大。', 413);
|
|
124
106
|
chunks.push(chunk);
|
|
125
107
|
}
|
|
126
108
|
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
127
109
|
}
|
|
128
110
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
];
|
|
111
|
+
function sendJson(res, status, data) {
|
|
112
|
+
res.writeHead(status, {
|
|
113
|
+
'content-type': 'application/json; charset=utf-8',
|
|
114
|
+
'cache-control': 'no-store',
|
|
115
|
+
'x-content-type-options': 'nosniff',
|
|
116
|
+
});
|
|
117
|
+
res.end(JSON.stringify(data));
|
|
152
118
|
}
|
|
153
119
|
|
|
154
|
-
function
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
};
|
|
120
|
+
function assertSameOriginPost(req) {
|
|
121
|
+
const host = req.headers.host;
|
|
122
|
+
if (req.headers.origin && req.headers.origin !== 'http://' + host) {
|
|
123
|
+
throw new DocumentError('来源不匹配。', 403);
|
|
124
|
+
}
|
|
204
125
|
}
|
|
205
126
|
|
|
206
127
|
export function createAgentHandler({
|
|
207
|
-
workspace,
|
|
208
|
-
|
|
209
|
-
args = [],
|
|
210
|
-
resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
|
|
211
|
-
resolveSettings = null,
|
|
212
|
-
saveSettings = null,
|
|
128
|
+
workspace,
|
|
129
|
+
mcpUrl,
|
|
213
130
|
resolveRuntimeInfo = null,
|
|
214
131
|
workspaceService = null,
|
|
215
132
|
events = null,
|
|
216
|
-
|
|
133
|
+
sessionFactory = null,
|
|
217
134
|
}) {
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
return { ...launch, ...base };
|
|
224
|
-
};
|
|
135
|
+
const bridge = createPiBridge({
|
|
136
|
+
workspaceService,
|
|
137
|
+
events,
|
|
138
|
+
sessionFactory,
|
|
139
|
+
});
|
|
225
140
|
|
|
226
|
-
|
|
227
|
-
const
|
|
228
|
-
const
|
|
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
|
-
}
|
|
141
|
+
const getRuntime = targetWorkspace => {
|
|
142
|
+
const ws = targetWorkspace || (typeof workspace === 'function' ? workspace() : workspace);
|
|
143
|
+
const info = resolveRuntimeInfo ? resolveRuntimeInfo(ws) : null;
|
|
244
144
|
return {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
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 : [],
|
|
145
|
+
workspace: ws,
|
|
146
|
+
stateDir: info?.stateDir || (ws + '/.clado'),
|
|
147
|
+
documentRoot: info?.documentRoot || ws,
|
|
148
|
+
pluginDescriptors: info?.pluginDescriptors || [],
|
|
257
149
|
};
|
|
258
|
-
}
|
|
259
|
-
|
|
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
|
-
}
|
|
267
|
-
|
|
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
|
-
}
|
|
274
|
-
}
|
|
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
|
-
}
|
|
290
|
-
|
|
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
|
-
}
|
|
150
|
+
};
|
|
299
151
|
|
|
300
|
-
async function
|
|
301
|
-
const
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
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: [] }] : [],
|
|
322
|
-
});
|
|
323
|
-
session.id = result.sessionId;
|
|
324
|
-
}
|
|
152
|
+
async function buildFullMeta(targetWorkspace) {
|
|
153
|
+
const rt = getRuntime(targetWorkspace);
|
|
154
|
+
const agentDir = resolvePiAgentDir();
|
|
155
|
+
const [modelsInfo, ecosystem] = await Promise.all([
|
|
156
|
+
listProvidersAndModels(rt.workspace, agentDir),
|
|
157
|
+
inspectPiEcosystem(rt.workspace, agentDir),
|
|
158
|
+
]);
|
|
159
|
+
const roles = listRoles(agentDir);
|
|
160
|
+
const memory = readAgentsMemory(rt.workspace);
|
|
161
|
+
const canvasComponents = readCanvasComponentsConfig(agentDir);
|
|
162
|
+
const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
|
|
325
163
|
|
|
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
164
|
return {
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
165
|
+
engine: 'pi',
|
|
166
|
+
version: VERSION,
|
|
167
|
+
workspace: rt.workspace,
|
|
168
|
+
mcpUrl: typeof mcpUrl === 'function' ? mcpUrl() : (mcpUrl || ''),
|
|
169
|
+
agentDir,
|
|
170
|
+
defaultProvider: modelsInfo.defaultProvider,
|
|
171
|
+
defaultModel: modelsInfo.defaultModel,
|
|
172
|
+
activeModelLabel: modelsInfo.activeModelLabel,
|
|
173
|
+
providers: modelsInfo.providers,
|
|
174
|
+
configuredModels: modelsInfo.configuredModels,
|
|
175
|
+
roles,
|
|
176
|
+
ecosystem,
|
|
177
|
+
canvasComponents,
|
|
178
|
+
workspacePlugins: rt.pluginDescriptors,
|
|
179
|
+
memory,
|
|
180
|
+
sessions,
|
|
356
181
|
};
|
|
357
182
|
}
|
|
358
183
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
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);
|
|
473
|
-
|
|
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,
|
|
515
|
-
});
|
|
516
|
-
emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
|
|
517
|
-
}
|
|
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',
|
|
535
|
-
});
|
|
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,
|
|
561
|
-
});
|
|
184
|
+
return {
|
|
185
|
+
async handleMeta(req, res, targetWorkspace) {
|
|
186
|
+
if (req.method !== 'GET') throw new DocumentError('仅支持 GET。', 405);
|
|
187
|
+
const data = await buildFullMeta(targetWorkspace);
|
|
188
|
+
sendJson(res, 200, data);
|
|
189
|
+
},
|
|
562
190
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
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,
|
|
575
|
-
});
|
|
576
|
-
emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
|
|
191
|
+
async handleSessions(req, res, url, targetWorkspace) {
|
|
192
|
+
const rt = getRuntime(targetWorkspace);
|
|
193
|
+
const agentDir = resolvePiAgentDir();
|
|
577
194
|
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
195
|
+
if (req.method === 'GET') {
|
|
196
|
+
const id = url.searchParams.get('id');
|
|
197
|
+
if (id) {
|
|
198
|
+
const item = getSessionMeta(rt.stateDir, id, agentDir);
|
|
199
|
+
if (!item) throw new DocumentError('找不到该角色会话。', 404);
|
|
200
|
+
sendJson(res, 200, { session: item });
|
|
201
|
+
return;
|
|
583
202
|
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
const q = String(target || '').trim();
|
|
589
|
-
const msgText = String(message || '').trim().slice(0, 4000);
|
|
590
|
-
if (!q || !msgText) throw new Error('target 与 message 必填。');
|
|
203
|
+
const includeArchived = url.searchParams.get('archived') === '1';
|
|
204
|
+
sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, agentDir }) });
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
591
207
|
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
208
|
+
if (req.method === 'POST') {
|
|
209
|
+
assertSameOriginPost(req);
|
|
210
|
+
const body = await readJsonBody(req);
|
|
211
|
+
if (body?.action === 'rename') {
|
|
212
|
+
const updated = renameSession(rt.stateDir, body.id, body.title, agentDir);
|
|
213
|
+
sendJson(res, 200, { ok: true, session: updated });
|
|
214
|
+
return;
|
|
596
215
|
}
|
|
597
|
-
if (
|
|
598
|
-
|
|
216
|
+
if (body?.action === 'archive') {
|
|
217
|
+
const updated = archiveSession(rt.stateDir, body.id, body.archived !== false, agentDir);
|
|
218
|
+
sendJson(res, 200, { ok: Boolean(updated), session: updated });
|
|
219
|
+
return;
|
|
599
220
|
}
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
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
|
-
});
|
|
627
|
-
|
|
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 || '同伴'}」呼叫…`;
|
|
635
|
-
|
|
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,
|
|
649
|
-
});
|
|
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
|
-
});
|
|
221
|
+
if (body?.action === 'rollback') {
|
|
222
|
+
const result = restoreCanvasSnapshot(rt.documentRoot, rt.stateDir, body.id, body.snapshotId || '', events, rt.workspace);
|
|
223
|
+
sendJson(res, 200, result);
|
|
224
|
+
return;
|
|
656
225
|
}
|
|
226
|
+
const created = upsertSessionMeta(rt.stateDir, {
|
|
227
|
+
id: body.id ? safeSessionId(body.id) : undefined,
|
|
228
|
+
title: body.title,
|
|
229
|
+
roleId: body.roleId || body.persona || 'architect',
|
|
230
|
+
model: body.model || '',
|
|
231
|
+
}, agentDir);
|
|
232
|
+
sendJson(res, 200, { ok: true, session: created });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
657
235
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
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 });
|
|
236
|
+
if (req.method === 'DELETE') {
|
|
237
|
+
assertSameOriginPost(req);
|
|
238
|
+
const id = url.searchParams.get('id');
|
|
239
|
+
if (!id) throw new DocumentError('缺少会话 ID。', 400);
|
|
240
|
+
await bridge.cancel(rt.workspace, id);
|
|
241
|
+
sendJson(res, 200, deleteSession(rt.stateDir, id, agentDir));
|
|
242
|
+
return;
|
|
686
243
|
}
|
|
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
244
|
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
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
|
-
};
|
|
245
|
+
throw new DocumentError('不支持的请求方法。', 405);
|
|
246
|
+
},
|
|
247
|
+
|
|
248
|
+
async handleConfig(req, res, targetWorkspace) {
|
|
249
|
+
const rt = getRuntime(targetWorkspace);
|
|
250
|
+
const agentDir = resolvePiAgentDir();
|
|
734
251
|
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
if (!record) throw new DocumentError('未找到该历史会话。', 404);
|
|
739
|
-
sendJson(200, { session: record });
|
|
252
|
+
if (req.method === 'GET') {
|
|
253
|
+
const data = await buildFullMeta(targetWorkspace);
|
|
254
|
+
sendJson(res, 200, data);
|
|
740
255
|
return;
|
|
741
256
|
}
|
|
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
|
-
}
|
|
752
257
|
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
return (async () => {
|
|
758
|
-
const body = await readJsonBody(req, 32 * 1024);
|
|
759
|
-
const act = body?.action;
|
|
258
|
+
if (req.method !== 'POST') throw new DocumentError('仅支持 GET 或 POST。', 405);
|
|
259
|
+
assertSameOriginPost(req);
|
|
260
|
+
const body = await readJsonBody(req, 256 * 1024);
|
|
261
|
+
const action = String(body?.action || '').trim();
|
|
760
262
|
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
const
|
|
764
|
-
|
|
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 });
|
|
263
|
+
try {
|
|
264
|
+
if (action === 'save_provider') {
|
|
265
|
+
const result = saveProviderConfig(body, agentDir, rt.workspace);
|
|
266
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
784
267
|
return;
|
|
785
268
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
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 });
|
|
269
|
+
if (action === 'delete_provider') {
|
|
270
|
+
const result = deleteProviderConfig(body.providerId, agentDir);
|
|
271
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
802
272
|
return;
|
|
803
273
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
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,
|
|
822
|
-
});
|
|
823
|
-
emitSessionSync(targetWorkspace, stateDir, meta.debugConfig.autoArchiveHours);
|
|
824
|
-
sendJson(200, { session: updated });
|
|
274
|
+
if (action === 'set_default_model') {
|
|
275
|
+
const result = await setDefaultPiModel(body.provider, body.model, agentDir, rt.workspace);
|
|
276
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
825
277
|
return;
|
|
826
278
|
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
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 });
|
|
279
|
+
if (action === 'save_role') {
|
|
280
|
+
const role = saveRole(body, agentDir);
|
|
281
|
+
sendJson(res, 200, { ok: true, role, meta: await buildFullMeta(targetWorkspace) });
|
|
835
282
|
return;
|
|
836
283
|
}
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
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 });
|
|
284
|
+
if (action === 'delete_role') {
|
|
285
|
+
const result = deleteRole(body.id, agentDir);
|
|
286
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
852
287
|
return;
|
|
853
288
|
}
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
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 });
|
|
289
|
+
if (action === 'save_mcp') {
|
|
290
|
+
const result = savePiMcpServer(body, rt.workspace, agentDir);
|
|
291
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
888
292
|
return;
|
|
889
293
|
}
|
|
890
|
-
|
|
891
|
-
|
|
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 }) });
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
|
|
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 }) });
|
|
1039
|
-
return;
|
|
1040
|
-
}
|
|
1041
|
-
|
|
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
|
-
});
|
|
294
|
+
if (action === 'toggle_mcp') {
|
|
295
|
+
const result = togglePiMcpServer(body.name, body.enabled, rt.workspace, agentDir);
|
|
296
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
297
|
+
return;
|
|
1063
298
|
}
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
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
|
-
}
|
|
1083
|
-
|
|
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
|
-
});
|
|
1098
|
-
return;
|
|
1099
|
-
}
|
|
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 }) });
|
|
299
|
+
if (action === 'delete_mcp') {
|
|
300
|
+
const result = deletePiMcpServer(body.name, rt.workspace, agentDir);
|
|
301
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
1142
302
|
return;
|
|
1143
|
-
} catch (err) {
|
|
1144
|
-
throw new DocumentError(err.message || '保存 MCP 服务失败。', 400);
|
|
1145
303
|
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
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 }) });
|
|
304
|
+
if (action === 'import_mcp_json') {
|
|
305
|
+
const result = importPiMcpJson(body.json, body.scope || 'user', rt.workspace, agentDir);
|
|
306
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
1155
307
|
return;
|
|
1156
|
-
} catch (err) {
|
|
1157
|
-
throw new DocumentError(err.message || '切换 MCP 状态失败。', 400);
|
|
1158
308
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
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 ?? '',
|
|
1173
|
-
});
|
|
1174
|
-
sendJson(200, { ok: true, imported, mcpServers: listMcpServers(targetWorkspace, { pluginMcp }) });
|
|
309
|
+
if (action === 'save_skill') {
|
|
310
|
+
const result = savePiSkill(body, rt.workspace, agentDir);
|
|
311
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
1175
312
|
return;
|
|
1176
|
-
} catch (err) {
|
|
1177
|
-
throw new DocumentError(err.message || '导入 MCP JSON 失败。', 400);
|
|
1178
313
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
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;
|
|
314
|
+
if (action === 'delete_skill') {
|
|
315
|
+
const result = deletePiSkill(body.name, rt.workspace, agentDir);
|
|
316
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
317
|
+
return;
|
|
1186
318
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
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 }) });
|
|
319
|
+
if (action === 'save_command') {
|
|
320
|
+
const result = savePiPrompt(body, rt.workspace, agentDir);
|
|
321
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
1203
322
|
return;
|
|
1204
|
-
} catch (err) {
|
|
1205
|
-
throw new DocumentError(err.message || '保存技能失败。', 400);
|
|
1206
323
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
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 }) });
|
|
324
|
+
if (action === 'delete_command') {
|
|
325
|
+
const result = deletePiPrompt(body.name, rt.workspace, agentDir);
|
|
326
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
1229
327
|
return;
|
|
1230
|
-
} catch (err) {
|
|
1231
|
-
throw new DocumentError(err.message || '保存斜杠命令失败。', 400);
|
|
1232
328
|
}
|
|
329
|
+
if (action === 'install_pi_package') {
|
|
330
|
+
const result = await installPiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
|
|
331
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (action === 'remove_pi_package') {
|
|
335
|
+
const result = await removePiPackage(body.source, { local: Boolean(body.local) }, rt.workspace, agentDir);
|
|
336
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (action === 'save_memory') {
|
|
340
|
+
const result = saveAgentsMemory(rt.workspace, body.content);
|
|
341
|
+
sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (action === 'toggle_canvas_component') {
|
|
345
|
+
const canvasComponents = toggleCanvasComponent(body.id, body.enabled, agentDir);
|
|
346
|
+
sendJson(res, 200, { ok: true, canvasComponents, meta: await buildFullMeta(targetWorkspace) });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
throw new DocumentError(`不支持的配置操作:${action}`, 400);
|
|
350
|
+
} catch (err) {
|
|
351
|
+
if (err instanceof DocumentError) throw err;
|
|
352
|
+
throw new DocumentError(err?.message || '配置更新失败', 400);
|
|
1233
353
|
}
|
|
1234
|
-
|
|
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
|
-
}
|
|
354
|
+
},
|
|
1242
355
|
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
356
|
+
async handle(req, res, targetWorkspace) {
|
|
357
|
+
if (req.method !== 'POST') throw new DocumentError('仅支持 POST。', 405);
|
|
358
|
+
assertSameOriginPost(req);
|
|
359
|
+
const raw = await readJsonBody(req);
|
|
360
|
+
const parsed = agentRequestSchema.safeParse(raw);
|
|
361
|
+
if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
|
|
362
|
+
const input = parsed.data;
|
|
363
|
+
const rt = getRuntime(targetWorkspace);
|
|
364
|
+
const agentDir = resolvePiAgentDir();
|
|
365
|
+
|
|
366
|
+
if (input.action === 'answer') {
|
|
367
|
+
const ok = bridge.answer(rt.workspace, input.session, input.questionId, input.answer);
|
|
368
|
+
sendJson(res, 200, { ok });
|
|
1250
369
|
return;
|
|
1251
370
|
}
|
|
1252
|
-
|
|
1253
|
-
|
|
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('已停止连接。'));
|
|
371
|
+
if (input.action === 'steer') {
|
|
372
|
+
const ok = await bridge.steer(rt.workspace, input.session, input.text);
|
|
373
|
+
sendJson(res, 200, { ok });
|
|
374
|
+
return;
|
|
1281
375
|
}
|
|
1282
|
-
|
|
1283
|
-
|
|
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' }));
|
|
376
|
+
if (input.action === 'cancel' || input.action === 'close') {
|
|
377
|
+
const ok = await bridge.cancel(rt.workspace, input.session);
|
|
378
|
+
sendJson(res, 200, { ok });
|
|
1293
379
|
return;
|
|
1294
380
|
}
|
|
1295
|
-
throw new DocumentError('当前会话未在运行中,请直接发送消息。', 409);
|
|
1296
|
-
}
|
|
1297
381
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
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,
|
|
382
|
+
// Streaming NDJSON response for prompt & handoff
|
|
383
|
+
res.writeHead(200, {
|
|
384
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
385
|
+
'cache-control': 'no-store',
|
|
386
|
+
'x-content-type-options': 'nosniff',
|
|
1309
387
|
});
|
|
1310
|
-
|
|
1311
|
-
|
|
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,
|
|
388
|
+
const emit = event => {
|
|
389
|
+
if (res.writableEnded || res.destroyed) return;
|
|
390
|
+
try { res.write(JSON.stringify(event) + '\n'); } catch {}
|
|
1324
391
|
};
|
|
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
392
|
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
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: '用户发起了新的指令' }),
|
|
1376
|
-
});
|
|
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;
|
|
1384
|
-
}
|
|
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;
|
|
1392
|
-
}
|
|
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,
|
|
393
|
+
if (input.action === 'handoff') {
|
|
394
|
+
const targetRole = resolveRole(input.targetRoleId, agentDir);
|
|
395
|
+
const existing = listSessions(rt.stateDir, { agentDir }).find(s => s.roleId === targetRole.id);
|
|
396
|
+
const targetSessionId = input.targetSession || existing?.id || ('role_' + targetRole.id);
|
|
397
|
+
const defaultTask = targetRole.id === 'developer'
|
|
398
|
+
? '请依据上述画布设计契约落地代码实现,并在完成后运行校验命令汇报结果。'
|
|
399
|
+
: targetRole.id === 'tester'
|
|
400
|
+
? '请依据上述画布契约补充单元测试与边界回归用例,并执行测试汇报结果。'
|
|
401
|
+
: targetRole.id === 'archivist'
|
|
402
|
+
? '请将上述画布定稿内容整理为清晰的架构文档 / ADR 决策记录。'
|
|
403
|
+
: '请依据上述画布契约推进当前阶段工作。';
|
|
404
|
+
|
|
405
|
+
await bridge.runTurn({
|
|
406
|
+
workspace: rt.workspace,
|
|
407
|
+
stateDir: rt.stateDir,
|
|
408
|
+
documentRoot: rt.documentRoot,
|
|
409
|
+
sessionId: targetSessionId,
|
|
410
|
+
roleId: targetRole.id,
|
|
411
|
+
text: input.text || defaultTask,
|
|
412
|
+
canvas: input.canvas,
|
|
413
|
+
handoffFrom: input.fromRoleName || '画布定稿',
|
|
414
|
+
emit,
|
|
1456
415
|
});
|
|
1457
|
-
|
|
1458
|
-
|
|
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,
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
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,
|
|
1487
|
-
});
|
|
1488
|
-
}
|
|
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,
|
|
1524
|
-
});
|
|
1525
|
-
emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
|
|
1526
|
-
}
|
|
1527
|
-
return { stopReason: result.stopReason };
|
|
1528
|
-
}
|
|
1529
|
-
|
|
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
|
-
};
|
|
1541
|
-
|
|
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);
|
|
1550
|
-
|
|
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
|
-
});
|
|
1567
|
-
|
|
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() : '',
|
|
1588
|
-
});
|
|
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;
|
|
416
|
+
if (!res.writableEnded) res.end();
|
|
417
|
+
return;
|
|
1622
418
|
}
|
|
1623
419
|
|
|
1624
|
-
//
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1637
|
-
|
|
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,
|
|
1653
|
-
});
|
|
1654
|
-
emitSessionSync(targetWorkspace, meta.rtInfo.stateDir, meta.debugConfig.autoArchiveHours);
|
|
1655
|
-
}
|
|
1656
|
-
return response;
|
|
1657
|
-
};
|
|
420
|
+
// action === 'prompt'
|
|
421
|
+
await bridge.runTurn({
|
|
422
|
+
workspace: rt.workspace,
|
|
423
|
+
stateDir: rt.stateDir,
|
|
424
|
+
documentRoot: rt.documentRoot,
|
|
425
|
+
sessionId: input.session,
|
|
426
|
+
roleId: input.roleId,
|
|
427
|
+
modelSpec: input.model,
|
|
428
|
+
text: input.text,
|
|
429
|
+
canvas: input.canvas,
|
|
430
|
+
emit,
|
|
431
|
+
});
|
|
432
|
+
if (!res.writableEnded) res.end();
|
|
433
|
+
},
|
|
1658
434
|
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
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); },
|
|
435
|
+
close() {
|
|
436
|
+
return bridge.closeAll();
|
|
437
|
+
},
|
|
1693
438
|
};
|
|
1694
439
|
}
|