cladogram 0.5.5-beta.9 → 0.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -79
- package/bin/clado.js +1 -1
- package/docs/release.md +7 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +928 -3131
- package/plugins/agent/style.css +404 -1511
- 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 +487 -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 +329 -1590
- 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
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clado Pi 1.x Bridge
|
|
3
|
+
*
|
|
4
|
+
* 极薄桥接层:把 Clado 的角色会话、画布快照回退、设计→交付单向交接
|
|
5
|
+
* 与 Pi 1.x 原生 createAgentSession / SessionManager / ModelRuntime 绑定。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import {
|
|
12
|
+
createAgentSession,
|
|
13
|
+
DefaultResourceLoader,
|
|
14
|
+
SessionManager,
|
|
15
|
+
SettingsManager,
|
|
16
|
+
} from '@earendil-works/pi-coding-agent';
|
|
17
|
+
import {
|
|
18
|
+
createCladoModelRuntime,
|
|
19
|
+
resolvePiAgentDir,
|
|
20
|
+
resolveRole,
|
|
21
|
+
} from './pi-config.js';
|
|
22
|
+
import { createCladoPiTools } from './clado-tools.js';
|
|
23
|
+
import { workspacePath } from '../workspace/documents.js';
|
|
24
|
+
|
|
25
|
+
export function safeSessionId(raw) {
|
|
26
|
+
const s = String(raw || '').trim().replace(/[^a-zA-Z0-9_-]/g, '');
|
|
27
|
+
return s.length >= 4 ? s.slice(0, 80) : ('role_' + randomUUID().replace(/-/g, '').slice(0, 12));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sessionsDir(stateDir) {
|
|
31
|
+
const dir = join(stateDir, 'sessions');
|
|
32
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
33
|
+
return dir;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function indexFile(stateDir) {
|
|
37
|
+
return join(sessionsDir(stateDir), 'index.json');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function readIndex(stateDir) {
|
|
41
|
+
const file = indexFile(stateDir);
|
|
42
|
+
if (!existsSync(file)) return [];
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
45
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
46
|
+
} catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function writeIndex(stateDir, list) {
|
|
52
|
+
writeFileSync(indexFile(stateDir), JSON.stringify(list, null, 2) + '\n', 'utf8');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir()) {
|
|
56
|
+
let list = readIndex(stateDir);
|
|
57
|
+
if (list.length > 0) return list;
|
|
58
|
+
const now = new Date().toISOString();
|
|
59
|
+
const defaults = ['architect', 'developer', 'tester'].map(roleId => {
|
|
60
|
+
const role = resolveRole(roleId, agentDir);
|
|
61
|
+
return {
|
|
62
|
+
id: 'role_' + role.id,
|
|
63
|
+
title: role.name,
|
|
64
|
+
roleId: role.id,
|
|
65
|
+
phase: role.phase,
|
|
66
|
+
tone: role.tone,
|
|
67
|
+
model: role.model || '',
|
|
68
|
+
archived: false,
|
|
69
|
+
status: 'idle',
|
|
70
|
+
summaryBadge: '',
|
|
71
|
+
createdAt: now,
|
|
72
|
+
updatedAt: now,
|
|
73
|
+
messages: [],
|
|
74
|
+
snapshots: [],
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
writeIndex(stateDir, defaults);
|
|
78
|
+
return defaults;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function listSessions(stateDir, { includeArchived = false, agentDir = resolvePiAgentDir() } = {}) {
|
|
82
|
+
const list = ensureDefaultSessions(stateDir, agentDir);
|
|
83
|
+
return includeArchived ? list : list.filter(s => !s.archived);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir()) {
|
|
87
|
+
const list = ensureDefaultSessions(stateDir, agentDir);
|
|
88
|
+
return list.find(s => s.id === id) || null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir()) {
|
|
92
|
+
const list = ensureDefaultSessions(stateDir, agentDir);
|
|
93
|
+
const id = safeSessionId(patch.id);
|
|
94
|
+
const idx = list.findIndex(s => s.id === id);
|
|
95
|
+
const role = resolveRole(patch.roleId || list[idx]?.roleId || 'architect', agentDir);
|
|
96
|
+
const now = new Date().toISOString();
|
|
97
|
+
const next = idx >= 0
|
|
98
|
+
? {
|
|
99
|
+
...list[idx],
|
|
100
|
+
...patch,
|
|
101
|
+
id,
|
|
102
|
+
roleId: role.id,
|
|
103
|
+
tone: patch.tone || list[idx].tone || role.tone,
|
|
104
|
+
phase: patch.phase || list[idx].phase || role.phase,
|
|
105
|
+
updatedAt: now,
|
|
106
|
+
}
|
|
107
|
+
: {
|
|
108
|
+
id,
|
|
109
|
+
title: String(patch.title || role.name).trim().slice(0, 60),
|
|
110
|
+
roleId: role.id,
|
|
111
|
+
phase: role.phase,
|
|
112
|
+
tone: role.tone,
|
|
113
|
+
model: String(patch.model || role.model || ''),
|
|
114
|
+
archived: false,
|
|
115
|
+
status: 'idle',
|
|
116
|
+
summaryBadge: '',
|
|
117
|
+
createdAt: now,
|
|
118
|
+
updatedAt: now,
|
|
119
|
+
messages: [],
|
|
120
|
+
snapshots: [],
|
|
121
|
+
};
|
|
122
|
+
if (idx >= 0) list[idx] = next;
|
|
123
|
+
else list.push(next);
|
|
124
|
+
writeIndex(stateDir, list);
|
|
125
|
+
return next;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function archiveSession(stateDir, id, archived = true, agentDir = resolvePiAgentDir()) {
|
|
129
|
+
const list = ensureDefaultSessions(stateDir, agentDir);
|
|
130
|
+
const item = list.find(s => s.id === id);
|
|
131
|
+
if (!item) return null;
|
|
132
|
+
item.archived = Boolean(archived);
|
|
133
|
+
item.updatedAt = new Date().toISOString();
|
|
134
|
+
writeIndex(stateDir, list);
|
|
135
|
+
return item;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
|
|
139
|
+
const list = ensureDefaultSessions(stateDir, agentDir);
|
|
140
|
+
const next = list.filter(s => s.id !== id);
|
|
141
|
+
writeIndex(stateDir, next);
|
|
142
|
+
const jsonl = join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl');
|
|
143
|
+
if (existsSync(jsonl)) {
|
|
144
|
+
try { rmSync(jsonl, { force: true }); } catch {}
|
|
145
|
+
}
|
|
146
|
+
return { deleted: next.length !== list.length, id };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function captureCanvasSnapshot(documentRoot, file) {
|
|
150
|
+
if (!documentRoot || !file) return null;
|
|
151
|
+
try {
|
|
152
|
+
const full = workspacePath(documentRoot, file, false);
|
|
153
|
+
if (!existsSync(full)) return null;
|
|
154
|
+
return {
|
|
155
|
+
id: 'snap_' + randomUUID().replace(/-/g, '').slice(0, 10),
|
|
156
|
+
file,
|
|
157
|
+
content: readFileSync(full, 'utf8'),
|
|
158
|
+
createdAt: new Date().toISOString(),
|
|
159
|
+
};
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function restoreCanvasSnapshot(documentRoot, stateDir, sessionId, snapshotId = '', events = null, workspace = '') {
|
|
166
|
+
const meta = getSessionMeta(stateDir, sessionId);
|
|
167
|
+
if (!meta || !Array.isArray(meta.snapshots) || !meta.snapshots.length) {
|
|
168
|
+
throw new Error('当前会话暂无可回退的画布快照。');
|
|
169
|
+
}
|
|
170
|
+
const snap = snapshotId
|
|
171
|
+
? meta.snapshots.find(s => s.id === snapshotId)
|
|
172
|
+
: meta.snapshots[meta.snapshots.length - 1];
|
|
173
|
+
if (!snap) throw new Error('找不到指定的画布快照。');
|
|
174
|
+
const full = workspacePath(documentRoot, snap.file, true);
|
|
175
|
+
writeFileSync(full, snap.content, 'utf8');
|
|
176
|
+
if (events && workspace) {
|
|
177
|
+
events.emit(workspace, 'doc.updated', { file: snap.file, action: 'rollback', label: '回退画布 ' + snap.file });
|
|
178
|
+
}
|
|
179
|
+
return { ok: true, file: snap.file, snapshotId: snap.id };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom }) {
|
|
183
|
+
const lines = [];
|
|
184
|
+
if (handoffFrom) {
|
|
185
|
+
lines.push(`[设计交付交接 · 来自「${handoffFrom}」]`);
|
|
186
|
+
}
|
|
187
|
+
if (canvas?.file) {
|
|
188
|
+
lines.push(`当前画布文件:${canvas.file}`);
|
|
189
|
+
if (Array.isArray(canvas.selection) && canvas.selection.length) {
|
|
190
|
+
const selStr = canvas.selection.map(pathArr => pathArr.join(' > ')).join(';');
|
|
191
|
+
lines.push(`用户选中的画布卡片:${selStr}`);
|
|
192
|
+
}
|
|
193
|
+
if (Array.isArray(canvas.objectSelection) && canvas.objectSelection.length) {
|
|
194
|
+
const objStr = canvas.objectSelection.map(o => `${o.title || o.id}(${o.kind})`).join(';');
|
|
195
|
+
lines.push(`用户选中的画布组件:${objStr}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (lines.length) {
|
|
199
|
+
return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${text}`;
|
|
200
|
+
}
|
|
201
|
+
return text;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function resolvePiModel(modelRuntime, settingsManager, requestedSpec) {
|
|
205
|
+
const parseSpec = spec => {
|
|
206
|
+
const clean = String(spec || '').trim();
|
|
207
|
+
if (!clean) return null;
|
|
208
|
+
if (clean.includes('/')) {
|
|
209
|
+
const idx = clean.indexOf('/');
|
|
210
|
+
return { provider: clean.slice(0, idx), modelId: clean.slice(idx + 1) };
|
|
211
|
+
}
|
|
212
|
+
return { provider: '', modelId: clean };
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const candidates = [];
|
|
216
|
+
if (requestedSpec) candidates.push(parseSpec(requestedSpec));
|
|
217
|
+
const defP = settingsManager.getDefaultProvider();
|
|
218
|
+
const defM = settingsManager.getDefaultModel();
|
|
219
|
+
if (defP && defM) candidates.push({ provider: defP, modelId: defM });
|
|
220
|
+
|
|
221
|
+
for (const c of candidates) {
|
|
222
|
+
if (!c) continue;
|
|
223
|
+
if (c.provider) {
|
|
224
|
+
const m = modelRuntime.getModel(c.provider, c.modelId);
|
|
225
|
+
if (m) return m;
|
|
226
|
+
} else {
|
|
227
|
+
const all = modelRuntime.getModels();
|
|
228
|
+
const found = all.find(m => m.id === c.modelId);
|
|
229
|
+
if (found) return found;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const avail = modelRuntime.getAvailableSnapshot();
|
|
234
|
+
if (avail.length > 0) return avail[0];
|
|
235
|
+
|
|
236
|
+
const allAvail = await modelRuntime.getAvailable();
|
|
237
|
+
if (allAvail.length > 0) return allAvail[0];
|
|
238
|
+
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function createPiBridge({
|
|
243
|
+
workspaceService = null,
|
|
244
|
+
events = null,
|
|
245
|
+
sessionFactory = null,
|
|
246
|
+
} = {}) {
|
|
247
|
+
const liveRuns = new Map();
|
|
248
|
+
|
|
249
|
+
async function runTurn({
|
|
250
|
+
workspace,
|
|
251
|
+
stateDir,
|
|
252
|
+
documentRoot,
|
|
253
|
+
sessionId,
|
|
254
|
+
roleId,
|
|
255
|
+
modelSpec,
|
|
256
|
+
text,
|
|
257
|
+
canvas,
|
|
258
|
+
handoffFrom = '',
|
|
259
|
+
emit,
|
|
260
|
+
}) {
|
|
261
|
+
const agentDir = resolvePiAgentDir();
|
|
262
|
+
const cleanId = safeSessionId(sessionId);
|
|
263
|
+
const meta = upsertSessionMeta(stateDir, {
|
|
264
|
+
id: cleanId,
|
|
265
|
+
...(roleId ? { roleId } : {}),
|
|
266
|
+
...(modelSpec ? { model: modelSpec } : {}),
|
|
267
|
+
status: 'running',
|
|
268
|
+
}, agentDir);
|
|
269
|
+
const role = resolveRole(meta.roleId, agentDir);
|
|
270
|
+
|
|
271
|
+
// Capture pre-turn canvas snapshot for 1-click rollback
|
|
272
|
+
const snap = captureCanvasSnapshot(documentRoot, canvas?.file);
|
|
273
|
+
if (snap) {
|
|
274
|
+
const nextSnaps = [...(meta.snapshots || []).slice(-11), snap];
|
|
275
|
+
upsertSessionMeta(stateDir, { id: cleanId, snapshots: nextSnaps }, agentDir);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const userMsg = {
|
|
279
|
+
id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
|
|
280
|
+
role: 'user',
|
|
281
|
+
text,
|
|
282
|
+
canvasFile: canvas?.file || '',
|
|
283
|
+
selection: canvas?.selection || [],
|
|
284
|
+
handoffFrom,
|
|
285
|
+
timestamp: new Date().toISOString(),
|
|
286
|
+
};
|
|
287
|
+
const nextMessages = [...(meta.messages || []).slice(-60), userMsg];
|
|
288
|
+
upsertSessionMeta(stateDir, { id: cleanId, messages: nextMessages }, agentDir);
|
|
289
|
+
|
|
290
|
+
const pendingQuestions = new Map();
|
|
291
|
+
const waitForUserAnswer = (questionId, signal) => new Promise((resolveAnswer, rejectAnswer) => {
|
|
292
|
+
const onAbort = () => {
|
|
293
|
+
pendingQuestions.delete(questionId);
|
|
294
|
+
rejectAnswer(new Error('已取消等待确认'));
|
|
295
|
+
};
|
|
296
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
297
|
+
pendingQuestions.set(questionId, {
|
|
298
|
+
resolve(ans) {
|
|
299
|
+
signal?.removeEventListener('abort', onAbort);
|
|
300
|
+
pendingQuestions.delete(questionId);
|
|
301
|
+
resolveAnswer(ans);
|
|
302
|
+
},
|
|
303
|
+
reject(err) {
|
|
304
|
+
signal?.removeEventListener('abort', onAbort);
|
|
305
|
+
pendingQuestions.delete(questionId);
|
|
306
|
+
rejectAnswer(err);
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const cladoTools = createCladoPiTools({
|
|
312
|
+
workspace,
|
|
313
|
+
stateDir,
|
|
314
|
+
workspaceService,
|
|
315
|
+
events,
|
|
316
|
+
emit,
|
|
317
|
+
waitForUserAnswer,
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
let assistantText = '';
|
|
321
|
+
const toolLog = [];
|
|
322
|
+
let session = null;
|
|
323
|
+
let unsub = null;
|
|
324
|
+
|
|
325
|
+
const runState = {
|
|
326
|
+
sessionId: cleanId,
|
|
327
|
+
answer(questionId, answerText) {
|
|
328
|
+
const waiter = pendingQuestions.get(questionId);
|
|
329
|
+
if (!waiter) return false;
|
|
330
|
+
waiter.resolve(answerText);
|
|
331
|
+
return true;
|
|
332
|
+
},
|
|
333
|
+
async steer(steerText) {
|
|
334
|
+
if (session?.steer) {
|
|
335
|
+
await session.steer(steerText);
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
return false;
|
|
339
|
+
},
|
|
340
|
+
async abort() {
|
|
341
|
+
for (const w of pendingQuestions.values()) w.reject(new Error('用户已中止'));
|
|
342
|
+
pendingQuestions.clear();
|
|
343
|
+
if (session?.abort) await session.abort();
|
|
344
|
+
},
|
|
345
|
+
};
|
|
346
|
+
liveRuns.set(`${workspace}::${cleanId}`, runState);
|
|
347
|
+
|
|
348
|
+
try {
|
|
349
|
+
emit({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
|
|
350
|
+
|
|
351
|
+
if (sessionFactory) {
|
|
352
|
+
// Test injection hook
|
|
353
|
+
const result = await sessionFactory({
|
|
354
|
+
workspace, stateDir, documentRoot, sessionId: cleanId, role, text, canvas, cladoTools, emit, waitForUserAnswer,
|
|
355
|
+
});
|
|
356
|
+
assistantText = String(result?.text || '');
|
|
357
|
+
} else {
|
|
358
|
+
const sm = SettingsManager.create(workspace, agentDir);
|
|
359
|
+
const mr = await createCladoModelRuntime(agentDir);
|
|
360
|
+
const chosenModel = await resolvePiModel(mr, sm, modelSpec || meta.model);
|
|
361
|
+
if (!chosenModel) {
|
|
362
|
+
throw new Error('尚未配置可用模型。请点击顶部「设置 → 模型与供应商」填写 API Key 或本地 Ollama 地址。');
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const loader = new DefaultResourceLoader({
|
|
366
|
+
cwd: workspace,
|
|
367
|
+
agentDir,
|
|
368
|
+
settingsManager: sm,
|
|
369
|
+
noThemes: true,
|
|
370
|
+
packageCommandOutput: 'capture',
|
|
371
|
+
appendSystemPrompt: [
|
|
372
|
+
role.systemPrompt,
|
|
373
|
+
'工作区规范:你可以通过 clado_* 工具读写空间画布,也可以直接使用 read/edit/write/bash 工具分析或修改代码。无需向用户弹窗请求命令权限。',
|
|
374
|
+
],
|
|
375
|
+
});
|
|
376
|
+
await loader.reload();
|
|
377
|
+
|
|
378
|
+
const jsonlFile = join(sessionsDir(stateDir), cleanId + '.jsonl');
|
|
379
|
+
const sessionManager = existsSync(jsonlFile)
|
|
380
|
+
? SessionManager.open(jsonlFile)
|
|
381
|
+
: SessionManager.create(workspace, sessionsDir(stateDir));
|
|
382
|
+
|
|
383
|
+
const created = await createAgentSession({
|
|
384
|
+
cwd: workspace,
|
|
385
|
+
agentDir,
|
|
386
|
+
modelRuntime: mr,
|
|
387
|
+
model: chosenModel,
|
|
388
|
+
settingsManager: sm,
|
|
389
|
+
resourceLoader: loader,
|
|
390
|
+
sessionManager,
|
|
391
|
+
customTools: cladoTools,
|
|
392
|
+
});
|
|
393
|
+
session = created.session;
|
|
394
|
+
|
|
395
|
+
emit({
|
|
396
|
+
type: 'model',
|
|
397
|
+
provider: chosenModel.provider,
|
|
398
|
+
model: chosenModel.id,
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
unsub = session.subscribe(ev => {
|
|
402
|
+
if (ev.type === 'message_update') {
|
|
403
|
+
const ae = ev.assistantMessageEvent;
|
|
404
|
+
if (ae?.type === 'text_delta' && ae.delta) {
|
|
405
|
+
assistantText += ae.delta;
|
|
406
|
+
emit({ type: 'text', text: ae.delta });
|
|
407
|
+
} else if (ae?.type === 'thinking_delta' && ae.delta) {
|
|
408
|
+
emit({ type: 'thinking', text: ae.delta });
|
|
409
|
+
}
|
|
410
|
+
} else if (ev.type === 'tool_execution_start') {
|
|
411
|
+
const entry = { id: ev.toolCallId, name: ev.toolName, status: 'running' };
|
|
412
|
+
toolLog.push(entry);
|
|
413
|
+
emit({ type: 'tool', id: ev.toolCallId, name: ev.toolName, title: ev.toolName, status: 'running' });
|
|
414
|
+
} else if (ev.type === 'tool_execution_end') {
|
|
415
|
+
const existing = toolLog.find(t => t.id === ev.toolCallId);
|
|
416
|
+
if (existing) existing.status = ev.isError ? 'failed' : 'completed';
|
|
417
|
+
emit({
|
|
418
|
+
type: 'tool',
|
|
419
|
+
id: ev.toolCallId,
|
|
420
|
+
name: ev.toolName,
|
|
421
|
+
title: ev.toolName,
|
|
422
|
+
status: ev.isError ? 'failed' : 'completed',
|
|
423
|
+
});
|
|
424
|
+
} else if (ev.type === 'compaction_start') {
|
|
425
|
+
emit({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
|
|
426
|
+
} else if (ev.type === 'auto_retry_start') {
|
|
427
|
+
emit({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
|
|
432
|
+
await session.prompt(promptText);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const assistantMsg = {
|
|
436
|
+
id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
|
|
437
|
+
role: 'assistant',
|
|
438
|
+
text: assistantText,
|
|
439
|
+
tools: toolLog,
|
|
440
|
+
snapshotId: snap?.id || '',
|
|
441
|
+
timestamp: new Date().toISOString(),
|
|
442
|
+
};
|
|
443
|
+
const curMeta = getSessionMeta(stateDir, cleanId, agentDir);
|
|
444
|
+
const badge = toolLog.length ? `${toolLog.length} tools` : '';
|
|
445
|
+
upsertSessionMeta(stateDir, {
|
|
446
|
+
id: cleanId,
|
|
447
|
+
status: 'idle',
|
|
448
|
+
summaryBadge: badge || curMeta?.summaryBadge || '',
|
|
449
|
+
messages: [...(curMeta?.messages || nextMessages), assistantMsg].slice(-80),
|
|
450
|
+
}, agentDir);
|
|
451
|
+
|
|
452
|
+
emit({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '' });
|
|
453
|
+
} catch (err) {
|
|
454
|
+
upsertSessionMeta(stateDir, { id: cleanId, status: 'idle' }, agentDir);
|
|
455
|
+
emit({ type: 'error', message: err?.message || 'Pi 执行失败' });
|
|
456
|
+
} finally {
|
|
457
|
+
liveRuns.delete(`${workspace}::${cleanId}`);
|
|
458
|
+
try { unsub?.(); } catch {}
|
|
459
|
+
try { session?.dispose?.(); } catch {}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
return {
|
|
464
|
+
runTurn,
|
|
465
|
+
answer(workspace, sessionId, questionId, answerText) {
|
|
466
|
+
const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
|
|
467
|
+
return run ? run.answer(questionId, answerText) : false;
|
|
468
|
+
},
|
|
469
|
+
async steer(workspace, sessionId, text) {
|
|
470
|
+
const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
|
|
471
|
+
return run ? run.steer(text) : false;
|
|
472
|
+
},
|
|
473
|
+
async cancel(workspace, sessionId) {
|
|
474
|
+
const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
|
|
475
|
+
if (run) {
|
|
476
|
+
await run.abort();
|
|
477
|
+
return true;
|
|
478
|
+
}
|
|
479
|
+
return false;
|
|
480
|
+
},
|
|
481
|
+
async closeAll() {
|
|
482
|
+
const all = [...liveRuns.values()];
|
|
483
|
+
liveRuns.clear();
|
|
484
|
+
await Promise.allSettled(all.map(r => r.abort()));
|
|
485
|
+
},
|
|
486
|
+
};
|
|
487
|
+
}
|