cladogram 0.5.5-beta.1 → 0.5.5-beta.3
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 +2 -0
- package/docs/release.md +14 -2
- package/package.json +1 -1
- package/plugins/agent/index.js +457 -24
- package/plugins/agent/style.css +299 -8
- package/skills/clado/SKILL.md +1 -0
- package/src/agent/executors.js +213 -0
- package/src/agent/probe.js +176 -0
- package/src/agent/providers/anthropic.js +220 -0
- package/src/agent/providers/index.js +52 -0
- package/src/agent/providers/openai.js +146 -0
- package/src/agent/runtime.js +557 -0
- package/src/agent/sessions.js +129 -0
- package/src/core/media-links.js +165 -11
- package/src/core/parse.js +25 -4
- package/src/html/canvas-ui.css +64 -1
- package/src/html/canvas-wires.js +2 -2
- package/src/html/media-anchors.js +174 -28
- package/src/html/mindmap-connectors.js +12 -10
- package/src/html/page.js +4 -0
- package/src/html/runtime-api.js +136 -5
- package/src/html/runtime.js +17 -218
- package/src/html/view-registry.js +95 -0
- package/src/html/views/view-cards.js +28 -0
- package/src/html/views/view-doc.js +51 -0
- package/src/html/views/view-mindmap.js +173 -0
- package/src/server/agent.js +331 -14
- package/src/server/assets/library-canvas.js +11 -2
- package/src/server/assets/library.js +92 -5
- package/src/server/events.js +189 -0
- package/src/server/mcp.js +10 -5
- package/src/server/plugin-settings.js +26 -0
- package/src/server/plugins.js +16 -3
- package/src/server/workspace.js +41 -3
- package/src/workspace/service.js +58 -21
- package/templates/test-cases.mdc +47 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/* ══ 内置视图插件:clado.view.mindmap(脑图视图) ════════════════ */
|
|
2
|
+
var MIND_CARD_STATE = {};
|
|
3
|
+
function applyMindCardPlacement(el) {
|
|
4
|
+
el.dataset.layoutX = el.style.left; el.dataset.layoutY = el.style.top;
|
|
5
|
+
var state = MIND_CARD_STATE[el.dataset.contentId];
|
|
6
|
+
if (state) {
|
|
7
|
+
el.style.left = (parseFloat(el.style.left) + (state.dx || 0)) + 'px';
|
|
8
|
+
el.style.top = (parseFloat(el.style.top) + (state.dy || 0)) + 'px';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function bindMindCard(el) {
|
|
12
|
+
function state() { return MIND_CARD_STATE[el.dataset.contentId] || (MIND_CARD_STATE[el.dataset.contentId] = {}); }
|
|
13
|
+
bindCanvasCard(el, {
|
|
14
|
+
move: function (x, y) { var s = state(); s.dx = x - parseFloat(el.dataset.layoutX); s.dy = y - parseFloat(el.dataset.layoutY); },
|
|
15
|
+
resize: function (width, height) { var s = state(); s.width = width; s.height = height; },
|
|
16
|
+
redraw: function () { drawMindWires(); }
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function renderMind() {
|
|
20
|
+
var mind = $('#mind');
|
|
21
|
+
$$('.mnode', mind).forEach(function (n) { n.remove(); });
|
|
22
|
+
var GX = 64, GY = 12, X0 = 40, Y0 = 40;
|
|
23
|
+
var cursor = Y0;
|
|
24
|
+
var ALL = []; // 所有节点,等宽度都量完了再统一算 left
|
|
25
|
+
// 先摆子、再回头把父摆在子的垂直中线上 —— 父先占位的话,父会挂在子树的头顶上,不是树
|
|
26
|
+
function place(nodes, depth, prefix) {
|
|
27
|
+
var out = [];
|
|
28
|
+
nodes.forEach(function (n, i) {
|
|
29
|
+
var path = prefix ? prefix + '.' + i : String(i);
|
|
30
|
+
var hasKids = !!(n.kids && n.kids.length);
|
|
31
|
+
var el = createCanvasCard(n.title, 'mnode');
|
|
32
|
+
el.dataset.path = path; el.dataset.contentId = n.card || n.id || '__document';
|
|
33
|
+
// 记下这张小卡片对应文档里的哪张卡 —— 画关系边的时候要靠它对上号
|
|
34
|
+
if (n.card) el.dataset.card = n.card;
|
|
35
|
+
if (n.md && n.md.trim()) el.classList.add('has-body');
|
|
36
|
+
$('.body', el).appendChild(mdToBody(n.md));
|
|
37
|
+
var savedSize = MIND_CARD_STATE[el.dataset.contentId];
|
|
38
|
+
if (savedSize && savedSize.width) el.style.width = savedSize.width + 'px';
|
|
39
|
+
if (savedSize && savedSize.height) el.style.height = savedSize.height + 'px';
|
|
40
|
+
mind.appendChild(el); bindMindCard(el);
|
|
41
|
+
ALL.push({ el: el, depth: depth });
|
|
42
|
+
var b = { el: el, kids: [] };
|
|
43
|
+
var from = cursor;
|
|
44
|
+
if (hasKids) {
|
|
45
|
+
b.kids = place(n.kids, depth + 1, path);
|
|
46
|
+
var f = b.kids[0].el, l = b.kids[b.kids.length - 1].el;
|
|
47
|
+
var mid = (f.offsetTop + l.offsetTop + l.offsetHeight) / 2;
|
|
48
|
+
var top = mid - el.offsetHeight / 2;
|
|
49
|
+
if (top < from) {
|
|
50
|
+
var shift = from - top;
|
|
51
|
+
(function shiftChildren(branches) {
|
|
52
|
+
branches.forEach(function (branch) {
|
|
53
|
+
branch.el.style.top = (parseFloat(branch.el.style.top) + shift) + 'px';
|
|
54
|
+
shiftChildren(branch.kids);
|
|
55
|
+
});
|
|
56
|
+
})(b.kids);
|
|
57
|
+
cursor += shift; top = from;
|
|
58
|
+
}
|
|
59
|
+
el.style.top = top + 'px';
|
|
60
|
+
} else {
|
|
61
|
+
el.style.top = cursor + 'px';
|
|
62
|
+
cursor += el.offsetHeight + GY;
|
|
63
|
+
}
|
|
64
|
+
cursor = Math.max(cursor, el.offsetTop + el.offsetHeight + GY);
|
|
65
|
+
out.push(b);
|
|
66
|
+
});
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
// 一棵树,不是好几棵:先立一个「文档」根,每张卡是它的第一层分支
|
|
70
|
+
var root = {
|
|
71
|
+
title: DOC.title || '文档', md: DOC.preamble,
|
|
72
|
+
kids: DOC.cards.map(function (c) { return { title: c.title, md: c.md, kids: c.nodes || [], card: c.id }; }),
|
|
73
|
+
};
|
|
74
|
+
var all = place([root], 0, '');
|
|
75
|
+
all.forEach(function (r) { r.el.classList.add('root'); });
|
|
76
|
+
/*
|
|
77
|
+
* 每一列取这一列最宽的那个节点当列宽,再按列累加出 x —— 宽度是内容说了算,
|
|
78
|
+
* 列里最宽的那张决定下一列从哪开始,列与列之间才不会叠在一起。
|
|
79
|
+
*/
|
|
80
|
+
var colW = [];
|
|
81
|
+
ALL.forEach(function (x) {
|
|
82
|
+
colW[x.depth] = Math.max(colW[x.depth] || 0, x.el.offsetWidth);
|
|
83
|
+
});
|
|
84
|
+
var colX = [], acc = X0;
|
|
85
|
+
for (var ci = 0; ci < colW.length; ci++) {
|
|
86
|
+
colX[ci] = acc;
|
|
87
|
+
acc += (colW[ci] || 0) + GX;
|
|
88
|
+
}
|
|
89
|
+
ALL.forEach(function (x) { x.el.style.left = colX[x.depth] + 'px'; applyMindCardPlacement(x.el); });
|
|
90
|
+
var w = 0, h = 0;
|
|
91
|
+
$$('.mnode', mind).forEach(function (n) {
|
|
92
|
+
w = Math.max(w, n.offsetLeft + n.offsetWidth);
|
|
93
|
+
h = Math.max(h, n.offsetTop + n.offsetHeight);
|
|
94
|
+
});
|
|
95
|
+
box = { w: w + X0, h: h + Y0 };
|
|
96
|
+
drawMindWires();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function drawMindWires() {
|
|
100
|
+
var mind = $('#mind');
|
|
101
|
+
/*
|
|
102
|
+
* ★ 文档里的关系边(正文里 [文字](目标) 连出来的那些)也要画在脑图上。
|
|
103
|
+
* 原来脑图只有「树」的线 —— 那是标题嵌套长出来的父子线,文档里真正
|
|
104
|
+
* 声明的边一条都没有,看着就像「脑图上没连线」。
|
|
105
|
+
* 只连线,不碰布局:脑图的坐标是 place() 摆好的,这里纯粹是照着画。
|
|
106
|
+
* 脑图里每张卡都摊成了小卡片,没有「一二三级标题」之分,所以一律浅色虚线。
|
|
107
|
+
*/
|
|
108
|
+
var nodeOf = {};
|
|
109
|
+
$$('.mnode[data-card]', mind).forEach(function (n) { nodeOf[n.dataset.card] = n; });
|
|
110
|
+
var svg = $('#mwires');
|
|
111
|
+
svg.setAttribute('width', box.w); svg.setAttribute('height', box.h);
|
|
112
|
+
svg.setAttribute('viewBox', '0 0 ' + box.w + ' ' + box.h);
|
|
113
|
+
svg.style.width = box.w + 'px'; svg.style.height = box.h + 'px';
|
|
114
|
+
var d = '';
|
|
115
|
+
DOC.edges.forEach(function (e) {
|
|
116
|
+
var A = nodeOf[e[0]], B = nodeOf[e[1]];
|
|
117
|
+
if (!A || !B) return;
|
|
118
|
+
var ax = A.offsetLeft, aw = A.offsetWidth, bx = B.offsetLeft, bw = B.offsetWidth;
|
|
119
|
+
var y1 = A.offsetTop + A.offsetHeight / 2, y2 = B.offsetTop + B.offsetHeight / 2;
|
|
120
|
+
var x1, x2, c1, c2;
|
|
121
|
+
if (Math.abs(ax - bx) < 1) {
|
|
122
|
+
/*
|
|
123
|
+
* ★ 同一列的边:卡片节点全在第一列,左右边完全重合。原来 x1 取源卡右边、
|
|
124
|
+
* x2 取目标卡左边,等于横穿整列卡片画一道弧 —— 看着就像「所有线都是从
|
|
125
|
+
* 一级那一列拉出来的」,而不是从某张卡出来。改成两头都钉在右边、向右
|
|
126
|
+
* 鼓出去再绕回来:线从哪张卡出、进哪张卡,一眼能对上。
|
|
127
|
+
*/
|
|
128
|
+
x1 = ax + aw; x2 = bx + bw;
|
|
129
|
+
var bulge = Math.max(x1, x2) + 44;
|
|
130
|
+
c1 = bulge; c2 = bulge;
|
|
131
|
+
} else if (bx < ax) { x1 = ax; x2 = bx + bw; c1 = (x1 + x2) / 2; c2 = c1; }
|
|
132
|
+
else { x1 = ax + aw; x2 = bx; c1 = (x1 + x2) / 2; c2 = c1; }
|
|
133
|
+
if (x2 === x1 && c1 === x1) return;
|
|
134
|
+
d += '<path class="edge" d="M' + x1 + ' ' + y1 + ' C' + c1 + ' ' + y1 + ' ' + c2 + ' ' + y2 + ' ' + x2 + ' ' + y2 + '"/>';
|
|
135
|
+
});
|
|
136
|
+
var byPath = {};
|
|
137
|
+
$$('.mnode', mind).forEach(function (el) { byPath[el.dataset.path] = el; });
|
|
138
|
+
Object.keys(byPath).forEach(function (path) {
|
|
139
|
+
var child = byPath[path], parent = byPath[path.slice(0, path.lastIndexOf('.'))];
|
|
140
|
+
if (!parent || !path.includes('.')) return;
|
|
141
|
+
var x1 = parent.offsetLeft + parent.offsetWidth, x2 = child.offsetLeft;
|
|
142
|
+
var input1 = $('.hbar', parent), input2 = $('.hbar', child);
|
|
143
|
+
var y1 = parent.offsetTop + input1.offsetTop + input1.offsetHeight / 2;
|
|
144
|
+
var y2 = child.offsetTop + input2.offsetTop + input2.offsetHeight / 2, mx = (x1 + x2) / 2;
|
|
145
|
+
d += '<path d="M' + x1 + ' ' + y1 + ' C' + mx + ' ' + y1 + ' ' + mx + ' ' + y2 + ' ' + x2 + ' ' + y2 + '"/>';
|
|
146
|
+
});
|
|
147
|
+
svg.innerHTML = d;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
CladoViewRegistry.registerBuiltIn({
|
|
151
|
+
id: 'clado.view.mindmap',
|
|
152
|
+
mode: 'mindmap',
|
|
153
|
+
label: '脑图',
|
|
154
|
+
scope: '#mind',
|
|
155
|
+
activate: function () {
|
|
156
|
+
// 脑图的节点位置是按「当前高度」摆的,所以图渲完必须重摆一次
|
|
157
|
+
requestAnimationFrame(function () {
|
|
158
|
+
renderMind(); fit();
|
|
159
|
+
var mm = $$('#mind .mermaid');
|
|
160
|
+
mm.forEach(function (d) { delete d.dataset.mmd; });
|
|
161
|
+
renderMermaid().then(function () { renderMind(); fit(); });
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
refresh: function () {
|
|
165
|
+
renderMind();
|
|
166
|
+
fit();
|
|
167
|
+
repinPorts();
|
|
168
|
+
},
|
|
169
|
+
restore: function () {
|
|
170
|
+
renderMind();
|
|
171
|
+
},
|
|
172
|
+
drawWires: function () { drawMindWires(); },
|
|
173
|
+
});
|
package/src/server/agent.js
CHANGED
|
@@ -4,19 +4,49 @@ import { client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk
|
|
|
4
4
|
import { z } from 'zod/v4';
|
|
5
5
|
import { VERSION } from '../util/version.js';
|
|
6
6
|
import { DocumentError } from '../workspace/documents.js';
|
|
7
|
+
import {
|
|
8
|
+
buildDispatchPrompt, createRunRecord, discoverExecutors, listRunRecords, publicExecutorList, updateRunRecord,
|
|
9
|
+
} from '../agent/executors.js';
|
|
10
|
+
import { resolveProviderCredentials } from '../agent/providers/index.js';
|
|
11
|
+
import {
|
|
12
|
+
BUILTIN_PERSONAS, deleteSessionRecord, listSessionRecords, loadSessionRecord, saveSessionRecord,
|
|
13
|
+
} from '../agent/sessions.js';
|
|
14
|
+
import { runVerticalAgent } from '../agent/runtime.js';
|
|
7
15
|
|
|
8
16
|
const idleMs = 15 * 60_000;
|
|
9
17
|
const turnMs = 5 * 60_000;
|
|
10
18
|
const sessionId = z.uuid();
|
|
19
|
+
const personaSchema = z.enum(['architect', 'qa', 'auditor', 'custom']);
|
|
20
|
+
const canvasSchema = z.strictObject({
|
|
21
|
+
file: z.string().min(1).max(1500),
|
|
22
|
+
revision: z.string().regex(/^[a-f0-9]{64}$/),
|
|
23
|
+
selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200),
|
|
24
|
+
});
|
|
11
25
|
const requestSchema = z.discriminatedUnion('action', [
|
|
12
26
|
z.strictObject({
|
|
13
27
|
action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
|
|
14
28
|
viewId: z.uuid().optional(),
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
29
|
+
mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
|
|
30
|
+
persona: personaSchema.optional(),
|
|
31
|
+
engine: z.enum(['auto', 'builtin', 'acp']).optional(),
|
|
32
|
+
canvas: canvasSchema.optional(),
|
|
33
|
+
}),
|
|
34
|
+
z.strictObject({
|
|
35
|
+
action: z.literal('answer'), session: sessionId,
|
|
36
|
+
questionId: z.string().min(1).max(128),
|
|
37
|
+
choiceId: z.string().max(128).optional(),
|
|
38
|
+
answer: z.string().trim().min(1).max(12_000),
|
|
39
|
+
viewId: z.uuid().optional(),
|
|
40
|
+
mode: z.enum(['general', 'design', 'qa', 'audit']).optional(),
|
|
41
|
+
persona: personaSchema.optional(),
|
|
42
|
+
canvas: canvasSchema.optional(),
|
|
43
|
+
}),
|
|
44
|
+
z.strictObject({
|
|
45
|
+
action: z.literal('dispatch'), session: sessionId,
|
|
46
|
+
executorId: z.string().min(1).max(128).optional(),
|
|
47
|
+
text: z.string().trim().max(12_000).default(''),
|
|
48
|
+
viewId: z.uuid().optional(),
|
|
49
|
+
canvas: canvasSchema.optional(),
|
|
20
50
|
}),
|
|
21
51
|
z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
|
|
22
52
|
]);
|
|
@@ -106,20 +136,38 @@ export function createAgentHandler({
|
|
|
106
136
|
command = process.env.CLADO_CODEX_ACP_PATH || 'codex-acp',
|
|
107
137
|
args = [],
|
|
108
138
|
resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
|
|
139
|
+
resolveSettings = null,
|
|
140
|
+
resolveRuntimeInfo = null,
|
|
141
|
+
workspaceService = null,
|
|
142
|
+
events = null,
|
|
143
|
+
fetchImpl = fetch,
|
|
109
144
|
}) {
|
|
110
145
|
const sessions = new Map();
|
|
111
146
|
const mcpName = () => 'clado_canvas_' + new URL(mcpUrl()).port;
|
|
147
|
+
const readSettings = () => {
|
|
148
|
+
const base = resolveSettings ? resolveSettings() : {};
|
|
149
|
+
const launch = resolveLaunch();
|
|
150
|
+
return { ...launch, ...base };
|
|
151
|
+
};
|
|
152
|
+
|
|
112
153
|
function close(session, error) {
|
|
113
154
|
if (sessions.get(session.key) !== session) return;
|
|
114
155
|
sessions.delete(session.key);
|
|
115
156
|
clearTimeout(session.idle);
|
|
157
|
+
session.abortController?.abort();
|
|
116
158
|
session.fail?.(error || new Error('Agent 会话已关闭。'));
|
|
117
159
|
session.agent?.dispose();
|
|
118
160
|
}
|
|
119
161
|
|
|
120
|
-
async function
|
|
162
|
+
async function connectAcp(session, launchOverride = null) {
|
|
163
|
+
const launch = launchOverride || resolveLaunch();
|
|
121
164
|
session.agent = startAgent({
|
|
122
|
-
workspace: session.workspace,
|
|
165
|
+
workspace: session.workspace,
|
|
166
|
+
command: launch.command,
|
|
167
|
+
args: launch.args || [],
|
|
168
|
+
env: launch.env || {},
|
|
169
|
+
mcpName: mcpName(),
|
|
170
|
+
emit: event => session.emit?.(event),
|
|
123
171
|
closed: error => close(session, error),
|
|
124
172
|
});
|
|
125
173
|
const { rpc } = session.agent;
|
|
@@ -137,6 +185,94 @@ export function createAgentHandler({
|
|
|
137
185
|
session.id = result.sessionId;
|
|
138
186
|
}
|
|
139
187
|
|
|
188
|
+
function resolveMeta(targetWorkspace) {
|
|
189
|
+
const settings = readSettings();
|
|
190
|
+
const rtInfo = resolveRuntimeInfo ? resolveRuntimeInfo(targetWorkspace) : {};
|
|
191
|
+
const executors = discoverExecutors({
|
|
192
|
+
stateDir: rtInfo.stateDir,
|
|
193
|
+
settings,
|
|
194
|
+
pluginDescriptors: rtInfo.pluginDescriptors || [],
|
|
195
|
+
});
|
|
196
|
+
const creds = resolveProviderCredentials(settings);
|
|
197
|
+
const builtinConfigured = Boolean(creds.apiKey);
|
|
198
|
+
const configuredMode = settings.mode || 'auto';
|
|
199
|
+
const activeEngine = configuredMode === 'builtin'
|
|
200
|
+
? 'builtin'
|
|
201
|
+
: configuredMode === 'acp'
|
|
202
|
+
? 'acp'
|
|
203
|
+
: (builtinConfigured ? 'builtin' : 'acp');
|
|
204
|
+
return {
|
|
205
|
+
settings,
|
|
206
|
+
rtInfo,
|
|
207
|
+
executors,
|
|
208
|
+
builtinConfigured,
|
|
209
|
+
activeEngine,
|
|
210
|
+
provider: creds.provider,
|
|
211
|
+
model: creds.model,
|
|
212
|
+
defaultPersona: settings.persona || 'architect',
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function handleMeta(req, res, targetWorkspace = workspace) {
|
|
217
|
+
const host = req.headers.host || '';
|
|
218
|
+
if (req.method !== 'GET') throw new DocumentError('Agent 元信息仅支持 GET。', 405);
|
|
219
|
+
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
|
|
220
|
+
const meta = resolveMeta(targetWorkspace);
|
|
221
|
+
res.writeHead(200, {
|
|
222
|
+
'content-type': 'application/json; charset=utf-8',
|
|
223
|
+
'cache-control': 'no-store',
|
|
224
|
+
'x-content-type-options': 'nosniff',
|
|
225
|
+
});
|
|
226
|
+
res.end(JSON.stringify({
|
|
227
|
+
engine: meta.activeEngine,
|
|
228
|
+
provider: meta.provider,
|
|
229
|
+
builtinConfigured: meta.builtinConfigured,
|
|
230
|
+
model: meta.model,
|
|
231
|
+
defaultPersona: meta.defaultPersona,
|
|
232
|
+
personas: BUILTIN_PERSONAS.map(({ id, name, summary }) => ({ id, name, summary })),
|
|
233
|
+
executors: publicExecutorList(meta.executors),
|
|
234
|
+
runs: listRunRecords(meta.rtInfo.stateDir, 10),
|
|
235
|
+
sessions: listSessionRecords(meta.rtInfo.stateDir, 20),
|
|
236
|
+
}));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function handleSessions(req, res, url, targetWorkspace = workspace) {
|
|
240
|
+
const host = req.headers.host || '';
|
|
241
|
+
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) throw new DocumentError('只接受本机请求。', 403);
|
|
242
|
+
const meta = resolveMeta(targetWorkspace);
|
|
243
|
+
const stateDir = meta.rtInfo.stateDir;
|
|
244
|
+
const id = url.searchParams.get('id');
|
|
245
|
+
const sendJson = (status, data) => {
|
|
246
|
+
res.writeHead(status, {
|
|
247
|
+
'content-type': 'application/json; charset=utf-8',
|
|
248
|
+
'cache-control': 'no-store',
|
|
249
|
+
'x-content-type-options': 'nosniff',
|
|
250
|
+
});
|
|
251
|
+
res.end(JSON.stringify(data));
|
|
252
|
+
};
|
|
253
|
+
if (req.method === 'GET') {
|
|
254
|
+
if (id) {
|
|
255
|
+
const record = loadSessionRecord(stateDir, id);
|
|
256
|
+
if (!record) throw new DocumentError('未找到该历史会话。', 404);
|
|
257
|
+
sendJson(200, { session: record });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
sendJson(200, { sessions: listSessionRecords(stateDir, 30) });
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (req.method === 'DELETE') {
|
|
264
|
+
if (req.headers.origin !== 'http://' + host) throw new DocumentError('删除会话只接受本机同源页面请求。', 403);
|
|
265
|
+
if (!id) throw new DocumentError('缺少会话 id。', 400);
|
|
266
|
+
const active = sessions.get(id);
|
|
267
|
+
if (active) close(active);
|
|
268
|
+
const deleted = deleteSessionRecord(stateDir, id);
|
|
269
|
+
if (!deleted) throw new DocumentError('未找到该历史会话。', 404);
|
|
270
|
+
sendJson(200, { deleted: true });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
throw new DocumentError('会话接口仅支持 GET / DELETE。', 405);
|
|
274
|
+
}
|
|
275
|
+
|
|
140
276
|
async function handle(req, res, targetWorkspace = workspace) {
|
|
141
277
|
const host = req.headers.host || '';
|
|
142
278
|
if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
|
|
@@ -147,12 +283,14 @@ export function createAgentHandler({
|
|
|
147
283
|
}
|
|
148
284
|
const input = await readRequest(req);
|
|
149
285
|
let session = sessions.get(input.session);
|
|
150
|
-
if (input.action
|
|
286
|
+
if (input.action === 'cancel' || input.action === 'close') {
|
|
151
287
|
if (input.action === 'close') {
|
|
152
288
|
close(session || { key: input.session });
|
|
153
289
|
} else if (session?.running) {
|
|
154
290
|
session.cancelled = true;
|
|
155
|
-
if (session.
|
|
291
|
+
if (session.abortController) {
|
|
292
|
+
session.abortController.abort();
|
|
293
|
+
} else if (session.id && session.agent) {
|
|
156
294
|
session.agent.rpc.notify('session/cancel', { sessionId: session.id }).catch(error => close(session, error));
|
|
157
295
|
session.stopTimer ||= setTimeout(() => close(session, new Error('Agent 停止超时,会话已关闭。')), 5000);
|
|
158
296
|
} else close(session, new Error('已停止连接。'));
|
|
@@ -160,13 +298,44 @@ export function createAgentHandler({
|
|
|
160
298
|
res.writeHead(204).end();
|
|
161
299
|
return;
|
|
162
300
|
}
|
|
301
|
+
|
|
163
302
|
if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
|
|
164
303
|
if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
|
|
304
|
+
const meta = resolveMeta(targetWorkspace);
|
|
165
305
|
if (!session) {
|
|
166
306
|
if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
|
|
167
|
-
|
|
307
|
+
const saved = loadSessionRecord(meta.rtInfo.stateDir, input.session);
|
|
308
|
+
session = {
|
|
309
|
+
key: input.session,
|
|
310
|
+
workspace: targetWorkspace,
|
|
311
|
+
title: saved?.title || '',
|
|
312
|
+
persona: saved?.persona || meta.defaultPersona,
|
|
313
|
+
mode: saved?.mode || 'design',
|
|
314
|
+
history: Array.isArray(saved?.messages) ? saved.messages : [],
|
|
315
|
+
uiMessages: Array.isArray(saved?.uiMessages) ? saved.uiMessages : [],
|
|
316
|
+
pendingQuestion: saved?.pendingQuestion || null,
|
|
317
|
+
};
|
|
168
318
|
sessions.set(input.session, session);
|
|
169
319
|
}
|
|
320
|
+
|
|
321
|
+
let resumeToolResult = null;
|
|
322
|
+
if (input.action === 'answer') {
|
|
323
|
+
const pending = session.pendingQuestion;
|
|
324
|
+
if (!pending || pending.id !== input.questionId) {
|
|
325
|
+
throw new DocumentError('当前没有待确认的提问,或该提问已失效。', 409);
|
|
326
|
+
}
|
|
327
|
+
resumeToolResult = {
|
|
328
|
+
toolCallId: pending.toolCallId,
|
|
329
|
+
choiceId: input.choiceId || '',
|
|
330
|
+
answer: input.answer,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const useBuiltin = input.action === 'answer' || (input.action === 'prompt' && (
|
|
335
|
+
input.engine === 'builtin' ||
|
|
336
|
+
((input.engine || 'auto') === 'auto' && meta.activeEngine === 'builtin')
|
|
337
|
+
));
|
|
338
|
+
|
|
170
339
|
session.running = true;
|
|
171
340
|
session.cancelled = false;
|
|
172
341
|
clearTimeout(session.idle);
|
|
@@ -183,8 +352,154 @@ export function createAgentHandler({
|
|
|
183
352
|
const onDisconnect = () => { if (!res.writableEnded) close(session); };
|
|
184
353
|
res.on('close', onDisconnect);
|
|
185
354
|
const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
|
|
355
|
+
|
|
186
356
|
const run = async () => {
|
|
187
|
-
if (
|
|
357
|
+
if (useBuiltin) {
|
|
358
|
+
session.abortController = new AbortController();
|
|
359
|
+
// 若上一轮有未回答的 ask_user,但用户直接发起了新指令,补一条跳过回执避免协议报孤立 tool_call 错误
|
|
360
|
+
if (input.action === 'prompt' && session.pendingQuestion) {
|
|
361
|
+
session.history.push({
|
|
362
|
+
role: 'tool',
|
|
363
|
+
tool_call_id: session.pendingQuestion.toolCallId,
|
|
364
|
+
content: JSON.stringify({ answered: false, skipped: true, reason: '用户发起了新的指令' }),
|
|
365
|
+
});
|
|
366
|
+
for (let i = session.uiMessages.length - 1; i >= 0; i--) {
|
|
367
|
+
if (session.uiMessages[i]?.question?.id === session.pendingQuestion.id) {
|
|
368
|
+
session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: '(已跳过,发起新指令)' };
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
session.pendingQuestion = null;
|
|
373
|
+
}
|
|
374
|
+
const activeMode = input.mode || session.mode || 'general';
|
|
375
|
+
const activePersona = input.persona || session.persona || meta.defaultPersona;
|
|
376
|
+
let thinkingBuf = '';
|
|
377
|
+
let textBuf = '';
|
|
378
|
+
let changesBuf = [];
|
|
379
|
+
const emitBuiltin = ev => {
|
|
380
|
+
if (ev.type === 'thinking' && ev.text) thinkingBuf += ev.text;
|
|
381
|
+
else if (ev.type === 'text' && ev.text) textBuf += ev.text;
|
|
382
|
+
else if (ev.type === 'changes' && Array.isArray(ev.items)) changesBuf = ev.items;
|
|
383
|
+
emit(ev);
|
|
384
|
+
};
|
|
385
|
+
const result = await runVerticalAgent({
|
|
386
|
+
workspace: session.workspace,
|
|
387
|
+
stateDir: meta.rtInfo.stateDir,
|
|
388
|
+
workspaceService,
|
|
389
|
+
events,
|
|
390
|
+
config: meta.settings,
|
|
391
|
+
history: session.history,
|
|
392
|
+
resumeToolResult,
|
|
393
|
+
input,
|
|
394
|
+
mode: activeMode,
|
|
395
|
+
persona: activePersona,
|
|
396
|
+
emit: emitBuiltin,
|
|
397
|
+
signal: session.abortController.signal,
|
|
398
|
+
fetchImpl,
|
|
399
|
+
});
|
|
400
|
+
if (input.action === 'answer') {
|
|
401
|
+
for (let i = session.uiMessages.length - 1; i >= 0; i--) {
|
|
402
|
+
if (session.uiMessages[i]?.question?.id === input.questionId) {
|
|
403
|
+
session.uiMessages[i].question = { ...session.uiMessages[i].question, answered: input.answer };
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
session.uiMessages.push({ role: 'human', text: input.answer, isAnswer: true });
|
|
408
|
+
} else {
|
|
409
|
+
session.uiMessages.push({
|
|
410
|
+
role: 'human',
|
|
411
|
+
text: input.text,
|
|
412
|
+
canvas: input.canvas ? { file: input.canvas.file, selectionCount: input.canvas.selection.length } : null,
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
if (thinkingBuf || textBuf || changesBuf.length || result.pendingQuestion) {
|
|
416
|
+
session.uiMessages.push({
|
|
417
|
+
role: 'assistant',
|
|
418
|
+
thinking: thinkingBuf,
|
|
419
|
+
text: textBuf,
|
|
420
|
+
changes: changesBuf,
|
|
421
|
+
question: result.pendingQuestion || null,
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
session.history = Array.isArray(result.conversation) ? result.conversation : session.history;
|
|
425
|
+
session.pendingQuestion = result.pendingQuestion || null;
|
|
426
|
+
session.persona = activePersona;
|
|
427
|
+
session.mode = activeMode;
|
|
428
|
+
if (!session.title) session.title = (input.text || input.answer || '新对话').slice(0, 48);
|
|
429
|
+
saveSessionRecord(meta.rtInfo.stateDir, {
|
|
430
|
+
id: session.key,
|
|
431
|
+
title: session.title,
|
|
432
|
+
persona: session.persona,
|
|
433
|
+
mode: session.mode,
|
|
434
|
+
messages: session.history,
|
|
435
|
+
uiMessages: session.uiMessages,
|
|
436
|
+
pendingQuestion: session.pendingQuestion,
|
|
437
|
+
});
|
|
438
|
+
return { stopReason: result.stopReason };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (input.action === 'dispatch') {
|
|
442
|
+
const chosen = input.executorId
|
|
443
|
+
? meta.executors.find(item => item.id === input.executorId)
|
|
444
|
+
: meta.executors[0];
|
|
445
|
+
if (!chosen) throw new Error('找不到指定的 ACP 执行器插件:' + (input.executorId || '默认'));
|
|
446
|
+
const runRec = createRunRecord(meta.rtInfo.stateDir, {
|
|
447
|
+
kind: 'dispatch',
|
|
448
|
+
mode: 'implement',
|
|
449
|
+
executorId: chosen.id,
|
|
450
|
+
file: input.canvas?.file || '',
|
|
451
|
+
instruction: input.text || '按画布规格实施开发',
|
|
452
|
+
});
|
|
453
|
+
emit({ type: 'run', run: runRec });
|
|
454
|
+
emit({ type: 'status', text: `正在派发给执行器:${chosen.name}` });
|
|
455
|
+
events?.emit(session.workspace, 'agent.activity', {
|
|
456
|
+
file: input.canvas?.file || '',
|
|
457
|
+
action: 'dispatch',
|
|
458
|
+
kind: 'write',
|
|
459
|
+
nodes: input.canvas?.selection || [],
|
|
460
|
+
label: `ACP 派发开发中 · ${chosen.name}`,
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
// 如果当前会话绑定的不是这个执行器,重新建立对应执行器的 ACP 连接
|
|
464
|
+
if (session.agent && session.executorId !== chosen.id) {
|
|
465
|
+
session.agent.dispose();
|
|
466
|
+
session.agent = null;
|
|
467
|
+
session.id = null;
|
|
468
|
+
session.started = false;
|
|
469
|
+
}
|
|
470
|
+
session.executorId = chosen.id;
|
|
471
|
+
if (!session.agent) await connectAcp(session, chosen);
|
|
472
|
+
if (session.cancelled || sessions.get(session.key) !== session) {
|
|
473
|
+
updateRunRecord(meta.rtInfo.stateDir, runRec, { status: 'cancelled' });
|
|
474
|
+
return { stopReason: 'cancelled' };
|
|
475
|
+
}
|
|
476
|
+
emit({ type: 'status', text: `${chosen.name} 执行中(无需切换窗口)…` });
|
|
477
|
+
const prompt = buildDispatchPrompt({
|
|
478
|
+
workspace: session.workspace,
|
|
479
|
+
documentRoot: meta.rtInfo.documentRoot,
|
|
480
|
+
file: input.canvas?.file || '',
|
|
481
|
+
selection: input.canvas?.selection || [],
|
|
482
|
+
instruction: input.text,
|
|
483
|
+
mcpName: session.hasMcp ? mcpName() : '',
|
|
484
|
+
});
|
|
485
|
+
const response = await session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
|
|
486
|
+
const finished = updateRunRecord(meta.rtInfo.stateDir, runRec, {
|
|
487
|
+
status: session.cancelled ? 'cancelled' : 'completed',
|
|
488
|
+
summary: `执行器 ${chosen.name} 已完成(${response.stopReason})`,
|
|
489
|
+
});
|
|
490
|
+
emit({ type: 'run', run: finished });
|
|
491
|
+
events?.emit(session.workspace, 'agent.activity', {
|
|
492
|
+
file: input.canvas?.file || '',
|
|
493
|
+
action: 'dispatch.done',
|
|
494
|
+
kind: 'write',
|
|
495
|
+
nodes: input.canvas?.selection || [],
|
|
496
|
+
label: `${chosen.name} 开发完成 · 可执行 Diff 验收`,
|
|
497
|
+
});
|
|
498
|
+
return response;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// 默认 ACP 对话模式(完全兼容既有行为)
|
|
502
|
+
if (!session.agent) await connectAcp(session);
|
|
188
503
|
if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
|
|
189
504
|
emit({ type: 'status', text: '正在生成' });
|
|
190
505
|
const prompt = promptBlocks(session.workspace, input);
|
|
@@ -194,8 +509,9 @@ export function createAgentHandler({
|
|
|
194
509
|
}
|
|
195
510
|
return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
|
|
196
511
|
};
|
|
512
|
+
|
|
197
513
|
try {
|
|
198
|
-
emit({ type: 'status', text: session.agent ? '正在发送' : '正在连接 Agent' });
|
|
514
|
+
emit({ type: 'status', text: useBuiltin ? '正在启动 Clado 独立 Agent' : (session.agent ? '正在发送' : '正在连接 Agent') });
|
|
199
515
|
const result = await Promise.race([run(), abort]);
|
|
200
516
|
emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
|
|
201
517
|
} catch (error) {
|
|
@@ -204,11 +520,12 @@ export function createAgentHandler({
|
|
|
204
520
|
const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
|
|
205
521
|
emit({ type: 'error', text: message });
|
|
206
522
|
}
|
|
207
|
-
close(session, error);
|
|
523
|
+
if (!useBuiltin) close(session, error);
|
|
208
524
|
} finally {
|
|
209
525
|
clearTimeout(timer);
|
|
210
526
|
clearTimeout(session.stopTimer);
|
|
211
527
|
session.stopTimer = undefined;
|
|
528
|
+
session.abortController = undefined;
|
|
212
529
|
session.running = false;
|
|
213
530
|
session.emit = session.fail = undefined;
|
|
214
531
|
res.off('close', onDisconnect);
|
|
@@ -219,5 +536,5 @@ export function createAgentHandler({
|
|
|
219
536
|
}
|
|
220
537
|
}
|
|
221
538
|
}
|
|
222
|
-
return { handle, close: () => { for (const session of sessions.values()) close(session); } };
|
|
539
|
+
return { handle, handleMeta, handleSessions, close: () => { for (const session of sessions.values()) close(session); } };
|
|
223
540
|
}
|
|
@@ -138,10 +138,19 @@
|
|
|
138
138
|
if (deferredDisplay) { const next=deferredDisplay;deferredDisplay=null;window.dispatchEvent(new MessageEvent('message', { source:parent,data:next })); }
|
|
139
139
|
});
|
|
140
140
|
window.addEventListener('message', async event => {
|
|
141
|
-
if(event.source!==parent
|
|
141
|
+
if (event.source !== parent) return;
|
|
142
|
+
if (event.data?.type === 'clado-workspace:ai-touch') {
|
|
143
|
+
runtime.highlightActivity?.(event.data);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (event.data?.type === 'clado-workspace:focus-node') {
|
|
147
|
+
runtime.focusNodePath?.(event.data.node, event.data.label);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (event.data?.type !== 'clado-workspace:display') return;
|
|
142
151
|
if (runtime.isChainOpen?.()) { deferredDisplay=event.data;return; }
|
|
143
152
|
const {mode,theme,anchor}=event.data;
|
|
144
|
-
if(['doc','cards','mindmap'].includes(mode)) runtime.setMode(mode);
|
|
153
|
+
if(window.CladoViews ? window.CladoViews.has(mode) : ['doc','cards','mindmap'].includes(mode)) runtime.setMode(mode);
|
|
145
154
|
if(['light','dark'].includes(theme))runtime.setTheme(theme,false);
|
|
146
155
|
await settle();
|
|
147
156
|
if(anchor) { let title=anchor;try{title=decodeURIComponent(anchor);}catch{}runtime.focusTitle(title); }
|