cladogram 0.6.0-beta.1 → 0.6.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -1,30 +1,40 @@
1
1
  /**
2
2
  * Clado Pi 1.x Bridge
3
3
  *
4
- * 极薄桥接层:把 Clado 的角色会话、画布快照回退、设计→交付单向交接
5
- * 与 Pi 1.x 原生 createAgentSession / SessionManager / ModelRuntime 绑定。
4
+ * 极薄桥接层:把 Clado 的多角色多会话管理、Pi 原生 JSONL 持久化、
5
+ * 画布快照回退、中断保留上下文与设计→交付单向交接绑定在一起。
6
6
  */
7
7
 
8
8
  import { randomUUID } from 'node:crypto';
9
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
- import { join } from 'node:path';
9
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
10
+ import { basename, dirname, extname, join, relative, resolve } from 'node:path';
11
11
  import {
12
12
  createAgentSession,
13
+ createCodemodeExtension,
14
+ createMcpExtension,
15
+ createToolSearchExtension,
13
16
  DefaultResourceLoader,
14
17
  SessionManager,
15
18
  SettingsManager,
16
19
  } from '@earendil-works/pi-coding-agent';
17
20
  import {
21
+ buildMergedPiMcpConfig,
18
22
  createCladoModelRuntime,
23
+ listPiMcpServers,
24
+ readCladoPlatformContext,
25
+ readMemoryBundle,
26
+ readPluginParams,
27
+ readRuntimeSettings,
19
28
  resolvePiAgentDir,
20
29
  resolveRole,
21
30
  } from './pi-config.js';
31
+ import { createCladoGuardAndHooksExtension } from './pi-hooks-perms.js';
22
32
  import { createCladoPiTools } from './clado-tools.js';
23
33
  import { workspacePath } from '../workspace/documents.js';
24
34
 
25
35
  export function safeSessionId(raw) {
26
36
  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));
37
+ return s.length >= 4 ? s.slice(0, 80) : ('sess_' + randomUUID().replace(/-/g, '').slice(0, 12));
28
38
  }
29
39
 
30
40
  function sessionsDir(stateDir) {
@@ -37,6 +47,74 @@ function indexFile(stateDir) {
37
47
  return join(sessionsDir(stateDir), 'index.json');
38
48
  }
39
49
 
50
+ function sessionMessagesFile(stateDir, id) {
51
+ return join(sessionsDir(stateDir), safeSessionId(id) + '.messages.json');
52
+ }
53
+
54
+ function summarizeMessagePreview(msgs) {
55
+ if (!Array.isArray(msgs) || !msgs.length) return '';
56
+ const last = msgs[msgs.length - 1];
57
+ const raw = String(last?.text || '').replace(/\s+/g, ' ').trim();
58
+ return raw.slice(0, 100);
59
+ }
60
+
61
+ export function readSessionMessages(stateDir, id, inlineFallback = null) {
62
+ const file = sessionMessagesFile(stateDir, id);
63
+ if (existsSync(file)) {
64
+ try {
65
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
66
+ if (Array.isArray(parsed)) return parsed;
67
+ } catch {}
68
+ }
69
+ return Array.isArray(inlineFallback) ? inlineFallback : [];
70
+ }
71
+
72
+ function writeSessionMessages(stateDir, id, messages) {
73
+ const clean = Array.isArray(messages) ? messages : [];
74
+ writeFileSync(sessionMessagesFile(stateDir, id), JSON.stringify(clean, null, 2) + '\n', 'utf8');
75
+ return clean;
76
+ }
77
+
78
+ export function readSessionMessagesPage(stateDir, id, { limit = 30, before = null, inlineFallback = null } = {}) {
79
+ const all = readSessionMessages(stateDir, id, inlineFallback);
80
+ const totalMessages = all.length;
81
+ const maxLimit = Math.max(1, Math.min(200, Math.round(Number(limit) || 30)));
82
+ const end = (before !== null && before !== undefined && Number.isFinite(Number(before)))
83
+ ? Math.max(0, Math.min(totalMessages, Math.floor(Number(before))))
84
+ : totalMessages;
85
+ const start = Math.max(0, end - maxLimit);
86
+ return {
87
+ messages: all.slice(start, end),
88
+ totalMessages,
89
+ oldestIndex: start,
90
+ endIndex: end,
91
+ hasMoreBefore: start > 0,
92
+ };
93
+ }
94
+
95
+ function hydrateSessionView(stateDir, meta, { messageLimit = 30, includeMessages = true } = {}) {
96
+ if (!meta) return null;
97
+ if (!includeMessages) {
98
+ const { messages: _omit, ...rest } = meta;
99
+ return {
100
+ ...rest,
101
+ messageCount: typeof meta.messageCount === 'number' ? meta.messageCount : readSessionMessages(stateDir, meta.id, meta.messages).length,
102
+ };
103
+ }
104
+ const page = readSessionMessagesPage(stateDir, meta.id, {
105
+ limit: messageLimit,
106
+ inlineFallback: meta.messages,
107
+ });
108
+ return {
109
+ ...meta,
110
+ messages: page.messages,
111
+ messageCount: page.totalMessages,
112
+ totalMessages: page.totalMessages,
113
+ oldestIndex: page.oldestIndex,
114
+ hasMoreBefore: page.hasMoreBefore,
115
+ };
116
+ }
117
+
40
118
  function readIndex(stateDir) {
41
119
  const file = indexFile(stateDir);
42
120
  if (!existsSync(file)) return [];
@@ -49,12 +127,32 @@ function readIndex(stateDir) {
49
127
  }
50
128
 
51
129
  function writeIndex(stateDir, list) {
52
- writeFileSync(indexFile(stateDir), JSON.stringify(list, null, 2) + '\n', 'utf8');
130
+ const slim = list.map(item => {
131
+ const { messages: _inline, ...rest } = item;
132
+ return rest;
133
+ });
134
+ writeFileSync(indexFile(stateDir), JSON.stringify(slim, null, 2) + '\n', 'utf8');
53
135
  }
54
136
 
55
137
  export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir()) {
56
138
  let list = readIndex(stateDir);
57
- if (list.length > 0) return list;
139
+ if (list.length > 0) {
140
+ // One-time transparent migration if legacy inline messages exist inside index.json
141
+ let migrated = false;
142
+ for (const item of list) {
143
+ if (Array.isArray(item.messages) && item.messages.length > 0) {
144
+ if (!existsSync(sessionMessagesFile(stateDir, item.id))) {
145
+ writeSessionMessages(stateDir, item.id, item.messages);
146
+ }
147
+ item.messageCount = item.messages.length;
148
+ item.lastMessagePreview = item.lastMessagePreview || summarizeMessagePreview(item.messages);
149
+ delete item.messages;
150
+ migrated = true;
151
+ }
152
+ }
153
+ if (migrated) writeIndex(stateDir, list);
154
+ return list;
155
+ }
58
156
  const now = new Date().toISOString();
59
157
  const defaults = ['architect', 'developer', 'tester'].map(roleId => {
60
158
  const role = resolveRole(roleId, agentDir);
@@ -65,12 +163,14 @@ export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir())
65
163
  phase: role.phase,
66
164
  tone: role.tone,
67
165
  model: role.model || '',
166
+ piSessionFile: '',
68
167
  archived: false,
69
168
  status: 'idle',
70
169
  summaryBadge: '',
170
+ messageCount: 0,
171
+ lastMessagePreview: '',
71
172
  createdAt: now,
72
173
  updatedAt: now,
73
- messages: [],
74
174
  snapshots: [],
75
175
  };
76
176
  });
@@ -78,30 +178,71 @@ export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir())
78
178
  return defaults;
79
179
  }
80
180
 
81
- export function listSessions(stateDir, { includeArchived = false, agentDir = resolvePiAgentDir() } = {}) {
181
+ export function listSessions(stateDir, { includeArchived = false, includeMessages = true, messageLimit = 30, sinceMinutes = 0, agentDir = resolvePiAgentDir() } = {}) {
82
182
  const list = ensureDefaultSessions(stateDir, agentDir);
83
- return includeArchived ? list : list.filter(s => !s.archived);
183
+ const cutoffMs = (typeof sinceMinutes === 'number' && sinceMinutes > 0)
184
+ ? (Date.now() - sinceMinutes * 60_000)
185
+ : 0;
186
+ return list
187
+ .filter(s => includeArchived || !s.archived)
188
+ .filter(s => {
189
+ if (!cutoffMs) return true;
190
+ const uMs = s.updatedAt ? Date.parse(s.updatedAt) : 0;
191
+ const count = typeof s.messageCount === 'number' ? s.messageCount : readSessionMessages(stateDir, s.id).length;
192
+ return count > 0 && uMs >= cutoffMs;
193
+ })
194
+ .map(s => hydrateSessionView(stateDir, s, { includeMessages, messageLimit }));
84
195
  }
85
196
 
86
- export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir()) {
197
+ export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir(), { messageLimit = 30, includeAll = false } = {}) {
87
198
  const list = ensureDefaultSessions(stateDir, agentDir);
88
- return list.find(s => s.id === id) || null;
199
+ const found = list.find(s => s.id === id) || null;
200
+ if (!found) return null;
201
+ if (includeAll) {
202
+ const all = readSessionMessages(stateDir, found.id, found.messages);
203
+ return {
204
+ ...found,
205
+ messages: all,
206
+ messageCount: all.length,
207
+ totalMessages: all.length,
208
+ oldestIndex: 0,
209
+ hasMoreBefore: false,
210
+ };
211
+ }
212
+ return hydrateSessionView(stateDir, found, { includeMessages: true, messageLimit });
89
213
  }
90
214
 
91
- export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir()) {
215
+ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(), options = {}) {
92
216
  const list = ensureDefaultSessions(stateDir, agentDir);
93
- const id = safeSessionId(patch.id);
217
+ const id = patch.id ? safeSessionId(patch.id) : ('sess_' + randomUUID().replace(/-/g, '').slice(0, 12));
94
218
  const idx = list.findIndex(s => s.id === id);
95
- const role = resolveRole(patch.roleId || list[idx]?.roleId || 'architect', agentDir);
219
+ const ws = options.workspace || patch.workspace || (stateDir && basename(stateDir) === '.clado' ? dirname(stateDir) : '');
220
+ const strictFlag = Boolean((options.strictRole ?? patch.strictRole) && patch.roleId);
221
+ const role = resolveRole(patch.roleId || list[idx]?.roleId || 'architect', agentDir, {
222
+ workspace: ws,
223
+ strict: strictFlag,
224
+ });
96
225
  const now = new Date().toISOString();
226
+
227
+ let messageCount = idx >= 0 ? (list[idx].messageCount ?? readSessionMessages(stateDir, id).length) : 0;
228
+ let lastMessagePreview = idx >= 0 ? (list[idx].lastMessagePreview || '') : '';
229
+ if (Array.isArray(patch.messages)) {
230
+ writeSessionMessages(stateDir, id, patch.messages);
231
+ messageCount = patch.messages.length;
232
+ lastMessagePreview = summarizeMessagePreview(patch.messages);
233
+ }
234
+ const { messages: _omitMessages, ...patchRest } = patch;
235
+
97
236
  const next = idx >= 0
98
237
  ? {
99
238
  ...list[idx],
100
- ...patch,
239
+ ...patchRest,
101
240
  id,
102
241
  roleId: role.id,
103
242
  tone: patch.tone || list[idx].tone || role.tone,
104
243
  phase: patch.phase || list[idx].phase || role.phase,
244
+ messageCount,
245
+ lastMessagePreview,
105
246
  updatedAt: now,
106
247
  }
107
248
  : {
@@ -111,18 +252,32 @@ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(
111
252
  phase: role.phase,
112
253
  tone: role.tone,
113
254
  model: String(patch.model || role.model || ''),
255
+ piSessionFile: String(patch.piSessionFile || ''),
114
256
  archived: false,
115
257
  status: 'idle',
116
258
  summaryBadge: '',
259
+ messageCount,
260
+ lastMessagePreview,
117
261
  createdAt: now,
118
262
  updatedAt: now,
119
- messages: [],
120
263
  snapshots: [],
121
264
  };
122
265
  if (idx >= 0) list[idx] = next;
123
266
  else list.push(next);
124
267
  writeIndex(stateDir, list);
125
- return next;
268
+ return hydrateSessionView(stateDir, next, { includeMessages: true, messageLimit: 30 });
269
+ }
270
+
271
+ export function renameSession(stateDir, id, title, agentDir = resolvePiAgentDir()) {
272
+ const cleanTitle = String(title || '').trim().slice(0, 60);
273
+ if (!cleanTitle) throw new Error('会话名称不能为空。');
274
+ const list = ensureDefaultSessions(stateDir, agentDir);
275
+ const item = list.find(s => s.id === id);
276
+ if (!item) throw new Error('找不到该会话。');
277
+ item.title = cleanTitle;
278
+ item.updatedAt = new Date().toISOString();
279
+ writeIndex(stateDir, list);
280
+ return hydrateSessionView(stateDir, item, { includeMessages: true, messageLimit: 30 });
126
281
  }
127
282
 
128
283
  export function archiveSession(stateDir, id, archived = true, agentDir = resolvePiAgentDir()) {
@@ -132,20 +287,92 @@ export function archiveSession(stateDir, id, archived = true, agentDir = resolve
132
287
  item.archived = Boolean(archived);
133
288
  item.updatedAt = new Date().toISOString();
134
289
  writeIndex(stateDir, list);
135
- return item;
290
+ return hydrateSessionView(stateDir, item, { includeMessages: true, messageLimit: 30 });
136
291
  }
137
292
 
138
293
  export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
139
294
  const list = ensureDefaultSessions(stateDir, agentDir);
295
+ const target = list.find(s => s.id === id);
140
296
  const next = list.filter(s => s.id !== id);
141
297
  writeIndex(stateDir, next);
142
- const jsonl = join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl');
143
- if (existsSync(jsonl)) {
144
- try { rmSync(jsonl, { force: true }); } catch {}
298
+ for (const candidate of [
299
+ target?.piSessionFile,
300
+ join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl'),
301
+ sessionMessagesFile(stateDir, id),
302
+ ]) {
303
+ if (candidate && existsSync(candidate)) {
304
+ try { rmSync(candidate, { force: true }); } catch {}
305
+ }
145
306
  }
146
307
  return { deleted: next.length !== list.length, id };
147
308
  }
148
309
 
310
+ export function clearArchivedSessions(stateDir, agentDir = resolvePiAgentDir()) {
311
+ const list = ensureDefaultSessions(stateDir, agentDir);
312
+ const archived = list.filter(s => s.archived);
313
+ let removed = 0;
314
+ for (const s of archived) {
315
+ const r = deleteSession(stateDir, s.id, agentDir);
316
+ if (r.deleted) removed++;
317
+ }
318
+ return { ok: true, removed };
319
+ }
320
+
321
+ export function exportSessionTranscript(stateDir, id, format = 'md', agentDir = resolvePiAgentDir()) {
322
+ const session = getSessionMeta(stateDir, id, agentDir, { includeAll: true });
323
+ if (!session) throw new Error('找不到目标会话。');
324
+ const msgs = Array.isArray(session.messages) ? session.messages : [];
325
+ if (format === 'json') {
326
+ return {
327
+ ok: true,
328
+ format: 'json',
329
+ fileName: `${safeSessionId(session.id)}.json`,
330
+ content: JSON.stringify({
331
+ id: session.id,
332
+ title: session.title,
333
+ roleId: session.roleId,
334
+ model: session.model || '',
335
+ createdAt: session.createdAt,
336
+ updatedAt: session.updatedAt,
337
+ archived: Boolean(session.archived),
338
+ messages: msgs,
339
+ }, null, 2) + '\n',
340
+ };
341
+ }
342
+ const lines = [
343
+ `# ${session.title || session.id}`,
344
+ '',
345
+ `- 会话 ID: \`${session.id}\``,
346
+ `- 角色: \`${session.roleId}\``,
347
+ ...(session.model ? [`- 模型: \`${session.model}\``] : []),
348
+ `- 导出时间: ${new Date().toISOString()}`,
349
+ '',
350
+ '---',
351
+ '',
352
+ ];
353
+ for (const m of msgs) {
354
+ const who = m.role === 'user' ? '## User' : m.role === 'system' ? '## System' : '## Assistant';
355
+ lines.push(who, '');
356
+ if (m.thinking) {
357
+ lines.push('<details><summary>Thinking</summary>', '', m.thinking, '', '</details>', '');
358
+ }
359
+ if (m.text) lines.push(String(m.text), '');
360
+ if (Array.isArray(m.tools) && m.tools.length) {
361
+ lines.push('**Tools:**', '');
362
+ for (const t of m.tools) {
363
+ lines.push(`- \`${t.name}\` (${t.status || 'done'})${t.summary ? ': ' + String(t.summary).slice(0, 160) : ''}`);
364
+ }
365
+ lines.push('');
366
+ }
367
+ }
368
+ return {
369
+ ok: true,
370
+ format: 'md',
371
+ fileName: `${safeSessionId(session.id)}.md`,
372
+ content: lines.join('\n'),
373
+ };
374
+ }
375
+
149
376
  export function captureCanvasSnapshot(documentRoot, file) {
150
377
  if (!documentRoot || !file) return null;
151
378
  try {
@@ -179,11 +406,160 @@ export function restoreCanvasSnapshot(documentRoot, stateDir, sessionId, snapsho
179
406
  return { ok: true, file: snap.file, snapshotId: snap.id };
180
407
  }
181
408
 
182
- export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom }) {
409
+ const BUILTIN_SLASH_PROMPTS = {
410
+ arch: '请分析当前工作区源码或目标模块,梳理清晰的架构边界、核心调用链与数据契约,并直接在 Clado 画布中绘制或更新结构化卡片与单向 DAG 连线。',
411
+ review: '请对当前画布、选中卡片或关联代码进行深度工程评审:逐项核查边界条件、数据一致性、并发安全、异常兜底与可维护性,给出具体可落地的改进建议。',
412
+ test: '请基于当前画布链路与源码边界,系统设计单元测试、边界条件、异常分支与回归测试矩阵;如已有代码实现,直接补充可运行测试并验证结果。',
413
+ diff: '请检查当前工作区 Git Diff 与改动源码,逐项对照画布契约验收实现完整性与潜在回归风险,并同步更新画布卡片状态。',
414
+ svg: '请为当前方案或需求设计一张清晰美观、结构分明的矢量架构图/流程图/时序图,在画布卡片中使用标准 ```svg 代码块(包含完整 viewBox 与 xmlns="http://www.w3.org/2000/svg")呈现。',
415
+ ui: '请为当前需求设计高保真交互式界面原型,在画布卡片中使用标准 ```ui 代码块呈现清晰布局、交互态与关键状态切换。',
416
+ };
417
+
418
+ function stripFrontmatter(raw) {
419
+ const s = String(raw || '').replace(/\r\n?/g, '\n');
420
+ const m = s.match(/^---\n[\s\S]*?\n---\n?/);
421
+ return (m ? s.slice(m[0].length) : s).trim();
422
+ }
423
+
424
+ function substitutePromptArgs(template, rawArgs) {
425
+ const argsStr = String(rawArgs || '').trim();
426
+ const tokens = argsStr ? (argsStr.match(/"[^"]*"|'[^']*'|\S+/g) || []).map(t => t.replace(/^["']|["']$/g, '')) : [];
427
+ let out = String(template || '');
428
+ let usedPlaceholder = false;
429
+ out = out.replace(/\{\{\s*args\s*\}\}|\$ARGUMENTS|\$@/g, () => {
430
+ usedPlaceholder = true;
431
+ return argsStr;
432
+ });
433
+ out = out.replace(/\$(\d+)/g, (_, idxStr) => {
434
+ usedPlaceholder = true;
435
+ const idx = Number(idxStr) - 1;
436
+ return tokens[idx] ?? '';
437
+ });
438
+ if (!usedPlaceholder && argsStr) {
439
+ out = out + '\n\n补充要求:' + argsStr;
440
+ }
441
+ return out.trim();
442
+ }
443
+
444
+ export function expandSlashPrompt(rawText, { workspace = '', agentDir = resolvePiAgentDir() } = {}) {
445
+ const clean = String(rawText || '').trim();
446
+ const match = clean.match(/^\/([a-zA-Z0-9_:-]+)(?:\s+([\s\S]*))?$/);
447
+ if (!match) return { expanded: false, text: clean, command: '' };
448
+ const cmd = match[1].toLowerCase();
449
+ const restArgs = (match[2] || '').trim();
450
+
451
+ // 1. /skill:<name> -> locate SKILL.md and instruct Pi to load/apply it
452
+ if (cmd.startsWith('skill:')) {
453
+ const skillName = cmd.slice('skill:'.length).trim();
454
+ if (!skillName || skillName.includes('..') || skillName.includes('/')) {
455
+ return { expanded: false, text: clean, command: '' };
456
+ }
457
+ const candidates = [
458
+ workspace ? join(workspace, '.pi', 'skills', skillName, 'SKILL.md') : '',
459
+ workspace ? join(workspace, '.clado', 'skills', skillName, 'SKILL.md') : '',
460
+ join(agentDir, 'skills', skillName, 'SKILL.md'),
461
+ ].filter(Boolean);
462
+ const found = candidates.find(p => existsSync(p));
463
+ const guide = found
464
+ ? `请严格按照技能 \`${skillName}\` 的指南执行(技能文件:${found},可先 read 该文件获取完整规范)。`
465
+ : `请优先加载并遵循名为 \`${skillName}\` 的技能规范来执行本任务。`;
466
+ return {
467
+ expanded: true,
468
+ command: '/' + cmd,
469
+ text: restArgs ? `${guide}\n\n用户任务:${restArgs}` : guide,
470
+ };
471
+ }
472
+
473
+ // 2. Project / User Pi prompt templates (.pi/prompts/<cmd>.md or ~/.pi/agent/prompts/<cmd>.md)
474
+ if (!cmd.includes('..') && !cmd.includes('/') && !cmd.includes(':')) {
475
+ const promptCandidates = [
476
+ workspace ? join(workspace, '.pi', 'prompts', cmd + '.md') : '',
477
+ join(agentDir, 'prompts', cmd + '.md'),
478
+ ].filter(Boolean);
479
+ const promptFile = promptCandidates.find(p => existsSync(p));
480
+ if (promptFile) {
481
+ try {
482
+ const body = stripFrontmatter(readFileSync(promptFile, 'utf8'));
483
+ if (body) {
484
+ return {
485
+ expanded: true,
486
+ command: '/' + cmd,
487
+ text: substitutePromptArgs(body, restArgs),
488
+ };
489
+ }
490
+ } catch {}
491
+ }
492
+ }
493
+
494
+ // 3. Built-in Clado slash prompt commands (/arch, /review, /test, /diff, /svg, /ui)
495
+ if (Object.prototype.hasOwnProperty.call(BUILTIN_SLASH_PROMPTS, cmd)) {
496
+ const base = BUILTIN_SLASH_PROMPTS[cmd];
497
+ return {
498
+ expanded: true,
499
+ command: '/' + cmd,
500
+ text: restArgs ? `${base}\n\n补充要求:${restArgs}` : base,
501
+ };
502
+ }
503
+
504
+ return { expanded: false, text: clean, command: '' };
505
+ }
506
+
507
+ function extractAtMentions(rawText, workspace) {
508
+ const s = String(rawText || '');
509
+ if (!s.includes('@')) return { cards: [], docs: [], files: [] };
510
+ const cards = [];
511
+ const docs = [];
512
+ const files = [];
513
+ const seenCard = new Set();
514
+ const seenDoc = new Set();
515
+ const seenFile = new Set();
516
+
517
+ // @[卡片:标题] or @卡片:标题
518
+ for (const m of s.matchAll(/@\[卡片:([^\]]+)\]/g)) {
519
+ const name = String(m[1] || '').trim();
520
+ if (name && !seenCard.has(name)) {
521
+ seenCard.add(name);
522
+ cards.push(name);
523
+ }
524
+ }
525
+ // @doc:path/to/file.md
526
+ for (const m of s.matchAll(/(?:^|[\s((【])@doc:([^\s))】]+)/g)) {
527
+ const doc = String(m[1] || '').trim();
528
+ if (doc && !seenDoc.has(doc)) {
529
+ seenDoc.add(doc);
530
+ docs.push(doc);
531
+ }
532
+ }
533
+ // @relative/path.ext (verify existence inside workspace to avoid matching emails)
534
+ if (workspace) {
535
+ const wsRoot = resolve(workspace);
536
+ for (const m of s.matchAll(/(?:^|[\s((【])@([a-zA-Z0-9._/-]+\.[a-zA-Z0-9_-]+)/g)) {
537
+ const rel = String(m[1] || '').replace(/^\/+/, '');
538
+ if (!rel || rel.startsWith('doc:') || rel.includes('..') || seenFile.has(rel)) continue;
539
+ try {
540
+ const abs = resolve(wsRoot, rel);
541
+ if ((abs === wsRoot || abs.startsWith(wsRoot + '/')) && existsSync(abs) && statSync(abs).isFile()) {
542
+ seenFile.add(rel);
543
+ files.push(rel);
544
+ }
545
+ } catch {}
546
+ }
547
+ }
548
+ return { cards, docs, files };
549
+ }
550
+
551
+ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir = resolvePiAgentDir() }) {
552
+ const slashResult = expandSlashPrompt(text, { workspace, agentDir });
553
+ const finalUserText = slashResult.text;
554
+ const mentions = extractAtMentions(text, workspace);
555
+
183
556
  const lines = [];
184
557
  if (handoffFrom) {
185
558
  lines.push(`[设计交付交接 · 来自「${handoffFrom}」]`);
186
559
  }
560
+ if (slashResult.expanded) {
561
+ lines.push(`已触发斜杠命令:${slashResult.command}`);
562
+ }
187
563
  if (canvas?.file) {
188
564
  lines.push(`当前画布文件:${canvas.file}`);
189
565
  if (Array.isArray(canvas.selection) && canvas.selection.length) {
@@ -194,11 +570,27 @@ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFr
194
570
  const objStr = canvas.objectSelection.map(o => `${o.title || o.id}(${o.kind})`).join(';');
195
571
  lines.push(`用户选中的画布组件:${objStr}`);
196
572
  }
573
+ if (canvas.textSnippet && typeof canvas.textSnippet === 'object' && canvas.textSnippet.text) {
574
+ const nodeLabel = Array.isArray(canvas.textSnippet.node) && canvas.textSnippet.node.length
575
+ ? canvas.textSnippet.node.join(' > ')
576
+ : '';
577
+ const quoted = String(canvas.textSnippet.text).replace(/\s+/g, ' ').trim().slice(0, 320);
578
+ lines.push(`用户框选的精确片段${nodeLabel ? `(位于 ${nodeLabel})` : ''}:「${quoted}」`);
579
+ }
580
+ }
581
+ if (mentions.cards.length) {
582
+ lines.push(`用户通过 @ 引用的画布卡片:${mentions.cards.join(';')}`);
583
+ }
584
+ if (mentions.docs.length) {
585
+ lines.push(`用户通过 @ 引用的画布文档:${mentions.docs.join(';')}`);
586
+ }
587
+ if (mentions.files.length) {
588
+ lines.push(`用户通过 @ 引用的工作区文件(请优先 read 查看):${mentions.files.join(';')}`);
197
589
  }
198
590
  if (lines.length) {
199
- return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${text}`;
591
+ return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${finalUserText}`;
200
592
  }
201
- return text;
593
+ return finalUserText;
202
594
  }
203
595
 
204
596
  async function resolvePiModel(modelRuntime, settingsManager, requestedSpec) {
@@ -243,8 +635,237 @@ export function createPiBridge({
243
635
  workspaceService = null,
244
636
  events = null,
245
637
  sessionFactory = null,
638
+ onSystemEvent = null,
639
+ automationOps = null,
246
640
  } = {}) {
247
641
  const liveRuns = new Map();
642
+ const warmSessions = new Map(); // `${workspace}::${cleanId}` -> { session, loader, sm, mr, modelKey, roleId, agentDir, stateDir, turnHooksRef, needsReload, notifications, extensionErrors }
643
+ const pairNoProgressStreak = new Map(); // sorted pair key -> consecutive no-progress cross-session sends
644
+ const SUBSTANTIVE_TOOLS = new Set([
645
+ 'clado_create', 'clado_update', 'clado_nodes', 'clado_links', 'clado_documents', 'clado_batch',
646
+ 'edit', 'write', 'bash', 'ask_user', 'canvas_objects_upsert', 'canvas_objects_delete',
647
+ ]);
648
+ const createBuiltInPiExtensions = (agentDir, { workspace = '', getAskUser = null, getRoleTools = null } = {}) => [
649
+ { name: 'codemode', factory: createCodemodeExtension(), replaceable: true, builtin: true },
650
+ { name: 'tool-search', factory: createToolSearchExtension(), replaceable: true, builtin: true },
651
+ {
652
+ name: 'mcp',
653
+ factory: createMcpExtension({
654
+ logPath: join(agentDir, 'mcp.log'),
655
+ loadConfig: () => buildMergedPiMcpConfig(workspace, agentDir),
656
+ }),
657
+ replaceable: true,
658
+ builtin: true,
659
+ },
660
+ { name: 'clado-guard-hooks', factory: createCladoGuardAndHooksExtension({ workspace, agentDir, getAskUser, getRoleTools }), replaceable: true, builtin: true },
661
+ ];
662
+ const shutdownAndDisposeSession = async session => {
663
+ if (!session) return;
664
+ try {
665
+ if (session.extensionRunner?.hasHandlers?.('session_shutdown')) {
666
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'exit' });
667
+ }
668
+ } catch {}
669
+ try { session.dispose?.(); } catch {}
670
+ };
671
+ const bindSessionForClado = async (session, entry) => {
672
+ await session.bindExtensions({
673
+ mode: 'print',
674
+ uiContext: {
675
+ notify(msg, level = 'info') {
676
+ if (!msg) return;
677
+ const note = { level: String(level || 'info'), message: String(msg), ts: Date.now() };
678
+ entry.notifications.push(note);
679
+ if (entry.notifications.length > 30) entry.notifications.splice(0, entry.notifications.length - 30);
680
+ try {
681
+ if (level === 'error' || level === 'warning') {
682
+ entry.turnHooksRef?.emit?.({ type: 'status', text: `[Pi ${level}] ${msg}` });
683
+ }
684
+ } catch {}
685
+ },
686
+ },
687
+ commandContextActions: {
688
+ waitForIdle: () => session.waitForIdle(),
689
+ reload: async () => {
690
+ await session.reload();
691
+ },
692
+ newSession: async () => ({ cancelled: true }),
693
+ fork: async () => ({ cancelled: true }),
694
+ navigateTree: async () => ({ cancelled: true }),
695
+ switchSession: async () => ({ cancelled: true }),
696
+ },
697
+ onError(err) {
698
+ const text = err?.error ? `${err.extensionPath || 'extension'}: ${err.error}` : String(err || 'Extension error');
699
+ entry.extensionErrors.push({ message: text, ts: Date.now() });
700
+ if (entry.extensionErrors.length > 20) entry.extensionErrors.splice(0, entry.extensionErrors.length - 20);
701
+ },
702
+ });
703
+ };
704
+ const pairKeyOf = (a, b) => [String(a || ''), String(b || '')].sort().join('::');
705
+ const resetProgressForSession = sid => {
706
+ const clean = String(sid || '');
707
+ if (!clean) return;
708
+ for (const k of pairNoProgressStreak.keys()) {
709
+ if (k.startsWith(clean + '::') || k.endsWith('::' + clean)) {
710
+ pairNoProgressStreak.set(k, 0);
711
+ }
712
+ }
713
+ };
714
+ const emitSystem = (workspace, eventType, payload = {}) => {
715
+ try { onSystemEvent?.(workspace, eventType, payload); } catch {}
716
+ };
717
+
718
+ function readSessionTranscript(stateDir, targetId, { limit = 12, agentDir = resolvePiAgentDir() } = {}) {
719
+ const cleanTarget = safeSessionId(targetId);
720
+ const meta = getSessionMeta(stateDir, cleanTarget, agentDir, { messageLimit: 1 });
721
+ if (!meta) return null;
722
+ const page = readSessionMessagesPage(stateDir, cleanTarget, { limit: Math.max(1, Math.min(60, Number(limit) || 12)) });
723
+ return {
724
+ session: {
725
+ id: meta.id,
726
+ title: meta.title,
727
+ roleId: meta.roleId,
728
+ phase: meta.phase,
729
+ status: meta.status,
730
+ updatedAt: meta.updatedAt,
731
+ messageCount: page.totalMessages,
732
+ },
733
+ totalMessages: page.totalMessages,
734
+ oldestIndex: page.oldestIndex,
735
+ hasMoreBefore: page.hasMoreBefore,
736
+ messages: page.messages.map(m => ({
737
+ role: m.role,
738
+ timestamp: m.timestamp,
739
+ fromRoleName: m.handoffFrom || m.fromRoleName || '',
740
+ text: String(m.text || '').slice(0, 1200),
741
+ tools: Array.isArray(m.tools) ? m.tools.map(t => ({ name: t.name, argsSummary: t.argsSummary || '', status: t.status || 'completed' })) : [],
742
+ })),
743
+ };
744
+ }
745
+
746
+ function openOrCreatePeerSession(stateDir, { roleId = 'architect', title = '', reuseLatest = true, workspace = '', agentDir = resolvePiAgentDir() } = {}) {
747
+ const ws = workspace || (stateDir && basename(stateDir) === '.clado' ? dirname(stateDir) : '');
748
+ const role = resolveRole(roleId, agentDir, { workspace: ws, strict: Boolean(roleId) });
749
+ if (reuseLatest) {
750
+ const existing = listSessions(stateDir, { includeArchived: false, includeMessages: false, agentDir })
751
+ .filter(s => s.roleId === role.id)
752
+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')))[0];
753
+ if (existing) return { session: existing, created: false };
754
+ }
755
+ const created = upsertSessionMeta(stateDir, {
756
+ roleId: role.id,
757
+ workspace: ws,
758
+ title: String(title || role.name).trim(),
759
+ }, agentDir);
760
+ return { session: created, created: true };
761
+ }
762
+
763
+ async function sendCrossSessionMessage({
764
+ workspace,
765
+ stateDir,
766
+ documentRoot,
767
+ fromSessionId = '',
768
+ fromRoleId = '',
769
+ fromRoleName = '同伴角色',
770
+ targetSessionId = '',
771
+ targetRoleId = '',
772
+ message = '',
773
+ canvas = null,
774
+ wait = false,
775
+ automationRuleId = '',
776
+ }) {
777
+ const cleanMsg = String(message || '').trim();
778
+ if (!cleanMsg) throw new Error('跨会话消息内容不能为空。');
779
+ const agentDir = resolvePiAgentDir();
780
+ let targetMeta = targetSessionId ? getSessionMeta(stateDir, safeSessionId(targetSessionId), agentDir, { messageLimit: 1 }) : null;
781
+ if (!targetMeta && targetRoleId) {
782
+ targetMeta = openOrCreatePeerSession(stateDir, { roleId: targetRoleId, reuseLatest: true, workspace, agentDir }).session;
783
+ }
784
+ if (!targetMeta) throw new Error('找不到目标主会话,请传入有效的 sessionId 或 roleId。');
785
+ if (fromSessionId && safeSessionId(fromSessionId) === targetMeta.id) {
786
+ throw new Error('不能给自己发送跨会话协作消息。');
787
+ }
788
+
789
+ // Progress-based anti-ping-pong guard (only trips after 3 consecutive no-progress bounces; resets on any substantive tool call!)
790
+ if (fromSessionId && !automationRuleId) {
791
+ const pKey = pairKeyOf(safeSessionId(fromSessionId), targetMeta.id);
792
+ const streak = (pairNoProgressStreak.get(pKey) || 0) + 1;
793
+ if (streak > 3) {
794
+ events?.emit(workspace, 'agent.sessions', { action: 'circuit_broken', fromSessionId, targetSessionId: targetMeta.id });
795
+ return {
796
+ ok: false,
797
+ circuitBroken: true,
798
+ targetSessionId: targetMeta.id,
799
+ message: `检测到「${fromRoleName}」与「${targetMeta.title}」连续 3 轮跨会话互发消息且无实质工具产出,已自动熔断防原地打转;请总结当前进展并交由用户确认或直接执行具体操作后再沟通。`,
800
+ };
801
+ }
802
+ pairNoProgressStreak.set(pKey, streak);
803
+ }
804
+
805
+ const formatted = `[来自「${fromRoleName}」的协作消息]\n${cleanMsg}`;
806
+ emitSystem(workspace, 'session.message_received', {
807
+ originSessionId: fromSessionId ? safeSessionId(fromSessionId) : '',
808
+ originRoleId: fromRoleId || '',
809
+ targetSessionId: targetMeta.id,
810
+ targetRoleId: targetMeta.roleId,
811
+ automationRuleId,
812
+ preview: cleanMsg.slice(0, 160),
813
+ });
814
+
815
+ const running = liveRuns.get(`${workspace}::${targetMeta.id}`);
816
+ if (running) {
817
+ const steered = await running.steer(formatted);
818
+ return {
819
+ ok: true,
820
+ delivered: steered ? 'steered' : 'busy',
821
+ targetSessionId: targetMeta.id,
822
+ targetTitle: targetMeta.title,
823
+ targetRoleId: targetMeta.roleId,
824
+ };
825
+ }
826
+
827
+ let replyPreview = '';
828
+ const turnPromise = runTurn({
829
+ workspace,
830
+ stateDir,
831
+ documentRoot,
832
+ sessionId: targetMeta.id,
833
+ roleId: targetMeta.roleId,
834
+ text: formatted,
835
+ canvas: canvas || {},
836
+ handoffFrom: fromRoleName,
837
+ automationRuleId,
838
+ emit: ev => {
839
+ if (ev?.type === 'text' && ev.text && replyPreview.length < 1200) {
840
+ replyPreview += ev.text;
841
+ }
842
+ },
843
+ }).then(() => {
844
+ events?.emit(workspace, 'agent.sessions', { action: 'updated', sessionId: targetMeta.id });
845
+ }).catch(() => {
846
+ events?.emit(workspace, 'agent.sessions', { action: 'updated', sessionId: targetMeta.id });
847
+ });
848
+
849
+ if (wait) {
850
+ await turnPromise;
851
+ return {
852
+ ok: true,
853
+ delivered: 'completed',
854
+ targetSessionId: targetMeta.id,
855
+ targetTitle: targetMeta.title,
856
+ targetRoleId: targetMeta.roleId,
857
+ replyPreview: replyPreview.trim().slice(0, 1000),
858
+ };
859
+ }
860
+
861
+ return {
862
+ ok: true,
863
+ delivered: 'woken',
864
+ targetSessionId: targetMeta.id,
865
+ targetTitle: targetMeta.title,
866
+ targetRoleId: targetMeta.roleId,
867
+ };
868
+ }
248
869
 
249
870
  async function runTurn({
250
871
  workspace,
@@ -256,24 +877,38 @@ export function createPiBridge({
256
877
  text,
257
878
  canvas,
258
879
  handoffFrom = '',
880
+ automationRuleId = '',
259
881
  emit,
260
882
  }) {
261
883
  const agentDir = resolvePiAgentDir();
262
884
  const cleanId = safeSessionId(sessionId);
263
885
  const meta = upsertSessionMeta(stateDir, {
264
886
  id: cleanId,
265
- ...(roleId ? { roleId } : {}),
887
+ workspace,
888
+ ...(roleId ? { roleId, strictRole: true } : {}),
266
889
  ...(modelSpec ? { model: modelSpec } : {}),
267
890
  status: 'running',
268
891
  }, agentDir);
269
- const role = resolveRole(meta.roleId, agentDir);
892
+ const role = resolveRole(meta.roleId, agentDir, { workspace });
893
+
894
+ // Load FULL un-truncated history from per-session file; dismiss any stale unanswered ask_user from past turns
895
+ const existingMessages = readSessionMessages(stateDir, cleanId).map(m => {
896
+ if (!m || m.role !== 'assistant') return m;
897
+ const hasStaleQ = Array.isArray(m.questions) && m.questions.some(q => q && !q.answered && !q.dismissed);
898
+ const hasStaleSingle = Boolean(m.question && !m.question.answered && !m.question.dismissed);
899
+ if (!hasStaleQ && !hasStaleSingle) return m;
900
+ return {
901
+ ...m,
902
+ ...(Array.isArray(m.questions) ? { questions: m.questions.map(q => (q && !q.answered ? { ...q, dismissed: true } : q)) } : {}),
903
+ ...(hasStaleSingle ? { question: { ...m.question, dismissed: true } } : {}),
904
+ };
905
+ });
906
+ const shouldAutoTitle = existingMessages.length === 0 && !cleanId.startsWith('role_') && (meta.title === role.name || meta.title.startsWith(role.name + ' · 新会话'));
907
+ const autoTitle = shouldAutoTitle ? text.replace(/\s+/g, ' ').trim().slice(0, 22) : undefined;
270
908
 
271
909
  // Capture pre-turn canvas snapshot for 1-click rollback
272
910
  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
- }
911
+ const nextSnaps = snap ? [...(meta.snapshots || []).slice(-11), snap] : (meta.snapshots || []);
277
912
 
278
913
  const userMsg = {
279
914
  id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
@@ -282,48 +917,288 @@ export function createPiBridge({
282
917
  canvasFile: canvas?.file || '',
283
918
  selection: canvas?.selection || [],
284
919
  handoffFrom,
920
+ ...(automationRuleId ? { automationRuleId } : {}),
285
921
  timestamp: new Date().toISOString(),
286
922
  };
287
- const nextMessages = [...(meta.messages || []).slice(-60), userMsg];
288
- upsertSessionMeta(stateDir, { id: cleanId, messages: nextMessages }, agentDir);
923
+ const nextMessages = [...existingMessages, userMsg];
924
+ upsertSessionMeta(stateDir, {
925
+ id: cleanId,
926
+ ...(autoTitle ? { title: autoTitle } : {}),
927
+ snapshots: nextSnaps,
928
+ messages: nextMessages,
929
+ }, agentDir);
289
930
 
290
931
  const pendingQuestions = new Map();
932
+ const recordedQuestions = [];
291
933
  const waitForUserAnswer = (questionId, signal) => new Promise((resolveAnswer, rejectAnswer) => {
292
934
  const onAbort = () => {
293
935
  pendingQuestions.delete(questionId);
294
- rejectAnswer(new Error('已取消等待确认'));
936
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
937
+ if (rec && !rec.answered) rec.dismissed = true;
938
+ rejectAnswer(new Error('已停止生成'));
295
939
  };
296
940
  signal?.addEventListener('abort', onAbort, { once: true });
297
941
  pendingQuestions.set(questionId, {
298
942
  resolve(ans) {
299
943
  signal?.removeEventListener('abort', onAbort);
300
944
  pendingQuestions.delete(questionId);
945
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
946
+ if (rec) { rec.answered = true; rec.answer = ans; rec.dismissed = false; }
301
947
  resolveAnswer(ans);
302
948
  },
303
949
  reject(err) {
304
950
  signal?.removeEventListener('abort', onAbort);
305
951
  pendingQuestions.delete(questionId);
952
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
953
+ if (rec && !rec.answered) rec.dismissed = true;
306
954
  rejectAnswer(err);
307
955
  },
308
956
  });
309
957
  });
310
958
 
959
+ const turnId = 'turn_' + randomUUID().replace(/-/g, '').slice(0, 10);
960
+ let liveActivity = '正在思考并准备上下文…';
961
+ let sseDeltaType = '';
962
+ let sseDeltaBuf = '';
963
+ let sseDeltaTimer = null;
964
+
965
+ const flushSseDelta = () => {
966
+ if (sseDeltaTimer) {
967
+ clearTimeout(sseDeltaTimer);
968
+ sseDeltaTimer = null;
969
+ }
970
+ if (sseDeltaType && sseDeltaBuf) {
971
+ events?.emit(workspace, 'agent.stream', {
972
+ sessionId: cleanId,
973
+ roleId: role.id,
974
+ roleName: role.name,
975
+ turnId,
976
+ type: sseDeltaType,
977
+ text: sseDeltaBuf,
978
+ activity: liveActivity,
979
+ });
980
+ }
981
+ sseDeltaType = '';
982
+ sseDeltaBuf = '';
983
+ };
984
+
985
+ const emitSseStream = ev => {
986
+ if (!events || !ev || !ev.type) return;
987
+ if (ev.type === 'text' || ev.type === 'thinking') {
988
+ const chunk = String(ev.text || '');
989
+ if (!chunk) return;
990
+ if (sseDeltaType && sseDeltaType !== ev.type) flushSseDelta();
991
+ sseDeltaType = ev.type;
992
+ sseDeltaBuf += chunk;
993
+ if (!sseDeltaTimer) {
994
+ sseDeltaTimer = setTimeout(flushSseDelta, 32);
995
+ sseDeltaTimer.unref?.();
996
+ }
997
+ return;
998
+ }
999
+ flushSseDelta();
1000
+ events.emit(workspace, 'agent.stream', {
1001
+ sessionId: cleanId,
1002
+ roleId: role.id,
1003
+ roleName: role.name,
1004
+ turnId,
1005
+ ...ev,
1006
+ activity: liveActivity,
1007
+ });
1008
+ };
1009
+
1010
+ let substantiveToolsCount = 0;
1011
+ const markSubstantiveProgress = toolName => {
1012
+ if (SUBSTANTIVE_TOOLS.has(toolName)) {
1013
+ substantiveToolsCount++;
1014
+ resetProgressForSession(cleanId);
1015
+ }
1016
+ };
1017
+
1018
+ const emitWrapped = ev => {
1019
+ if (ev?.type === 'thinking') liveActivity = '正在深度思考…';
1020
+ else if (ev?.type === 'text') liveActivity = '正在生成回复…';
1021
+ else if (ev?.type === 'tool') {
1022
+ if (ev.status === 'running') {
1023
+ liveActivity = `正在执行 ${ev.name || '工具'}${ev.argsSummary ? ' · ' + ev.argsSummary : ''}`;
1024
+ } else if (ev.status === 'failed' || ev.isError) {
1025
+ liveActivity = `${ev.name || '工具'} 执行失败,正在诊断并修复…`;
1026
+ } else {
1027
+ liveActivity = '工具执行完成,正在继续…';
1028
+ }
1029
+ } else if (ev?.type === 'steer') liveActivity = '已收到中途插话,正在调整方向…';
1030
+ else if (ev?.type === 'status' && ev.text) liveActivity = ev.text;
1031
+ else if (ev?.type === 'done' || ev?.type === 'error') liveActivity = '';
1032
+
1033
+ if (ev?.type === 'tool' && ev.status === 'completed' && !ev.isError) {
1034
+ markSubstantiveProgress(ev.name);
1035
+ }
1036
+ if (ev?.type === 'ask_user') {
1037
+ liveActivity = '等待你的确认…';
1038
+ markSubstantiveProgress('ask_user');
1039
+ recordedQuestions.push({
1040
+ questionId: ev.questionId,
1041
+ question: ev.question,
1042
+ options: ev.options || [],
1043
+ answered: false,
1044
+ answer: '',
1045
+ });
1046
+ emitSystem(workspace, 'session.waiting_user', {
1047
+ originSessionId: cleanId,
1048
+ originRoleId: role.id,
1049
+ questionId: ev.questionId,
1050
+ question: ev.question,
1051
+ automationRuleId,
1052
+ });
1053
+ }
1054
+ emitSseStream(ev);
1055
+ emit(ev);
1056
+ };
1057
+
311
1058
  const cladoTools = createCladoPiTools({
312
1059
  workspace,
313
1060
  stateDir,
314
1061
  workspaceService,
315
1062
  events,
316
- emit,
1063
+ emit: emitWrapped,
317
1064
  waitForUserAnswer,
1065
+ sessionOps: {
1066
+ currentSessionId: cleanId,
1067
+ currentRoleId: role.id,
1068
+ currentRoleName: role.name,
1069
+ list: ({ sinceMinutes = 0, includeArchived = false } = {}) =>
1070
+ listSessions(stateDir, { includeArchived, includeMessages: false, sinceMinutes, agentDir }),
1071
+ read: ({ sessionId: targetId, limit = 12 }) =>
1072
+ readSessionTranscript(stateDir, targetId, { limit, agentDir }),
1073
+ open: ({ roleId: targetRoleId, title = '', reuseLatest = true }) =>
1074
+ openOrCreatePeerSession(stateDir, { roleId: targetRoleId, title, reuseLatest, workspace, agentDir }),
1075
+ send: ({ targetSessionId, targetRoleId, message, wait = false }) =>
1076
+ sendCrossSessionMessage({
1077
+ workspace,
1078
+ stateDir,
1079
+ documentRoot,
1080
+ fromSessionId: cleanId,
1081
+ fromRoleId: role.id,
1082
+ fromRoleName: role.name,
1083
+ targetSessionId,
1084
+ targetRoleId,
1085
+ message,
1086
+ canvas,
1087
+ wait,
1088
+ }),
1089
+ },
1090
+ automationOps,
1091
+ onCardChanges: (toolName, res) => {
1092
+ markSubstantiveProgress(toolName);
1093
+ if (Array.isArray(res?.cardChanges)) {
1094
+ for (const ch of res.cardChanges) {
1095
+ emitSystem(workspace, `card.${ch.action}`, {
1096
+ file: ch.file,
1097
+ card: ch.card,
1098
+ addedTags: ch.addedTags,
1099
+ removedTags: ch.removedTags,
1100
+ originSessionId: cleanId,
1101
+ originRoleId: role.id,
1102
+ automationRuleId,
1103
+ });
1104
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
1105
+ emitSystem(workspace, 'tag.changed', {
1106
+ file: ch.file,
1107
+ card: ch.card,
1108
+ addedTags: ch.addedTags,
1109
+ removedTags: ch.removedTags,
1110
+ originSessionId: cleanId,
1111
+ originRoleId: role.id,
1112
+ automationRuleId,
1113
+ });
1114
+ }
1115
+ }
1116
+ }
1117
+ },
318
1118
  });
319
1119
 
320
1120
  let assistantText = '';
321
1121
  const toolLog = [];
1122
+ const blocks = [];
322
1123
  let session = null;
1124
+ let activeWarmEntry = null;
323
1125
  let unsub = null;
1126
+ let abortedByUser = false;
1127
+ let piSessionFile = meta.piSessionFile || '';
1128
+
1129
+ const appendThinkingDelta = delta => {
1130
+ if (!delta) return;
1131
+ const lastBlock = blocks[blocks.length - 1];
1132
+ if (lastBlock && lastBlock.type === 'thinking') {
1133
+ lastBlock.text += delta;
1134
+ } else {
1135
+ blocks.push({ type: 'thinking', text: delta });
1136
+ }
1137
+ };
1138
+
1139
+ const appendTextDelta = delta => {
1140
+ if (!delta) return;
1141
+ const lastBlock = blocks[blocks.length - 1];
1142
+ if (lastBlock && lastBlock.type === 'text') {
1143
+ lastBlock.text += delta;
1144
+ assistantText += delta;
1145
+ } else {
1146
+ blocks.push({ type: 'text', text: delta });
1147
+ if (assistantText && !assistantText.endsWith('\n\n') && !delta.startsWith('\n')) {
1148
+ assistantText += '\n\n';
1149
+ }
1150
+ assistantText += delta;
1151
+ }
1152
+ };
1153
+
1154
+ const upsertToolEntry = ev => {
1155
+ const existing = toolLog.find(t => t.id === ev.id);
1156
+ if (existing) {
1157
+ if (ev.name || ev.title) existing.name = ev.name || existing.name;
1158
+ if (ev.argsSummary !== undefined && ev.argsSummary !== '') existing.argsSummary = ev.argsSummary;
1159
+ if (ev.status) existing.status = ev.status;
1160
+ if (ev.isError !== undefined) existing.isError = Boolean(ev.isError);
1161
+ if (ev.resultPreview !== undefined) existing.resultPreview = ev.resultPreview;
1162
+ return existing;
1163
+ }
1164
+ const entry = {
1165
+ id: ev.id,
1166
+ name: ev.name || ev.title || 'tool',
1167
+ argsSummary: ev.argsSummary || '',
1168
+ status: ev.status || 'running',
1169
+ isError: Boolean(ev.isError || ev.status === 'failed'),
1170
+ resultPreview: ev.resultPreview || '',
1171
+ };
1172
+ toolLog.push(entry);
1173
+ const lastBlock = blocks[blocks.length - 1];
1174
+ if (lastBlock && lastBlock.type === 'tools') {
1175
+ lastBlock.tools.push(entry);
1176
+ } else {
1177
+ blocks.push({ type: 'tools', tools: [entry] });
1178
+ }
1179
+ return entry;
1180
+ };
1181
+
1182
+ const turnAbort = new AbortController();
1183
+ let draftActive = false;
1184
+ let customSteerHandler = null;
324
1185
 
325
1186
  const runState = {
326
1187
  sessionId: cleanId,
1188
+ turnId,
1189
+ getLiveAssistant() {
1190
+ return {
1191
+ id: 'live_' + turnId,
1192
+ turnId,
1193
+ role: 'assistant',
1194
+ text: assistantText,
1195
+ tools: toolLog.map(t => ({ ...t })),
1196
+ blocks: blocks.map(b => (b?.type === 'tools' ? { ...b, tools: b.tools.map(t => ({ ...t })) } : { ...b })),
1197
+ questions: recordedQuestions.map(q => ({ ...q })),
1198
+ activity: liveActivity || 'Pi 正在思考与执行…',
1199
+ streaming: true,
1200
+ };
1201
+ },
327
1202
  answer(questionId, answerText) {
328
1203
  const waiter = pendingQuestions.get(questionId);
329
1204
  if (!waiter) return false;
@@ -331,29 +1206,224 @@ export function createPiBridge({
331
1206
  return true;
332
1207
  },
333
1208
  async steer(steerText) {
334
- if (session?.steer) {
335
- await session.steer(steerText);
1209
+ const clean = String(steerText || '').trim();
1210
+ if (!clean) return false;
1211
+ const handler = session?.steer
1212
+ ? (t) => session.steer(t)
1213
+ : (typeof customSteerHandler === 'function' ? customSteerHandler : null);
1214
+ if (!handler) return false;
1215
+ const steerBlock = { type: 'steer', text: clean };
1216
+ blocks.push(steerBlock);
1217
+ emitWrapped({ type: 'steer', text: clean });
1218
+ try {
1219
+ await handler(clean);
336
1220
  return true;
1221
+ } catch (err) {
1222
+ const idx = blocks.lastIndexOf(steerBlock);
1223
+ if (idx >= 0) blocks.splice(idx, 1);
1224
+ throw err;
337
1225
  }
338
- return false;
339
1226
  },
340
1227
  async abort() {
341
- for (const w of pendingQuestions.values()) w.reject(new Error('用户已中止'));
1228
+ abortedByUser = true;
1229
+ turnAbort.abort();
1230
+ for (const w of pendingQuestions.values()) w.reject(new Error('用户已停止生成'));
342
1231
  pendingQuestions.clear();
343
1232
  if (session?.abort) await session.abort();
344
1233
  },
345
1234
  };
346
1235
  liveRuns.set(`${workspace}::${cleanId}`, runState);
1236
+ emitSseStream({ type: 'turn_start', userMessage: userMsg, title: autoTitle || meta.title, phase: meta.phase, tone: meta.tone });
1237
+ events?.emit(workspace, 'agent.sessions', { action: 'started', sessionId: cleanId, roleId: role.id, title: autoTitle || meta.title });
1238
+
1239
+ const persistAssistantTurn = ({ stopped = false, errorMsg = '' } = {}) => {
1240
+ const suffixParts = [];
1241
+ if (stopped) suffixParts.push('_(已手动停止,以上内容已保留)_');
1242
+ if (errorMsg) suffixParts.push('提示:' + errorMsg);
1243
+ if (suffixParts.length) {
1244
+ const suffix = suffixParts.join('\n\n');
1245
+ const lastBlock = blocks[blocks.length - 1];
1246
+ if (lastBlock && lastBlock.type === 'text') {
1247
+ lastBlock.text += (lastBlock.text ? '\n\n' : '') + suffix;
1248
+ } else {
1249
+ blocks.push({ type: 'text', text: suffix });
1250
+ }
1251
+ }
1252
+ const finalText = assistantText
1253
+ + (stopped ? (assistantText ? '\n\n' : '') + '_(已手动停止,以上内容已保留)_' : '')
1254
+ + (errorMsg ? (assistantText ? '\n\n' : '') + '提示:' + errorMsg : '');
1255
+ const curMeta = getSessionMeta(stateDir, cleanId, agentDir, { messageLimit: 1 });
1256
+ const diskMsgs = readSessionMessages(stateDir, cleanId);
1257
+ const baseMsgs = diskMsgs.length ? diskMsgs : nextMessages;
1258
+ const finalizedQuestions = recordedQuestions.map(q => (q && !q.answered ? { ...q, dismissed: true } : q));
1259
+ const assistantMsg = {
1260
+ id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
1261
+ role: 'assistant',
1262
+ text: finalText,
1263
+ tools: toolLog,
1264
+ blocks,
1265
+ questions: finalizedQuestions,
1266
+ stopped: Boolean(stopped),
1267
+ snapshotId: snap?.id || '',
1268
+ timestamp: new Date().toISOString(),
1269
+ };
1270
+ const badge = toolLog.length ? `${toolLog.length} tools` : (curMeta?.summaryBadge || '');
1271
+ upsertSessionMeta(stateDir, {
1272
+ id: cleanId,
1273
+ status: 'idle',
1274
+ ...(piSessionFile ? { piSessionFile } : {}),
1275
+ ...(latestContextUsage ? { contextUsage: latestContextUsage } : {}),
1276
+ summaryBadge: badge,
1277
+ messages: [...baseMsgs, assistantMsg],
1278
+ }, agentDir);
1279
+ };
1280
+
1281
+ let latestContextUsage = meta.contextUsage || null;
1282
+ let presenceTouched = false;
1283
+ const selectedCardTitles = [...new Set(
1284
+ (Array.isArray(canvas?.selection) ? canvas.selection : [])
1285
+ .map(item => (Array.isArray(item) ? item[0] : (Array.isArray(item?.nodePath) ? item.nodePath[0] : (typeof item === 'string' ? item : ''))))
1286
+ .map(s => String(s || '').trim())
1287
+ .filter(Boolean)
1288
+ )];
1289
+ const emitPresence = (payload = {}) => {
1290
+ if (!events) return;
1291
+ const phase = payload.phase || 'active';
1292
+ if (phase === 'active') presenceTouched = true;
1293
+ events.emit(workspace, 'agent.presence', {
1294
+ sessionId: cleanId,
1295
+ roleId: role.id,
1296
+ roleName: role.name,
1297
+ tone: role.tone || 'sky',
1298
+ file: payload.file || canvas?.file || '',
1299
+ cards: Array.isArray(payload.cards) ? payload.cards : [],
1300
+ label: payload.label || '',
1301
+ codePath: payload.codePath || '',
1302
+ phase,
1303
+ ts: Date.now(),
1304
+ });
1305
+ };
347
1306
 
348
1307
  try {
349
- emit({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
1308
+ emitWrapped({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
1309
+ events?.emit(workspace, 'agent.stage', {
1310
+ sessionId: cleanId,
1311
+ roleId: role.id,
1312
+ roleName: role.name,
1313
+ phase: role.phase || '',
1314
+ tone: role.tone || 'sky',
1315
+ handoffFrom: handoffFrom || '',
1316
+ file: canvas?.file || '',
1317
+ });
1318
+ if (selectedCardTitles.length) {
1319
+ const phaseVerb = role.phase ? role.phase.replace(/阶段$/, '') : '处理';
1320
+ emitPresence({
1321
+ phase: 'active',
1322
+ cards: selectedCardTitles,
1323
+ label: `${phaseVerb}中…`,
1324
+ });
1325
+ }
350
1326
 
351
- if (sessionFactory) {
352
- // Test injection hook
1327
+ const platformContext = readCladoPlatformContext(agentDir);
1328
+ const pluginParamsBundle = readPluginParams(workspace, stateDir, agentDir);
1329
+ const pluginParamEntries = Object.entries(pluginParamsBundle?.items || {});
1330
+ const PROTECTED_ENV_KEYS = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD', 'NODE_ENV', 'CLADO_PI_AGENT_DIR']);
1331
+ const injectedParamLines = [];
1332
+ for (const [pluginId, cfg] of pluginParamEntries) {
1333
+ const envObj = cfg?.env && typeof cfg.env === 'object' ? cfg.env : {};
1334
+ const paramsObj = cfg?.params && typeof cfg.params === 'object' ? cfg.params : {};
1335
+ const envKeys = [];
1336
+ for (const [k, v] of Object.entries(envObj)) {
1337
+ if (!k || PROTECTED_ENV_KEYS.has(k)) continue;
1338
+ envKeys.push(k);
1339
+ if (!sessionFactory) process.env[k] = String(v ?? '');
1340
+ }
1341
+ const hasParams = Object.keys(paramsObj).length > 0;
1342
+ if (hasParams || envKeys.length) {
1343
+ injectedParamLines.push(
1344
+ `- ${pluginId}:`
1345
+ + (hasParams ? ` params=${JSON.stringify(paramsObj)}` : '')
1346
+ + (envKeys.length ? ` envKeys=[${envKeys.join(', ')}]` : '')
1347
+ );
1348
+ }
1349
+ }
1350
+ const pluginParamsContext = injectedParamLines.length
1351
+ ? `\n\n## 插件与扩展注入参数\n以下参数由用户在 Clado 设置中心为当前工作区/插件配置(环境变量已注入进程环境):\n${injectedParamLines.join('\n')}`
1352
+ : '';
1353
+
1354
+ const trimmedCommand = String(text || '').trim();
1355
+ const isReloadCmd = !handoffFrom && (/^\/reload(?:\s|$)/i.test(trimmedCommand));
1356
+ const isCompactCmd = !handoffFrom && (/^\/compact(?:\s|$)/i.test(trimmedCommand));
1357
+
1358
+ if (isReloadCmd) {
1359
+ emitWrapped({ type: 'status', text: '正在执行 Pi 原生热重载(/reload)…' });
1360
+ const summary = await reloadSession({
1361
+ workspace,
1362
+ stateDir,
1363
+ sessionId: cleanId,
1364
+ roleId: role.id,
1365
+ modelSpec: modelSpec || meta.model,
1366
+ });
1367
+ const mcpTools = summary.mcpTools || [];
1368
+ const lines = [
1369
+ '### Pi 原生热重载完成 (`/reload`)',
1370
+ '',
1371
+ `- **已加载扩展** (${summary.extensions.length}):${summary.extensions.length ? summary.extensions.map(e => '`' + e + '`').join('、') : '无'}`,
1372
+ `- **已配置 MCP 服务** (${summary.mcpServers.length}):${summary.mcpServers.length ? summary.mcpServers.map(s => '`' + s.name + '` (' + s.type + '/' + (s.exposure || 'codemode') + (s.enabled ? '' : '·已禁用') + ')').join('、') : '无'}`,
1373
+ `- **活跃 MCP 工具** (${mcpTools.length}):${mcpTools.length ? mcpTools.slice(0, 24).map(t => '`' + t + '`').join('、') + (mcpTools.length > 24 ? ` 等共 ${mcpTools.length} 项` : '') : '暂无直接暴露工具(若 MCP 使用 codemode/deferred 模式,将按需通过 codemode 或 tool_search 调用)'}`,
1374
+ `- **全部活跃工具** (${summary.activeTools.length}) · **Skills** (${summary.skillsCount}) · **Prompt 命令** (${summary.promptsCount})`,
1375
+ `- **已同步热重载其它会话**:${summary.reloadedPeers || 0} 个`,
1376
+ ];
1377
+ if (summary.errors?.length) {
1378
+ lines.push('', '**诊断警告 / 错误:**');
1379
+ for (const e of summary.errors.slice(0, 8)) lines.push(`- ${e}`);
1380
+ }
1381
+ const reply = lines.join('\n');
1382
+ appendTextDelta(reply);
1383
+ emitWrapped({ type: 'text', text: reply });
1384
+ } else if (isCompactCmd) {
1385
+ const customInstructions = trimmedCommand.replace(/^\/compact\s*/i, '').trim();
1386
+ emitWrapped({ type: 'status', text: '正在压缩当前会话上下文…' });
1387
+ const res = await compactSession({ workspace, stateDir, sessionId: cleanId, customInstructions, allowDuringSelfRun: true });
1388
+ if (res.contextUsage) {
1389
+ latestContextUsage = res.contextUsage;
1390
+ emitWrapped({ type: 'usage', usage: res.contextUsage });
1391
+ }
1392
+ const reply = res.skipped
1393
+ ? `当前会话暂无可压缩历史:${res.reason || ''}`
1394
+ : `已完成上下文压缩(当前占用 ${res.contextUsage?.usedPercent ?? 0}%)。`;
1395
+ appendTextDelta(reply);
1396
+ emitWrapped({ type: 'text', text: reply });
1397
+ } else if (sessionFactory) {
1398
+ const factoryEmit = ev => {
1399
+ if (ev?.type === 'thinking' && ev.text) appendThinkingDelta(ev.text);
1400
+ if (ev?.type === 'text' && ev.text) appendTextDelta(ev.text);
1401
+ if (ev?.type === 'tool') upsertToolEntry(ev);
1402
+ if (ev?.type === 'usage' && ev.usage) latestContextUsage = ev.usage;
1403
+ if (ev?.type === 'presence') {
1404
+ emitPresence(ev);
1405
+ return;
1406
+ }
1407
+ emitWrapped(ev);
1408
+ };
353
1409
  const result = await sessionFactory({
354
- workspace, stateDir, documentRoot, sessionId: cleanId, role, text, canvas, cladoTools, emit, waitForUserAnswer,
1410
+ workspace,
1411
+ stateDir,
1412
+ documentRoot,
1413
+ sessionId: cleanId,
1414
+ role,
1415
+ platformContext,
1416
+ pluginParams: pluginParamsBundle?.items || {},
1417
+ text,
1418
+ canvas,
1419
+ cladoTools,
1420
+ events,
1421
+ emit: factoryEmit,
1422
+ waitForUserAnswer,
1423
+ onSteer: fn => { customSteerHandler = fn; },
1424
+ signal: turnAbort.signal,
355
1425
  });
356
- assistantText = String(result?.text || '');
1426
+ if (!assistantText && result?.text) appendTextDelta(String(result.text));
357
1427
  } else {
358
1428
  const sm = SettingsManager.create(workspace, agentDir);
359
1429
  const mr = await createCladoModelRuntime(agentDir);
@@ -362,106 +1432,1097 @@ export function createPiBridge({
362
1432
  throw new Error('尚未配置可用模型。请点击顶部「设置 → 模型与供应商」填写 API Key 或本地 Ollama 地址。');
363
1433
  }
364
1434
 
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;
1435
+ const activeCtxWin = chosenModel.contextWindow || 128000;
1436
+ const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
1437
+ const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
1438
+ const triggerBudgetTokens = Math.max(8192, activeCtxWin - effectiveReserveTokens);
1439
+ const effectiveKeepRecentTokens = Math.min(
1440
+ runtimeSettings.keepRecentTokens,
1441
+ Math.max(4096, Math.floor(triggerBudgetTokens * 0.45))
1442
+ );
1443
+ const modelOverrideKey = `${chosenModel.provider}/${chosenModel.id}`;
1444
+ const applyRuntimeOverrides = targetSm => {
1445
+ targetSm.applyOverrides({
1446
+ defaultThinkingLevel: runtimeSettings.thinkingLevel,
1447
+ transport: runtimeSettings.transport,
1448
+ hideThinkingBlock: runtimeSettings.hideThinkingBlock,
1449
+ cacheWarming: runtimeSettings.cacheWarming,
1450
+ compaction: {
1451
+ enabled: runtimeSettings.compactionEnabled,
1452
+ reserveTokens: effectiveReserveTokens,
1453
+ keepRecentTokens: effectiveKeepRecentTokens,
1454
+ modelOverrides: {
1455
+ [modelOverrideKey]: {
1456
+ reserveTokens: effectiveReserveTokens,
1457
+ keepRecentTokens: effectiveKeepRecentTokens,
1458
+ },
1459
+ },
1460
+ },
1461
+ retry: {
1462
+ enabled: runtimeSettings.retryEnabled,
1463
+ maxRetries: runtimeSettings.maxRetries,
1464
+ },
1465
+ });
1466
+ };
1467
+ applyRuntimeOverrides(sm);
1468
+
1469
+ const sessionKey = `${workspace}::${cleanId}`;
1470
+ const existingWarm = warmSessions.get(sessionKey);
1471
+ const canReuseWarm = Boolean(
1472
+ existingWarm
1473
+ && existingWarm.session
1474
+ && existingWarm.modelKey === modelOverrideKey
1475
+ && existingWarm.roleId === role.id
1476
+ && existingWarm.agentDir === agentDir
1477
+ && existingWarm.pluginParamsSig === pluginParamsContext
1478
+ );
1479
+
1480
+ const currentHooks = {
1481
+ emit: emitWrapped,
1482
+ waitForUserAnswer,
1483
+ canvas,
1484
+ onCardChanges: (toolName, res) => {
1485
+ markSubstantiveProgress(toolName);
1486
+ if (Array.isArray(res?.cardChanges)) {
1487
+ for (const ch of res.cardChanges) {
1488
+ emitSystem(workspace, `card.${ch.action}`, {
1489
+ file: ch.file,
1490
+ card: ch.card,
1491
+ addedTags: ch.addedTags,
1492
+ removedTags: ch.removedTags,
1493
+ originSessionId: cleanId,
1494
+ originRoleId: role.id,
1495
+ automationRuleId,
1496
+ });
1497
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
1498
+ emitSystem(workspace, 'tag.changed', {
1499
+ file: ch.file,
1500
+ card: ch.card,
1501
+ addedTags: ch.addedTags,
1502
+ removedTags: ch.removedTags,
1503
+ originSessionId: cleanId,
1504
+ originRoleId: role.id,
1505
+ automationRuleId,
1506
+ });
1507
+ }
1508
+ }
1509
+ }
1510
+ },
1511
+ };
1512
+
1513
+ if (canReuseWarm) {
1514
+ activeWarmEntry = existingWarm;
1515
+ activeWarmEntry.turnHooksRef.current = currentHooks;
1516
+ applyRuntimeOverrides(activeWarmEntry.sm);
1517
+ if (activeWarmEntry.needsReload) {
1518
+ emitWrapped({ type: 'status', text: '检测到 MCP / 扩展配置已更新,正在热重载 Pi 会话…' });
1519
+ try {
1520
+ await activeWarmEntry.session.reload();
1521
+ activeWarmEntry.needsReload = false;
1522
+ } catch {
1523
+ await shutdownAndDisposeSession(activeWarmEntry.session);
1524
+ warmSessions.delete(sessionKey);
1525
+ activeWarmEntry = null;
1526
+ }
1527
+ }
1528
+ } else if (existingWarm) {
1529
+ await shutdownAndDisposeSession(existingWarm.session);
1530
+ warmSessions.delete(sessionKey);
1531
+ }
394
1532
 
395
- emit({
1533
+ if (!activeWarmEntry) {
1534
+ const turnHooksRef = { current: currentHooks };
1535
+ const delegatedCladoTools = createCladoPiTools({
1536
+ workspace,
1537
+ stateDir,
1538
+ workspaceService,
1539
+ events,
1540
+ emit: ev => turnHooksRef.current?.emit?.(ev),
1541
+ waitForUserAnswer: (...a) => turnHooksRef.current?.waitForUserAnswer?.(...a),
1542
+ sessionOps: {
1543
+ currentSessionId: cleanId,
1544
+ currentRoleId: role.id,
1545
+ currentRoleName: role.name,
1546
+ list: ({ sinceMinutes = 0, includeArchived = false } = {}) =>
1547
+ listSessions(stateDir, { includeArchived, includeMessages: false, sinceMinutes, agentDir }),
1548
+ read: ({ sessionId: targetId, limit = 12 }) =>
1549
+ readSessionTranscript(stateDir, targetId, { limit, agentDir }),
1550
+ open: ({ roleId: targetRoleId, title = '', reuseLatest = true }) =>
1551
+ openOrCreatePeerSession(stateDir, { roleId: targetRoleId, title, reuseLatest, workspace, agentDir }),
1552
+ send: ({ targetSessionId, targetRoleId, message, wait = false }) =>
1553
+ sendCrossSessionMessage({
1554
+ workspace,
1555
+ stateDir,
1556
+ documentRoot,
1557
+ fromSessionId: cleanId,
1558
+ fromRoleId: role.id,
1559
+ fromRoleName: role.name,
1560
+ targetSessionId,
1561
+ targetRoleId,
1562
+ message,
1563
+ canvas: turnHooksRef.current?.canvas || canvas,
1564
+ wait,
1565
+ }),
1566
+ },
1567
+ automationOps,
1568
+ onCardChanges: (...a) => turnHooksRef.current?.onCardChanges?.(...a),
1569
+ });
1570
+
1571
+ const memoryBundle = readMemoryBundle(workspace, agentDir);
1572
+ const scopedRulesContext = memoryBundle.rules.length
1573
+ ? ['# Project Scoped Rules (.clado/rules/)', ...memoryBundle.rules.map(r => `## Rule: ${r.name}\n${r.content.trim()}`)].join('\n\n')
1574
+ : '';
1575
+ const loader = new DefaultResourceLoader({
1576
+ cwd: workspace,
1577
+ agentDir,
1578
+ settingsManager: sm,
1579
+ noThemes: true,
1580
+ packageCommandOutput: 'capture',
1581
+ extensionFactories: createBuiltInPiExtensions(agentDir, {
1582
+ workspace,
1583
+ getAskUser: () => turnHooksRef.current?.askUser || null,
1584
+ getRoleTools: () => ({ tools: role.tools || [], disabledTools: role.disabledTools || [] }),
1585
+ }),
1586
+ appendSystemPrompt: [
1587
+ role.systemPrompt,
1588
+ platformContext,
1589
+ scopedRulesContext,
1590
+ pluginParamsContext,
1591
+ ].filter(Boolean),
1592
+ });
1593
+ await loader.reload();
1594
+
1595
+ const sessionManager = (piSessionFile && existsSync(piSessionFile))
1596
+ ? SessionManager.open(piSessionFile)
1597
+ : SessionManager.create(workspace, sessionsDir(stateDir));
1598
+ const resolvedFile = sessionManager.getSessionFile?.() || '';
1599
+ if (resolvedFile) {
1600
+ piSessionFile = resolvedFile;
1601
+ upsertSessionMeta(stateDir, { id: cleanId, piSessionFile }, agentDir);
1602
+ }
1603
+
1604
+ const created = await createAgentSession({
1605
+ cwd: workspace,
1606
+ agentDir,
1607
+ modelRuntime: mr,
1608
+ model: chosenModel,
1609
+ settingsManager: sm,
1610
+ resourceLoader: loader,
1611
+ sessionManager,
1612
+ customTools: delegatedCladoTools,
1613
+ });
1614
+ activeWarmEntry = {
1615
+ session: created.session,
1616
+ loader,
1617
+ sm,
1618
+ mr,
1619
+ modelKey: modelOverrideKey,
1620
+ roleId: role.id,
1621
+ agentDir,
1622
+ stateDir,
1623
+ pluginParamsSig: pluginParamsContext,
1624
+ turnHooksRef,
1625
+ needsReload: false,
1626
+ notifications: [],
1627
+ extensionErrors: [],
1628
+ };
1629
+ await bindSessionForClado(created.session, activeWarmEntry);
1630
+ warmSessions.set(sessionKey, activeWarmEntry);
1631
+ }
1632
+
1633
+ session = activeWarmEntry.session;
1634
+ try {
1635
+ const effectiveThink = role.thinkingLevel || runtimeSettings.thinkingLevel;
1636
+ if (effectiveThink && typeof session.setThinkingLevel === 'function') {
1637
+ session.setThinkingLevel(effectiveThink);
1638
+ }
1639
+ } catch {}
1640
+
1641
+ let lastKnownWindowTokens = typeof latestContextUsage?.tokens === 'number' ? latestContextUsage.tokens : 0;
1642
+ let compactedDuringTurn = false;
1643
+
1644
+ const readContextUsageSnapshot = () => {
1645
+ try {
1646
+ const cu = session.getContextUsage?.();
1647
+ const stats = session.getSessionStats?.();
1648
+ const total = cu?.contextWindow || activeCtxWin;
1649
+ let used = lastKnownWindowTokens;
1650
+ if (typeof cu?.tokens === 'number' && Number.isFinite(cu.tokens)) {
1651
+ used = Math.max(0, Math.round(cu.tokens));
1652
+ lastKnownWindowTokens = used;
1653
+ }
1654
+ const usedPercent = typeof cu?.percent === 'number' && Number.isFinite(cu.percent)
1655
+ ? Number(Math.min(100, Math.max(0, cu.percent)).toFixed(1))
1656
+ : Number(Math.min(100, (used / Math.max(1, total)) * 100).toFixed(1));
1657
+ const remainingTokens = Math.max(0, total - used);
1658
+ const remainingPercent = Number(Math.max(0, 100 - usedPercent).toFixed(1));
1659
+ return {
1660
+ tokens: used,
1661
+ contextWindow: total,
1662
+ maxTokens: chosenModel.maxTokens || 16384,
1663
+ remainingTokens,
1664
+ usedPercent,
1665
+ remainingPercent,
1666
+ compactionEnabled: runtimeSettings.compactionEnabled,
1667
+ compactAtPercent: runtimeSettings.compactionTriggerPercent,
1668
+ keepRecentTokens: effectiveKeepRecentTokens,
1669
+ thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
1670
+ transport: runtimeSettings.transport,
1671
+ model: `${chosenModel.provider}/${chosenModel.id}`,
1672
+ totalTokens: stats?.tokens || null,
1673
+ cost: typeof stats?.cost === 'number' ? Number(stats.cost.toFixed(4)) : 0,
1674
+ updatedAt: new Date().toISOString(),
1675
+ };
1676
+ } catch {
1677
+ return null;
1678
+ }
1679
+ };
1680
+
1681
+ emitWrapped({
396
1682
  type: 'model',
397
1683
  provider: chosenModel.provider,
398
1684
  model: chosenModel.id,
1685
+ contextWindow: activeCtxWin,
1686
+ maxTokens: chosenModel.maxTokens || 16384,
1687
+ thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
1688
+ transport: runtimeSettings.transport,
399
1689
  });
1690
+ const initUsage = readContextUsageSnapshot();
1691
+ if (initUsage) {
1692
+ latestContextUsage = initUsage;
1693
+ emitWrapped({ type: 'usage', usage: initUsage });
1694
+ }
1695
+
1696
+ const summarizeToolArgs = (name, args) => {
1697
+ if (!args || typeof args !== 'object') return '';
1698
+ const pick = args.path || args.file_path || args.file || args.command || args.cmd || args.query || args.pattern || args.title || args.heading || args.templateId || '';
1699
+ if (pick) return String(pick).replace(/\s+/g, ' ').trim().slice(0, 110);
1700
+ const keys = Object.keys(args);
1701
+ if (!keys.length) return '';
1702
+ try {
1703
+ return JSON.stringify(args).slice(0, 100);
1704
+ } catch {
1705
+ return '';
1706
+ }
1707
+ };
1708
+ const summarizeToolResult = result => {
1709
+ if (!result) return '';
1710
+ if (typeof result === 'string') return result.trim().slice(0, 360);
1711
+ const blocksList = Array.isArray(result.content) ? result.content : [];
1712
+ const txt = blocksList.filter(b => b?.type === 'text' && b.text).map(b => b.text).join('\n').trim();
1713
+ return txt.slice(0, 360);
1714
+ };
1715
+
1716
+ const activeToolMeta = new Map();
1717
+ const activeCodeMeta = new Map();
1718
+ let lastDraftEmitAt = 0;
1719
+ let cachedCardTitles = null;
1720
+
1721
+ const readCanvasCardTitles = () => {
1722
+ if (cachedCardTitles) return cachedCardTitles;
1723
+ cachedCardTitles = [];
1724
+ if (!canvas?.file || !documentRoot) return cachedCardTitles;
1725
+ try {
1726
+ const full = workspacePath(documentRoot, canvas.file, true);
1727
+ if (existsSync(full)) {
1728
+ const md = readFileSync(full, 'utf8');
1729
+ const matches = md.match(/^#\s+(.+)$/gm) || [];
1730
+ cachedCardTitles = matches.map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
1731
+ }
1732
+ } catch {}
1733
+ return cachedCardTitles;
1734
+ };
1735
+
1736
+ const matchCanvasCardsForCodePath = relPath => {
1737
+ const titles = readCanvasCardTitles();
1738
+ if (!titles.length || !relPath) return [];
1739
+ const base = basename(relPath);
1740
+ const stem = basename(relPath, extname(relPath)).toLowerCase();
1741
+ const relLower = relPath.toLowerCase();
1742
+ const matched = [];
1743
+ for (const t of titles) {
1744
+ const tl = t.toLowerCase();
1745
+ if (
1746
+ (stem.length >= 3 && tl.includes(stem))
1747
+ || tl.includes(base.toLowerCase())
1748
+ || (tl.length >= 4 && relLower.includes(tl.split(/[.#((\s]/)[0]))
1749
+ ) {
1750
+ matched.push([t]);
1751
+ }
1752
+ }
1753
+ return matched.slice(0, 4);
1754
+ };
1755
+
1756
+ const resolveCanvasRelFile = rawPath => {
1757
+ if (!rawPath || !documentRoot) return '';
1758
+ const abs = resolve(workspace, String(rawPath));
1759
+ const docRootAbs = resolve(documentRoot);
1760
+ const rel = relative(docRootAbs, abs).split('\\').join('/');
1761
+ if (!rel || rel.startsWith('..') || !/\.mdc?$/i.test(rel)) return '';
1762
+ return rel;
1763
+ };
1764
+
1765
+ const resolveWorkspaceCodeRel = rawPath => {
1766
+ if (!rawPath || !workspace) return '';
1767
+ if (resolveCanvasRelFile(rawPath)) return '';
1768
+ const wsAbs = resolve(workspace);
1769
+ const abs = resolve(wsAbs, String(rawPath));
1770
+ const rel = relative(wsAbs, abs).split('\\').join('/');
1771
+ if (!rel || rel.startsWith('..') || rel === '.git' || rel.startsWith('.git/')) return '';
1772
+ return { abs, rel };
1773
+ };
1774
+
1775
+ const safeReadCodeSnapshot = abs => {
1776
+ try {
1777
+ if (!existsSync(abs)) return null;
1778
+ const st = statSync(abs);
1779
+ if (!st.isFile() || st.size > 262144) return null;
1780
+ const buf = readFileSync(abs);
1781
+ if (buf.subarray(0, 4096).includes(0)) return null;
1782
+ return buf.toString('utf8');
1783
+ } catch {
1784
+ return null;
1785
+ }
1786
+ };
1787
+
1788
+ const verbForNodeOp = rawOp => {
1789
+ const a = String(rawOp || '').toLowerCase();
1790
+ if (a === 'delete' || a === 'remove') return '正在删除';
1791
+ if (a === 'create' || a === 'add' || a === 'insert' || a === 'append') return '正在新建';
1792
+ if (a === 'move' || a === 'reorder' || a === 'rename') return '正在调整';
1793
+ return '正在编辑';
1794
+ };
1795
+
1796
+ const inferCanvasActivity = (toolName, args) => {
1797
+ if (!args || typeof args !== 'object') return null;
1798
+ if (['clado_nodes', 'clado_links', 'clado_update', 'clado_create'].includes(toolName)) {
1799
+ if (toolName === 'clado_links' && (args.action || 'list') === 'list') return null;
1800
+ const file = String(args.file || canvas?.file || '').trim();
1801
+ const nodes = [];
1802
+ const opGroups = new Map(); // verb -> Set<cardTitle>
1803
+ const addCardVerb = (verb, pathOrTitle) => {
1804
+ const cardTitle = Array.isArray(pathOrTitle)
1805
+ ? String(pathOrTitle[0] || '').trim()
1806
+ : String(pathOrTitle || '').trim();
1807
+ if (!cardTitle) return;
1808
+ if (!opGroups.has(verb)) opGroups.set(verb, new Set());
1809
+ opGroups.get(verb).add(cardTitle);
1810
+ };
1811
+ const defaultVerb = toolName === 'clado_create'
1812
+ ? '正在新建'
1813
+ : toolName === 'clado_links'
1814
+ ? ((args.action === 'remove' || args.action === 'delete') ? '正在移除连线' : '正在连线')
1815
+ : verbForNodeOp(args.action);
1816
+
1817
+ if (Array.isArray(args.node) && args.node.length) {
1818
+ nodes.push(args.node);
1819
+ addCardVerb(defaultVerb, args.node);
1820
+ }
1821
+ if (Array.isArray(args.targetNode) && args.targetNode.length && !args.targetFile) {
1822
+ nodes.push(args.targetNode);
1823
+ addCardVerb(defaultVerb, args.targetNode);
1824
+ }
1825
+ if (Array.isArray(args.operations)) {
1826
+ for (const op of args.operations) {
1827
+ const opVerb = verbForNodeOp(op?.action || op?.op || args.action);
1828
+ if (Array.isArray(op?.node) && op.node.length) {
1829
+ nodes.push(op.node);
1830
+ addCardVerb(opVerb, op.node);
1831
+ } else if (op?.title) {
1832
+ const full = [...(Array.isArray(op.parent) ? op.parent : []), op.title];
1833
+ nodes.push(full);
1834
+ addCardVerb(opVerb, full);
1835
+ }
1836
+ }
1837
+ }
1838
+ if (typeof args.content === 'string') {
1839
+ const h1s = (args.content.match(/^#\s+(.+)$/gm) || []).map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
1840
+ for (const h of h1s.slice(0, 12)) addCardVerb(defaultVerb, h);
1841
+ }
1842
+ const labelTarget = nodes[0]?.at(-1) || args.title || file || '画布';
1843
+ const primaryVerb = opGroups.size === 1 ? Array.from(opGroups.keys())[0] : defaultVerb;
1844
+ return {
1845
+ file,
1846
+ kind: 'editing',
1847
+ nodes: nodes.slice(0, 12),
1848
+ opGroups: Array.from(opGroups.entries()).map(([verb, set]) => ({ verb, cards: Array.from(set) })),
1849
+ label: `AI ${primaryVerb} · ${labelTarget}`,
1850
+ verb: primaryVerb,
1851
+ isDirectFile: false,
1852
+ };
1853
+ }
1854
+ if (['clado_read', 'clado_graph'].includes(toolName)) {
1855
+ const file = String(args.file || canvas?.file || '').trim();
1856
+ return { file, kind: 'read', nodes: [], opGroups: [], verb: '正在查看', label: `AI 正在查看 · ${file || '画布拓扑'}`, isDirectFile: false };
1857
+ }
1858
+ if (['edit', 'write'].includes(toolName)) {
1859
+ const rel = resolveCanvasRelFile(args.path || args.file_path || args.file);
1860
+ if (rel) {
1861
+ return { file: rel, kind: 'editing', nodes: [], opGroups: [], verb: '正在编辑', label: `AI 正在编辑 · ${rel}`, isDirectFile: true };
1862
+ }
1863
+ }
1864
+ return null;
1865
+ };
1866
+
1867
+ const maybeEmitCanvasDraft = msg => {
1868
+ const now = Date.now();
1869
+ if (now - lastDraftEmitAt < 150) return;
1870
+ const content = Array.isArray(msg?.content) ? msg.content : [];
1871
+ let latest = null;
1872
+ for (let i = content.length - 1; i >= 0; i--) {
1873
+ const c = content[i];
1874
+ if (c?.type === 'toolCall' && ['clado_create', 'clado_update', 'clado_nodes'].includes(c.name)) {
1875
+ latest = c;
1876
+ break;
1877
+ }
1878
+ }
1879
+ if (!latest || !latest.arguments || typeof latest.arguments !== 'object') return;
1880
+ const args = latest.arguments;
1881
+ const file = String(args.file || canvas?.file || '').trim();
1882
+ let title = String(args.title || '').trim();
1883
+ let preview = '';
1884
+ if (typeof args.content === 'string' && args.content.trim()) {
1885
+ const lines = args.content.replace(/\r\n?/g, '\n').split('\n');
1886
+ if (!title) {
1887
+ const h1 = [...lines].reverse().find(l => /^#\s+/.test(l));
1888
+ if (h1) title = h1.replace(/^#\s+/, '').trim();
1889
+ }
1890
+ preview = lines.slice(-10).join('\n').trim();
1891
+ } else if (Array.isArray(args.operations) && args.operations.length) {
1892
+ const lastOp = args.operations[args.operations.length - 1];
1893
+ if (lastOp && typeof lastOp === 'object') {
1894
+ title = lastOp.title || (Array.isArray(lastOp.node) ? lastOp.node.at(-1) : '') || title;
1895
+ const bodyStr = String(lastOp.body || lastOp.content || '').trim();
1896
+ if (bodyStr) preview = bodyStr.split('\n').slice(-8).join('\n');
1897
+ }
1898
+ }
1899
+ if (!title && !preview) return;
1900
+ lastDraftEmitAt = now;
1901
+ draftActive = true;
1902
+ events?.emit(workspace, 'canvas.draft', {
1903
+ active: true,
1904
+ toolName: latest.name,
1905
+ file,
1906
+ title: title || file || '新卡片',
1907
+ preview: preview.slice(0, 600),
1908
+ roleName: role.name,
1909
+ });
1910
+ };
400
1911
 
401
1912
  unsub = session.subscribe(ev => {
402
1913
  if (ev.type === 'message_update') {
403
1914
  const ae = ev.assistantMessageEvent;
404
1915
  if (ae?.type === 'text_delta' && ae.delta) {
405
- assistantText += ae.delta;
406
- emit({ type: 'text', text: ae.delta });
1916
+ appendTextDelta(ae.delta);
1917
+ emitWrapped({ type: 'text', text: ae.delta });
407
1918
  } else if (ae?.type === 'thinking_delta' && ae.delta) {
408
- emit({ type: 'thinking', text: ae.delta });
1919
+ appendThinkingDelta(ae.delta);
1920
+ emitWrapped({ type: 'thinking', text: ae.delta });
1921
+ } else if (ae?.type === 'toolcall_delta') {
1922
+ maybeEmitCanvasDraft(ev.message || ae.partial);
409
1923
  }
410
1924
  } 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' });
1925
+ const argsSummary = summarizeToolArgs(ev.toolName, ev.args);
1926
+ const canvasAct = inferCanvasActivity(ev.toolName, ev.args);
1927
+ if (canvasAct) {
1928
+ activeToolMeta.set(ev.toolCallId, canvasAct);
1929
+ events?.emit(workspace, 'agent.activity', {
1930
+ file: canvasAct.file,
1931
+ action: ev.toolName,
1932
+ kind: canvasAct.kind,
1933
+ nodes: canvasAct.nodes,
1934
+ label: canvasAct.label,
1935
+ });
1936
+ if (Array.isArray(canvasAct.opGroups) && canvasAct.opGroups.length) {
1937
+ for (const grp of canvasAct.opGroups) {
1938
+ if (!grp.cards.length) continue;
1939
+ emitPresence({
1940
+ phase: 'active',
1941
+ file: canvasAct.file,
1942
+ cards: grp.cards,
1943
+ label: grp.verb,
1944
+ });
1945
+ }
1946
+ } else {
1947
+ let pCards = canvasAct.nodes
1948
+ .map(n => (Array.isArray(n) ? n[0] : String(n || '')))
1949
+ .map(s => String(s || '').trim())
1950
+ .filter(Boolean);
1951
+ if (!pCards.length) pCards = selectedCardTitles;
1952
+ if (pCards.length) {
1953
+ emitPresence({
1954
+ phase: 'active',
1955
+ file: canvasAct.file,
1956
+ cards: [...new Set(pCards)],
1957
+ label: canvasAct.verb || canvasAct.label.replace(/^AI\s*/, ''),
1958
+ });
1959
+ }
1960
+ }
1961
+ } else if (['edit', 'write', 'read'].includes(ev.toolName)) {
1962
+ const codeTarget = resolveWorkspaceCodeRel(ev.args?.path || ev.args?.file_path || ev.args?.file);
1963
+ if (codeTarget) {
1964
+ const before = ev.toolName === 'read' ? null : safeReadCodeSnapshot(codeTarget.abs);
1965
+ const matchedCards = matchCanvasCardsForCodePath(codeTarget.rel);
1966
+ activeCodeMeta.set(ev.toolCallId, {
1967
+ ...codeTarget,
1968
+ action: ev.toolName,
1969
+ before,
1970
+ matchedCards,
1971
+ });
1972
+ events?.emit(workspace, 'code.activity', {
1973
+ path: codeTarget.rel,
1974
+ action: ev.toolName,
1975
+ phase: ev.toolName === 'read' ? 'reading' : 'editing',
1976
+ matchedCards,
1977
+ roleId: role.id,
1978
+ roleName: role.name,
1979
+ });
1980
+ const codeCards = matchedCards
1981
+ .map(n => (Array.isArray(n) ? n[0] : String(n || '')))
1982
+ .map(s => String(s || '').trim())
1983
+ .filter(Boolean);
1984
+ const presenceCards = codeCards.length ? codeCards : selectedCardTitles;
1985
+ if (presenceCards.length) {
1986
+ emitPresence({
1987
+ phase: 'active',
1988
+ cards: [...new Set(presenceCards)],
1989
+ codePath: codeTarget.rel,
1990
+ label: `${ev.toolName === 'read' ? '正在查看' : '正在修改'} ${codeTarget.rel}`,
1991
+ });
1992
+ }
1993
+ }
1994
+ }
1995
+ upsertToolEntry({
1996
+ id: ev.toolCallId,
1997
+ name: ev.toolName,
1998
+ argsSummary,
1999
+ status: 'running',
2000
+ isError: false,
2001
+ resultPreview: '',
2002
+ });
2003
+ emitWrapped({
2004
+ type: 'tool',
2005
+ id: ev.toolCallId,
2006
+ name: ev.toolName,
2007
+ argsSummary,
2008
+ title: argsSummary ? `${ev.toolName} ${argsSummary}` : ev.toolName,
2009
+ status: 'running',
2010
+ isError: false,
2011
+ });
414
2012
  } 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({
2013
+ const resultPreview = summarizeToolResult(ev.result);
2014
+ const isFailed = Boolean(
2015
+ ev.isError
2016
+ || ev.result?.isError === true
2017
+ || ev.result?.details?.ok === false
2018
+ || resultPreview.startsWith('[TOOL_ERROR]')
2019
+ );
2020
+ if (draftActive && ['clado_create', 'clado_update', 'clado_nodes'].includes(ev.toolName)) {
2021
+ draftActive = false;
2022
+ events?.emit(workspace, 'canvas.draft', { active: false });
2023
+ }
2024
+ const canvasAct = activeToolMeta.get(ev.toolCallId);
2025
+ activeToolMeta.delete(ev.toolCallId);
2026
+ if (canvasAct) {
2027
+ cachedCardTitles = null;
2028
+ if (isFailed) {
2029
+ events?.emit(workspace, 'agent.activity', { file: canvasAct.file, kind: 'clear', nodes: [] });
2030
+ } else if (canvasAct.isDirectFile && canvasAct.file) {
2031
+ events?.emit(workspace, 'doc.updated', {
2032
+ file: canvasAct.file,
2033
+ action: 'update',
2034
+ nodes: [],
2035
+ label: `AI 更新画布 · ${canvasAct.file}`,
2036
+ });
2037
+ }
2038
+ }
2039
+ const codeAct = activeCodeMeta.get(ev.toolCallId);
2040
+ activeCodeMeta.delete(ev.toolCallId);
2041
+ if (!isFailed) markSubstantiveProgress(ev.toolName);
2042
+ if (codeAct && !isFailed && ['edit', 'write'].includes(codeAct.action)) {
2043
+ const after = safeReadCodeSnapshot(codeAct.abs);
2044
+ if (after !== null) {
2045
+ events?.emit(workspace, 'code.diff', {
2046
+ path: codeAct.rel,
2047
+ action: codeAct.action,
2048
+ before: codeAct.before,
2049
+ after,
2050
+ isNew: codeAct.before === null,
2051
+ matchedCards: codeAct.matchedCards,
2052
+ roleId: role.id,
2053
+ roleName: role.name,
2054
+ });
2055
+ }
2056
+ const normRel = String(codeAct.rel || '').replace(/\\/g, '/');
2057
+ if (normRel === 'AGENTS.md' || normRel === '.clado/memory.md' || normRel === 'CLAUDE.md') {
2058
+ emitSystem(workspace, 'memory.updated', {
2059
+ file: normRel,
2060
+ originSessionId: cleanId,
2061
+ originRoleId: role.id,
2062
+ automationRuleId,
2063
+ });
2064
+ } else {
2065
+ emitSystem(workspace, 'code.file_changed', {
2066
+ file: normRel,
2067
+ action: codeAct.action,
2068
+ originSessionId: cleanId,
2069
+ originRoleId: role.id,
2070
+ automationRuleId,
2071
+ });
2072
+ }
2073
+ }
2074
+ const updated = upsertToolEntry({
2075
+ id: ev.toolCallId,
2076
+ name: ev.toolName,
2077
+ status: isFailed ? 'failed' : 'completed',
2078
+ isError: isFailed,
2079
+ resultPreview,
2080
+ });
2081
+ emitWrapped({
418
2082
  type: 'tool',
419
2083
  id: ev.toolCallId,
420
2084
  name: ev.toolName,
421
- title: ev.toolName,
422
- status: ev.isError ? 'failed' : 'completed',
2085
+ argsSummary: updated?.argsSummary || '',
2086
+ resultPreview,
2087
+ title: updated?.argsSummary ? `${ev.toolName} ${updated.argsSummary}` : ev.toolName,
2088
+ status: isFailed ? 'failed' : 'completed',
2089
+ isError: isFailed,
423
2090
  });
2091
+ } else if (ev.type === 'message_end') {
2092
+ const snapUsage = readContextUsageSnapshot();
2093
+ if (snapUsage) {
2094
+ latestContextUsage = snapUsage;
2095
+ emitWrapped({ type: 'usage', usage: snapUsage });
2096
+ }
424
2097
  } else if (ev.type === 'compaction_start') {
425
- emit({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
2098
+ emitWrapped({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
2099
+ } else if (ev.type === 'compaction_end') {
2100
+ const snapUsage = readContextUsageSnapshot();
2101
+ if (snapUsage) {
2102
+ latestContextUsage = snapUsage;
2103
+ emitWrapped({ type: 'usage', usage: snapUsage });
2104
+ }
2105
+ if (!ev.aborted && !ev.errorMessage) {
2106
+ compactedDuringTurn = true;
2107
+ emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
2108
+ emitSystem(workspace, 'context.compacted', {
2109
+ originSessionId: cleanId,
2110
+ originRoleId: role.id,
2111
+ usedPercent: snapUsage?.usedPercent ?? 0,
2112
+ automationRuleId,
2113
+ });
2114
+ }
426
2115
  } else if (ev.type === 'auto_retry_start') {
427
- emit({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
2116
+ emitWrapped({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
428
2117
  }
429
2118
  });
430
2119
 
431
- const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
432
- await session.prompt(promptText);
2120
+ const rawSlash = !handoffFrom && trimmedCommand.startsWith('/');
2121
+ const promptText = rawSlash
2122
+ ? trimmedCommand
2123
+ : buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
2124
+ await session.prompt(promptText, { expandPromptTemplates: true });
2125
+ let finalUsage = readContextUsageSnapshot();
2126
+ if (finalUsage) {
2127
+ latestContextUsage = finalUsage;
2128
+ emitWrapped({ type: 'usage', usage: finalUsage });
2129
+ }
2130
+ // Fallback auto-compaction guarantee: if usage reached configured trigger % and Pi didn't compact during turn, compact now!
2131
+ if (
2132
+ runtimeSettings.compactionEnabled
2133
+ && !abortedByUser
2134
+ && !compactedDuringTurn
2135
+ && finalUsage
2136
+ && finalUsage.usedPercent >= runtimeSettings.compactionTriggerPercent
2137
+ && typeof session.compact === 'function'
2138
+ ) {
2139
+ try {
2140
+ emitWrapped({ type: 'status', text: `上下文已达 ${finalUsage.usedPercent}%(阈值 ${runtimeSettings.compactionTriggerPercent}%),正在自动压缩…` });
2141
+ await session.compact();
2142
+ const postUsage = readContextUsageSnapshot();
2143
+ if (postUsage) {
2144
+ finalUsage = postUsage;
2145
+ latestContextUsage = postUsage;
2146
+ emitWrapped({ type: 'usage', usage: postUsage });
2147
+ }
2148
+ emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
2149
+ emitSystem(workspace, 'context.compacted', {
2150
+ originSessionId: cleanId,
2151
+ originRoleId: role.id,
2152
+ usedPercent: postUsage?.usedPercent ?? 0,
2153
+ automationRuleId,
2154
+ });
2155
+ } catch {}
2156
+ }
433
2157
  }
434
2158
 
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 || '' });
2159
+ persistAssistantTurn({ stopped: abortedByUser });
2160
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser, usage: latestContextUsage });
2161
+ emitSystem(workspace, abortedByUser ? 'session.turn_stopped' : 'session.turn_completed', {
2162
+ originSessionId: cleanId,
2163
+ originRoleId: role.id,
2164
+ roleName: role.name,
2165
+ substantiveToolsCount,
2166
+ automationRuleId,
2167
+ });
453
2168
  } catch (err) {
454
- upsertSessionMeta(stateDir, { id: cleanId, status: 'idle' }, agentDir);
455
- emit({ type: 'error', message: err?.message || 'Pi 执行失败' });
2169
+ if (abortedByUser) {
2170
+ persistAssistantTurn({ stopped: true });
2171
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true, usage: latestContextUsage });
2172
+ emitSystem(workspace, 'session.turn_stopped', {
2173
+ originSessionId: cleanId,
2174
+ originRoleId: role.id,
2175
+ roleName: role.name,
2176
+ substantiveToolsCount,
2177
+ automationRuleId,
2178
+ });
2179
+ } else {
2180
+ const msg = err?.message || 'Pi 执行失败';
2181
+ persistAssistantTurn({ errorMsg: msg });
2182
+ emitWrapped({ type: 'error', message: msg });
2183
+ emitSystem(workspace, 'session.turn_error', {
2184
+ originSessionId: cleanId,
2185
+ originRoleId: role.id,
2186
+ roleName: role.name,
2187
+ error: msg,
2188
+ automationRuleId,
2189
+ });
2190
+ }
456
2191
  } finally {
2192
+ flushSseDelta();
2193
+ if (draftActive) {
2194
+ draftActive = false;
2195
+ events?.emit(workspace, 'canvas.draft', { active: false });
2196
+ }
2197
+ if (presenceTouched) {
2198
+ emitPresence({ phase: 'afterglow', label: '刚刚编辑了', stopped: abortedByUser });
2199
+ }
457
2200
  liveRuns.delete(`${workspace}::${cleanId}`);
458
2201
  try { unsub?.(); } catch {}
459
- try { session?.dispose?.(); } catch {}
2202
+ if (activeWarmEntry) {
2203
+ activeWarmEntry.turnHooksRef.current = null;
2204
+ if (activeWarmEntry.needsReload) {
2205
+ activeWarmEntry.session.reload()
2206
+ .then(() => { activeWarmEntry.needsReload = false; })
2207
+ .catch(() => {});
2208
+ }
2209
+ } else if (session) {
2210
+ await shutdownAndDisposeSession(session);
2211
+ }
460
2212
  }
461
2213
  }
462
2214
 
2215
+ const lastRuntimeSnapshotByWorkspace = new Map();
2216
+
2217
+ const waitBrieflyForMcpTools = async (session, enabledMcpServers, maxWaitMs = 2400) => {
2218
+ const hasDirect = (enabledMcpServers || []).some(s => s.enabled && s.exposure === 'direct');
2219
+ if (!hasDirect) {
2220
+ if ((enabledMcpServers || []).some(s => s.enabled)) {
2221
+ await new Promise(r => setTimeout(r, 250));
2222
+ }
2223
+ return;
2224
+ }
2225
+ const deadline = Date.now() + maxWaitMs;
2226
+ while (Date.now() < deadline) {
2227
+ const tools = session.getActiveToolNames?.() || [];
2228
+ if (tools.some(t => t.startsWith('mcp__'))) {
2229
+ // Give sibling servers a tiny beat to finish too
2230
+ await new Promise(r => setTimeout(r, 150));
2231
+ return;
2232
+ }
2233
+ await new Promise(r => setTimeout(r, 120));
2234
+ }
2235
+ };
2236
+
2237
+ const collectRuntimeSnapshot = (workspace, agentDir, session, loader, entryErrors = [], entryNotes = []) => {
2238
+ const activeTools = session?.getActiveToolNames?.() || [];
2239
+ const allTools = (session?.getAllTools?.() || []).map(t => t.name);
2240
+ const mcpTools = [...new Set([...activeTools, ...allTools])].filter(t => t.startsWith('mcp__'));
2241
+ const extRes = loader?.getExtensions?.() || { extensions: [], errors: [], warnings: [] };
2242
+ const runtimeServers = (extRes?.runtime?.mcpServers?.list?.() || []).map(s => ({
2243
+ name: s.name,
2244
+ config: s.config || {},
2245
+ extensionPath: s.extensionPath || '',
2246
+ extensionName: s.extensionPath ? basename(dirname(s.extensionPath)) || basename(s.extensionPath) : '',
2247
+ }));
2248
+ const mcpServers = listPiMcpServers(workspace, agentDir, { runtimeServers, liveMcpTools: mcpTools });
2249
+ const extensions = (extRes.extensions || []).map(e => e.path || e.resolvedPath || 'extension');
2250
+ const errors = [
2251
+ ...(extRes.errors || []).map(e => `${e.path || 'extension'}: ${e.error}`),
2252
+ ...(extRes.warnings || []).map(w => `${w.path || 'extension'}: ${w.warning}`),
2253
+ ...(entryErrors || []).map(e => e.message),
2254
+ ...(entryNotes || []).filter(n => n.level === 'error' || n.level === 'warning').map(n => n.message),
2255
+ ];
2256
+ const skillsCount = (loader?.getSkills?.()?.skills || []).length;
2257
+ const promptsCount = (loader?.getPrompts?.()?.prompts || []).length;
2258
+ const snap = {
2259
+ reloadedAt: new Date().toISOString(),
2260
+ extensions,
2261
+ runtimeServers,
2262
+ mcpServers,
2263
+ mcpTools,
2264
+ activeTools,
2265
+ allTools,
2266
+ skillsCount,
2267
+ promptsCount,
2268
+ errors: [...new Set(errors)],
2269
+ };
2270
+ lastRuntimeSnapshotByWorkspace.set(workspace, snap);
2271
+ return snap;
2272
+ };
2273
+
2274
+ async function reloadWorkspaceSessions(workspace) {
2275
+ const prefix = workspace ? `${workspace}::` : '';
2276
+ let reloadedCount = 0;
2277
+ let deferredCount = 0;
2278
+ let firstReloadedEntry = null;
2279
+ for (const [key, entry] of warmSessions.entries()) {
2280
+ if (prefix && !key.startsWith(prefix)) continue;
2281
+ if (liveRuns.has(key)) {
2282
+ entry.needsReload = true;
2283
+ deferredCount++;
2284
+ continue;
2285
+ }
2286
+ try {
2287
+ entry.notifications.length = 0;
2288
+ entry.extensionErrors.length = 0;
2289
+ await entry.session.reload();
2290
+ entry.needsReload = false;
2291
+ reloadedCount++;
2292
+ if (!firstReloadedEntry) firstReloadedEntry = entry;
2293
+ } catch {
2294
+ await shutdownAndDisposeSession(entry.session);
2295
+ warmSessions.delete(key);
2296
+ }
2297
+ }
2298
+ if (firstReloadedEntry) {
2299
+ const agentDir = firstReloadedEntry.agentDir || resolvePiAgentDir();
2300
+ await waitBrieflyForMcpTools(firstReloadedEntry.session, listPiMcpServers(workspace, agentDir));
2301
+ collectRuntimeSnapshot(
2302
+ workspace,
2303
+ agentDir,
2304
+ firstReloadedEntry.session,
2305
+ firstReloadedEntry.loader,
2306
+ firstReloadedEntry.extensionErrors,
2307
+ firstReloadedEntry.notifications
2308
+ );
2309
+ }
2310
+ return { reloadedCount, deferredCount };
2311
+ }
2312
+
2313
+ async function reloadSession({ workspace, stateDir, sessionId = '', roleId = 'architect', modelSpec = '' } = {}) {
2314
+ const agentDir = resolvePiAgentDir();
2315
+ const cleanId = sessionId ? safeSessionId(sessionId) : '';
2316
+ const targetKey = cleanId ? `${workspace}::${cleanId}` : '';
2317
+ const mcpServers = listPiMcpServers(workspace, agentDir);
2318
+ let reloadedPeers = 0;
2319
+
2320
+ // 1. Reload other warm sessions in this workspace
2321
+ for (const [key, entry] of warmSessions.entries()) {
2322
+ if (!key.startsWith(`${workspace}::`) || key === targetKey) continue;
2323
+ if (liveRuns.has(key)) {
2324
+ entry.needsReload = true;
2325
+ } else {
2326
+ try {
2327
+ entry.notifications.length = 0;
2328
+ entry.extensionErrors.length = 0;
2329
+ await entry.session.reload();
2330
+ entry.needsReload = false;
2331
+ reloadedPeers++;
2332
+ } catch {
2333
+ await shutdownAndDisposeSession(entry.session);
2334
+ warmSessions.delete(key);
2335
+ }
2336
+ }
2337
+ }
2338
+
2339
+ // 2. If target warm session exists, use Pi's native session.reload()
2340
+ const existing = targetKey ? warmSessions.get(targetKey) : [...warmSessions.entries()].find(([k]) => k.startsWith(`${workspace}::`))?.[1];
2341
+ if (existing && existing.session) {
2342
+ existing.notifications.length = 0;
2343
+ existing.extensionErrors.length = 0;
2344
+ await existing.session.reload();
2345
+ existing.needsReload = false;
2346
+ await waitBrieflyForMcpTools(existing.session, mcpServers);
2347
+ const snap = collectRuntimeSnapshot(workspace, agentDir, existing.session, existing.loader, existing.extensionErrors, existing.notifications);
2348
+ return { ok: true, mode: 'native_session_reload', reloadedPeers, ...snap };
2349
+ }
2350
+
2351
+ // 3. Otherwise create a clean bound session probe (or warm session when sessionId is provided) to load & verify MCP/extensions natively
2352
+ const sm = SettingsManager.create(workspace, agentDir);
2353
+ const loader = new DefaultResourceLoader({
2354
+ cwd: workspace,
2355
+ agentDir,
2356
+ settingsManager: sm,
2357
+ noThemes: true,
2358
+ packageCommandOutput: 'capture',
2359
+ extensionFactories: createBuiltInPiExtensions(agentDir, { workspace }),
2360
+ });
2361
+ await loader.reload();
2362
+
2363
+ let probeSession = null;
2364
+ const probeEntry = { notifications: [], extensionErrors: [], turnHooksRef: { current: null } };
2365
+ try {
2366
+ const mr = await createCladoModelRuntime(agentDir);
2367
+ const chosenModel = await resolvePiModel(mr, sm, modelSpec).catch(() => null);
2368
+ const created = await createAgentSession({
2369
+ cwd: workspace,
2370
+ agentDir,
2371
+ modelRuntime: mr,
2372
+ ...(chosenModel ? { model: chosenModel } : {}),
2373
+ settingsManager: sm,
2374
+ resourceLoader: loader,
2375
+ sessionManager: SessionManager.inMemory(),
2376
+ });
2377
+ probeSession = created.session;
2378
+ await bindSessionForClado(probeSession, probeEntry);
2379
+ await waitBrieflyForMcpTools(probeSession, mcpServers);
2380
+ const snap = collectRuntimeSnapshot(workspace, agentDir, probeSession, loader, probeEntry.extensionErrors, probeEntry.notifications);
2381
+ return { ok: true, mode: 'native_fresh_reload', reloadedPeers, ...snap };
2382
+ } finally {
2383
+ if (probeSession) await shutdownAndDisposeSession(probeSession);
2384
+ }
2385
+ }
2386
+
2387
+ async function disposeWarmSession(workspace, sessionId) {
2388
+ const key = `${workspace}::${safeSessionId(sessionId)}`;
2389
+ const entry = warmSessions.get(key);
2390
+ if (!entry) return false;
2391
+ warmSessions.delete(key);
2392
+ await shutdownAndDisposeSession(entry.session);
2393
+ return true;
2394
+ }
2395
+
2396
+ function inspectRuntime(workspace) {
2397
+ const prefix = workspace ? `${workspace}::` : '';
2398
+ const warmEntries = [...warmSessions.entries()]
2399
+ .filter(([k]) => !prefix || k.startsWith(prefix))
2400
+ .map(([, v]) => v);
2401
+ if (warmEntries.length) {
2402
+ const first = warmEntries[0];
2403
+ const agentDir = first.agentDir || resolvePiAgentDir();
2404
+ const snap = collectRuntimeSnapshot(workspace, agentDir, first.session, first.loader, first.extensionErrors, first.notifications);
2405
+ return { warmSessions: warmEntries.length, ...snap };
2406
+ }
2407
+ const cached = lastRuntimeSnapshotByWorkspace.get(workspace);
2408
+ return cached
2409
+ ? { warmSessions: 0, ...cached }
2410
+ : { warmSessions: 0, mcpTools: [], activeTools: [], extensions: [], errors: [] };
2411
+ }
2412
+
2413
+ async function compactSession({ workspace, stateDir, sessionId, customInstructions = '', allowDuringSelfRun = false }) {
2414
+ const cleanId = safeSessionId(sessionId);
2415
+ const runKey = `${workspace}::${cleanId}`;
2416
+ if (!allowDuringSelfRun && liveRuns.has(runKey)) {
2417
+ throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
2418
+ }
2419
+ const agentDir = resolvePiAgentDir();
2420
+ const meta = getSessionMeta(stateDir, cleanId, agentDir, { messageLimit: 1 });
2421
+ if (!meta) throw new Error('找不到目标会话。');
2422
+ if (!meta.piSessionFile || !existsSync(meta.piSessionFile)) {
2423
+ return { ok: true, skipped: true, reason: '当前会话尚无需要压缩的历史记录。', session: meta };
2424
+ }
2425
+ const sm = SettingsManager.create(workspace, agentDir);
2426
+ const mr = await createCladoModelRuntime(agentDir);
2427
+ const chosenModel = await resolvePiModel(mr, sm, meta.model);
2428
+ if (!chosenModel) throw new Error('尚未配置可用模型,无法执行上下文压缩。');
2429
+
2430
+ const activeCtxWin = chosenModel.contextWindow || 128000;
2431
+ const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
2432
+ const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
2433
+ const effectiveKeepRecentTokens = Math.min(
2434
+ runtimeSettings.keepRecentTokens,
2435
+ Math.max(4096, Math.floor(Math.max(8192, activeCtxWin - effectiveReserveTokens) * 0.45))
2436
+ );
2437
+ sm.applyOverrides({
2438
+ compaction: {
2439
+ enabled: runtimeSettings.compactionEnabled,
2440
+ reserveTokens: effectiveReserveTokens,
2441
+ keepRecentTokens: effectiveKeepRecentTokens,
2442
+ },
2443
+ });
2444
+ const loader = new DefaultResourceLoader({ cwd: workspace, agentDir, settingsManager: sm, noThemes: true });
2445
+ await loader.reload();
2446
+ const sessionManager = SessionManager.open(meta.piSessionFile);
2447
+ const created = await createAgentSession({
2448
+ cwd: workspace,
2449
+ agentDir,
2450
+ modelRuntime: mr,
2451
+ model: chosenModel,
2452
+ settingsManager: sm,
2453
+ resourceLoader: loader,
2454
+ sessionManager,
2455
+ });
2456
+ const session = created.session;
2457
+ try {
2458
+ await session.compact(customInstructions || undefined);
2459
+ const cu = session.getContextUsage?.();
2460
+ const total = cu?.contextWindow || activeCtxWin;
2461
+ const used = typeof cu?.tokens === 'number' ? cu.tokens : 0;
2462
+ const usedPercent = typeof cu?.percent === 'number' ? Number(cu.percent.toFixed(1)) : Number(((used / Math.max(1, total)) * 100).toFixed(1));
2463
+ const contextUsage = {
2464
+ tokens: used,
2465
+ contextWindow: total,
2466
+ maxTokens: chosenModel.maxTokens || 16384,
2467
+ remainingTokens: Math.max(0, total - used),
2468
+ usedPercent,
2469
+ remainingPercent: Number(Math.max(0, 100 - usedPercent).toFixed(1)),
2470
+ compactionEnabled: runtimeSettings.compactionEnabled,
2471
+ compactAtPercent: runtimeSettings.compactionTriggerPercent,
2472
+ keepRecentTokens: effectiveKeepRecentTokens,
2473
+ thinkingLevel: runtimeSettings.thinkingLevel,
2474
+ transport: runtimeSettings.transport,
2475
+ model: `${chosenModel.provider}/${chosenModel.id}`,
2476
+ updatedAt: new Date().toISOString(),
2477
+ };
2478
+ const updated = upsertSessionMeta(stateDir, { id: cleanId, contextUsage }, agentDir);
2479
+ emitSystem(workspace, 'context.compacted', {
2480
+ originSessionId: cleanId,
2481
+ originRoleId: meta.roleId,
2482
+ usedPercent,
2483
+ });
2484
+ return { ok: true, contextUsage, session: updated };
2485
+ } finally {
2486
+ await shutdownAndDisposeSession(session);
2487
+ }
2488
+ }
2489
+
2490
+ function overlayLiveSession(workspace, item) {
2491
+ if (!item || !item.id) return item;
2492
+ const run = liveRuns.get(`${workspace}::${item.id}`);
2493
+ if (!run || typeof run.getLiveAssistant !== 'function') return item;
2494
+ const liveMsg = run.getLiveAssistant();
2495
+ const msgs = Array.isArray(item.messages) ? item.messages.slice() : null;
2496
+ if (msgs && !msgs.some(m => m && (m.id === liveMsg.id || m.turnId === liveMsg.turnId))) {
2497
+ msgs.push(liveMsg);
2498
+ }
2499
+ return {
2500
+ ...item,
2501
+ status: 'running',
2502
+ ...(msgs ? { messages: msgs } : {}),
2503
+ };
2504
+ }
2505
+
463
2506
  return {
464
2507
  runTurn,
2508
+ compactSession,
2509
+ reloadSession,
2510
+ reloadWorkspaceSessions,
2511
+ disposeWarmSession,
2512
+ inspectRuntime,
2513
+ sendCrossSessionMessage,
2514
+ readSessionTranscript,
2515
+ openOrCreatePeerSession,
2516
+ overlayLiveSession,
2517
+ overlayLiveSessions(workspace, list) {
2518
+ return Array.isArray(list) ? list.map(s => overlayLiveSession(workspace, s)) : [];
2519
+ },
2520
+ listActiveRuns(workspace) {
2521
+ const prefix = workspace ? `${workspace}::` : '';
2522
+ return [...liveRuns.entries()]
2523
+ .filter(([k]) => !prefix || k.startsWith(prefix))
2524
+ .map(([, v]) => v.sessionId);
2525
+ },
465
2526
  answer(workspace, sessionId, questionId, answerText) {
466
2527
  const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
467
2528
  return run ? run.answer(questionId, answerText) : false;
@@ -478,10 +2539,21 @@ export function createPiBridge({
478
2539
  }
479
2540
  return false;
480
2541
  },
2542
+ async abortAllRuns(workspace) {
2543
+ const prefix = workspace ? `${workspace}::` : '';
2544
+ const targets = [...liveRuns.entries()]
2545
+ .filter(([k]) => !prefix || k.startsWith(prefix))
2546
+ .map(([, v]) => v);
2547
+ await Promise.allSettled(targets.map(r => r.abort()));
2548
+ return targets.length;
2549
+ },
481
2550
  async closeAll() {
482
- const all = [...liveRuns.values()];
2551
+ const allRuns = [...liveRuns.values()];
483
2552
  liveRuns.clear();
484
- await Promise.allSettled(all.map(r => r.abort()));
2553
+ await Promise.allSettled(allRuns.map(r => r.abort()));
2554
+ const allWarm = [...warmSessions.values()];
2555
+ warmSessions.clear();
2556
+ await Promise.allSettled(allWarm.map(e => shutdownAndDisposeSession(e.session)));
485
2557
  },
486
2558
  };
487
2559
  }