cladogram 0.6.0-beta.4 → 0.6.0-beta.6

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.
@@ -39,6 +39,74 @@ function indexFile(stateDir) {
39
39
  return join(sessionsDir(stateDir), 'index.json');
40
40
  }
41
41
 
42
+ function sessionMessagesFile(stateDir, id) {
43
+ return join(sessionsDir(stateDir), safeSessionId(id) + '.messages.json');
44
+ }
45
+
46
+ function summarizeMessagePreview(msgs) {
47
+ if (!Array.isArray(msgs) || !msgs.length) return '';
48
+ const last = msgs[msgs.length - 1];
49
+ const raw = String(last?.text || '').replace(/\s+/g, ' ').trim();
50
+ return raw.slice(0, 100);
51
+ }
52
+
53
+ export function readSessionMessages(stateDir, id, inlineFallback = null) {
54
+ const file = sessionMessagesFile(stateDir, id);
55
+ if (existsSync(file)) {
56
+ try {
57
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
58
+ if (Array.isArray(parsed)) return parsed;
59
+ } catch {}
60
+ }
61
+ return Array.isArray(inlineFallback) ? inlineFallback : [];
62
+ }
63
+
64
+ function writeSessionMessages(stateDir, id, messages) {
65
+ const clean = Array.isArray(messages) ? messages : [];
66
+ writeFileSync(sessionMessagesFile(stateDir, id), JSON.stringify(clean, null, 2) + '\n', 'utf8');
67
+ return clean;
68
+ }
69
+
70
+ export function readSessionMessagesPage(stateDir, id, { limit = 30, before = null, inlineFallback = null } = {}) {
71
+ const all = readSessionMessages(stateDir, id, inlineFallback);
72
+ const totalMessages = all.length;
73
+ const maxLimit = Math.max(1, Math.min(200, Math.round(Number(limit) || 30)));
74
+ const end = (before !== null && before !== undefined && Number.isFinite(Number(before)))
75
+ ? Math.max(0, Math.min(totalMessages, Math.floor(Number(before))))
76
+ : totalMessages;
77
+ const start = Math.max(0, end - maxLimit);
78
+ return {
79
+ messages: all.slice(start, end),
80
+ totalMessages,
81
+ oldestIndex: start,
82
+ endIndex: end,
83
+ hasMoreBefore: start > 0,
84
+ };
85
+ }
86
+
87
+ function hydrateSessionView(stateDir, meta, { messageLimit = 30, includeMessages = true } = {}) {
88
+ if (!meta) return null;
89
+ if (!includeMessages) {
90
+ const { messages: _omit, ...rest } = meta;
91
+ return {
92
+ ...rest,
93
+ messageCount: typeof meta.messageCount === 'number' ? meta.messageCount : readSessionMessages(stateDir, meta.id, meta.messages).length,
94
+ };
95
+ }
96
+ const page = readSessionMessagesPage(stateDir, meta.id, {
97
+ limit: messageLimit,
98
+ inlineFallback: meta.messages,
99
+ });
100
+ return {
101
+ ...meta,
102
+ messages: page.messages,
103
+ messageCount: page.totalMessages,
104
+ totalMessages: page.totalMessages,
105
+ oldestIndex: page.oldestIndex,
106
+ hasMoreBefore: page.hasMoreBefore,
107
+ };
108
+ }
109
+
42
110
  function readIndex(stateDir) {
43
111
  const file = indexFile(stateDir);
44
112
  if (!existsSync(file)) return [];
@@ -51,12 +119,32 @@ function readIndex(stateDir) {
51
119
  }
52
120
 
53
121
  function writeIndex(stateDir, list) {
54
- writeFileSync(indexFile(stateDir), JSON.stringify(list, null, 2) + '\n', 'utf8');
122
+ const slim = list.map(item => {
123
+ const { messages: _inline, ...rest } = item;
124
+ return rest;
125
+ });
126
+ writeFileSync(indexFile(stateDir), JSON.stringify(slim, null, 2) + '\n', 'utf8');
55
127
  }
56
128
 
57
129
  export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir()) {
58
130
  let list = readIndex(stateDir);
59
- if (list.length > 0) return list;
131
+ if (list.length > 0) {
132
+ // One-time transparent migration if legacy inline messages exist inside index.json
133
+ let migrated = false;
134
+ for (const item of list) {
135
+ if (Array.isArray(item.messages) && item.messages.length > 0) {
136
+ if (!existsSync(sessionMessagesFile(stateDir, item.id))) {
137
+ writeSessionMessages(stateDir, item.id, item.messages);
138
+ }
139
+ item.messageCount = item.messages.length;
140
+ item.lastMessagePreview = item.lastMessagePreview || summarizeMessagePreview(item.messages);
141
+ delete item.messages;
142
+ migrated = true;
143
+ }
144
+ }
145
+ if (migrated) writeIndex(stateDir, list);
146
+ return list;
147
+ }
60
148
  const now = new Date().toISOString();
61
149
  const defaults = ['architect', 'developer', 'tester'].map(roleId => {
62
150
  const role = resolveRole(roleId, agentDir);
@@ -71,9 +159,10 @@ export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir())
71
159
  archived: false,
72
160
  status: 'idle',
73
161
  summaryBadge: '',
162
+ messageCount: 0,
163
+ lastMessagePreview: '',
74
164
  createdAt: now,
75
165
  updatedAt: now,
76
- messages: [],
77
166
  snapshots: [],
78
167
  };
79
168
  });
@@ -81,14 +170,38 @@ export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir())
81
170
  return defaults;
82
171
  }
83
172
 
84
- export function listSessions(stateDir, { includeArchived = false, agentDir = resolvePiAgentDir() } = {}) {
173
+ export function listSessions(stateDir, { includeArchived = false, includeMessages = true, messageLimit = 30, sinceMinutes = 0, agentDir = resolvePiAgentDir() } = {}) {
85
174
  const list = ensureDefaultSessions(stateDir, agentDir);
86
- return includeArchived ? list : list.filter(s => !s.archived);
175
+ const cutoffMs = (typeof sinceMinutes === 'number' && sinceMinutes > 0)
176
+ ? (Date.now() - sinceMinutes * 60_000)
177
+ : 0;
178
+ return list
179
+ .filter(s => includeArchived || !s.archived)
180
+ .filter(s => {
181
+ if (!cutoffMs) return true;
182
+ const uMs = s.updatedAt ? Date.parse(s.updatedAt) : 0;
183
+ const count = typeof s.messageCount === 'number' ? s.messageCount : readSessionMessages(stateDir, s.id).length;
184
+ return count > 0 && uMs >= cutoffMs;
185
+ })
186
+ .map(s => hydrateSessionView(stateDir, s, { includeMessages, messageLimit }));
87
187
  }
88
188
 
89
- export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir()) {
189
+ export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir(), { messageLimit = 30, includeAll = false } = {}) {
90
190
  const list = ensureDefaultSessions(stateDir, agentDir);
91
- return list.find(s => s.id === id) || null;
191
+ const found = list.find(s => s.id === id) || null;
192
+ if (!found) return null;
193
+ if (includeAll) {
194
+ const all = readSessionMessages(stateDir, found.id, found.messages);
195
+ return {
196
+ ...found,
197
+ messages: all,
198
+ messageCount: all.length,
199
+ totalMessages: all.length,
200
+ oldestIndex: 0,
201
+ hasMoreBefore: false,
202
+ };
203
+ }
204
+ return hydrateSessionView(stateDir, found, { includeMessages: true, messageLimit });
92
205
  }
93
206
 
94
207
  export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir()) {
@@ -97,14 +210,26 @@ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(
97
210
  const idx = list.findIndex(s => s.id === id);
98
211
  const role = resolveRole(patch.roleId || list[idx]?.roleId || 'architect', agentDir);
99
212
  const now = new Date().toISOString();
213
+
214
+ let messageCount = idx >= 0 ? (list[idx].messageCount ?? readSessionMessages(stateDir, id).length) : 0;
215
+ let lastMessagePreview = idx >= 0 ? (list[idx].lastMessagePreview || '') : '';
216
+ if (Array.isArray(patch.messages)) {
217
+ writeSessionMessages(stateDir, id, patch.messages);
218
+ messageCount = patch.messages.length;
219
+ lastMessagePreview = summarizeMessagePreview(patch.messages);
220
+ }
221
+ const { messages: _omitMessages, ...patchRest } = patch;
222
+
100
223
  const next = idx >= 0
101
224
  ? {
102
225
  ...list[idx],
103
- ...patch,
226
+ ...patchRest,
104
227
  id,
105
228
  roleId: role.id,
106
229
  tone: patch.tone || list[idx].tone || role.tone,
107
230
  phase: patch.phase || list[idx].phase || role.phase,
231
+ messageCount,
232
+ lastMessagePreview,
108
233
  updatedAt: now,
109
234
  }
110
235
  : {
@@ -118,15 +243,16 @@ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(
118
243
  archived: false,
119
244
  status: 'idle',
120
245
  summaryBadge: '',
246
+ messageCount,
247
+ lastMessagePreview,
121
248
  createdAt: now,
122
249
  updatedAt: now,
123
- messages: [],
124
250
  snapshots: [],
125
251
  };
126
252
  if (idx >= 0) list[idx] = next;
127
253
  else list.push(next);
128
254
  writeIndex(stateDir, list);
129
- return next;
255
+ return hydrateSessionView(stateDir, next, { includeMessages: true, messageLimit: 30 });
130
256
  }
131
257
 
132
258
  export function renameSession(stateDir, id, title, agentDir = resolvePiAgentDir()) {
@@ -138,7 +264,7 @@ export function renameSession(stateDir, id, title, agentDir = resolvePiAgentDir(
138
264
  item.title = cleanTitle;
139
265
  item.updatedAt = new Date().toISOString();
140
266
  writeIndex(stateDir, list);
141
- return item;
267
+ return hydrateSessionView(stateDir, item, { includeMessages: true, messageLimit: 30 });
142
268
  }
143
269
 
144
270
  export function archiveSession(stateDir, id, archived = true, agentDir = resolvePiAgentDir()) {
@@ -148,7 +274,7 @@ export function archiveSession(stateDir, id, archived = true, agentDir = resolve
148
274
  item.archived = Boolean(archived);
149
275
  item.updatedAt = new Date().toISOString();
150
276
  writeIndex(stateDir, list);
151
- return item;
277
+ return hydrateSessionView(stateDir, item, { includeMessages: true, messageLimit: 30 });
152
278
  }
153
279
 
154
280
  export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
@@ -156,7 +282,11 @@ export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
156
282
  const target = list.find(s => s.id === id);
157
283
  const next = list.filter(s => s.id !== id);
158
284
  writeIndex(stateDir, next);
159
- for (const candidate of [target?.piSessionFile, join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl')]) {
285
+ for (const candidate of [
286
+ target?.piSessionFile,
287
+ join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl'),
288
+ sessionMessagesFile(stateDir, id),
289
+ ]) {
160
290
  if (candidate && existsSync(candidate)) {
161
291
  try { rmSync(candidate, { force: true }); } catch {}
162
292
  }
@@ -197,11 +327,160 @@ export function restoreCanvasSnapshot(documentRoot, stateDir, sessionId, snapsho
197
327
  return { ok: true, file: snap.file, snapshotId: snap.id };
198
328
  }
199
329
 
200
- export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom }) {
330
+ const BUILTIN_SLASH_PROMPTS = {
331
+ arch: '请分析当前工作区源码或目标模块,梳理清晰的架构边界、核心调用链与数据契约,并直接在 Clado 画布中绘制或更新结构化卡片与单向 DAG 连线。',
332
+ review: '请对当前画布、选中卡片或关联代码进行深度工程评审:逐项核查边界条件、数据一致性、并发安全、异常兜底与可维护性,给出具体可落地的改进建议。',
333
+ test: '请基于当前画布链路与源码边界,系统设计单元测试、边界条件、异常分支与回归测试矩阵;如已有代码实现,直接补充可运行测试并验证结果。',
334
+ diff: '请检查当前工作区 Git Diff 与改动源码,逐项对照画布契约验收实现完整性与潜在回归风险,并同步更新画布卡片状态。',
335
+ svg: '请为当前方案或需求设计一张清晰美观、结构分明的矢量架构图/流程图/时序图,在画布卡片中使用标准 ```svg 代码块(包含完整 viewBox 与 xmlns="http://www.w3.org/2000/svg")呈现。',
336
+ ui: '请为当前需求设计高保真交互式界面原型,在画布卡片中使用标准 ```ui 代码块呈现清晰布局、交互态与关键状态切换。',
337
+ };
338
+
339
+ function stripFrontmatter(raw) {
340
+ const s = String(raw || '').replace(/\r\n?/g, '\n');
341
+ const m = s.match(/^---\n[\s\S]*?\n---\n?/);
342
+ return (m ? s.slice(m[0].length) : s).trim();
343
+ }
344
+
345
+ function substitutePromptArgs(template, rawArgs) {
346
+ const argsStr = String(rawArgs || '').trim();
347
+ const tokens = argsStr ? (argsStr.match(/"[^"]*"|'[^']*'|\S+/g) || []).map(t => t.replace(/^["']|["']$/g, '')) : [];
348
+ let out = String(template || '');
349
+ let usedPlaceholder = false;
350
+ out = out.replace(/\{\{\s*args\s*\}\}|\$ARGUMENTS|\$@/g, () => {
351
+ usedPlaceholder = true;
352
+ return argsStr;
353
+ });
354
+ out = out.replace(/\$(\d+)/g, (_, idxStr) => {
355
+ usedPlaceholder = true;
356
+ const idx = Number(idxStr) - 1;
357
+ return tokens[idx] ?? '';
358
+ });
359
+ if (!usedPlaceholder && argsStr) {
360
+ out = out + '\n\n补充要求:' + argsStr;
361
+ }
362
+ return out.trim();
363
+ }
364
+
365
+ export function expandSlashPrompt(rawText, { workspace = '', agentDir = resolvePiAgentDir() } = {}) {
366
+ const clean = String(rawText || '').trim();
367
+ const match = clean.match(/^\/([a-zA-Z0-9_:-]+)(?:\s+([\s\S]*))?$/);
368
+ if (!match) return { expanded: false, text: clean, command: '' };
369
+ const cmd = match[1].toLowerCase();
370
+ const restArgs = (match[2] || '').trim();
371
+
372
+ // 1. /skill:<name> -> locate SKILL.md and instruct Pi to load/apply it
373
+ if (cmd.startsWith('skill:')) {
374
+ const skillName = cmd.slice('skill:'.length).trim();
375
+ if (!skillName || skillName.includes('..') || skillName.includes('/')) {
376
+ return { expanded: false, text: clean, command: '' };
377
+ }
378
+ const candidates = [
379
+ workspace ? join(workspace, '.pi', 'skills', skillName, 'SKILL.md') : '',
380
+ workspace ? join(workspace, '.clado', 'skills', skillName, 'SKILL.md') : '',
381
+ join(agentDir, 'skills', skillName, 'SKILL.md'),
382
+ ].filter(Boolean);
383
+ const found = candidates.find(p => existsSync(p));
384
+ const guide = found
385
+ ? `请严格按照技能 \`${skillName}\` 的指南执行(技能文件:${found},可先 read 该文件获取完整规范)。`
386
+ : `请优先加载并遵循名为 \`${skillName}\` 的技能规范来执行本任务。`;
387
+ return {
388
+ expanded: true,
389
+ command: '/' + cmd,
390
+ text: restArgs ? `${guide}\n\n用户任务:${restArgs}` : guide,
391
+ };
392
+ }
393
+
394
+ // 2. Project / User Pi prompt templates (.pi/prompts/<cmd>.md or ~/.pi/agent/prompts/<cmd>.md)
395
+ if (!cmd.includes('..') && !cmd.includes('/') && !cmd.includes(':')) {
396
+ const promptCandidates = [
397
+ workspace ? join(workspace, '.pi', 'prompts', cmd + '.md') : '',
398
+ join(agentDir, 'prompts', cmd + '.md'),
399
+ ].filter(Boolean);
400
+ const promptFile = promptCandidates.find(p => existsSync(p));
401
+ if (promptFile) {
402
+ try {
403
+ const body = stripFrontmatter(readFileSync(promptFile, 'utf8'));
404
+ if (body) {
405
+ return {
406
+ expanded: true,
407
+ command: '/' + cmd,
408
+ text: substitutePromptArgs(body, restArgs),
409
+ };
410
+ }
411
+ } catch {}
412
+ }
413
+ }
414
+
415
+ // 3. Built-in Clado slash prompt commands (/arch, /review, /test, /diff, /svg, /ui)
416
+ if (Object.prototype.hasOwnProperty.call(BUILTIN_SLASH_PROMPTS, cmd)) {
417
+ const base = BUILTIN_SLASH_PROMPTS[cmd];
418
+ return {
419
+ expanded: true,
420
+ command: '/' + cmd,
421
+ text: restArgs ? `${base}\n\n补充要求:${restArgs}` : base,
422
+ };
423
+ }
424
+
425
+ return { expanded: false, text: clean, command: '' };
426
+ }
427
+
428
+ function extractAtMentions(rawText, workspace) {
429
+ const s = String(rawText || '');
430
+ if (!s.includes('@')) return { cards: [], docs: [], files: [] };
431
+ const cards = [];
432
+ const docs = [];
433
+ const files = [];
434
+ const seenCard = new Set();
435
+ const seenDoc = new Set();
436
+ const seenFile = new Set();
437
+
438
+ // @[卡片:标题] or @卡片:标题
439
+ for (const m of s.matchAll(/@\[卡片:([^\]]+)\]/g)) {
440
+ const name = String(m[1] || '').trim();
441
+ if (name && !seenCard.has(name)) {
442
+ seenCard.add(name);
443
+ cards.push(name);
444
+ }
445
+ }
446
+ // @doc:path/to/file.md
447
+ for (const m of s.matchAll(/(?:^|[\s((【])@doc:([^\s))】]+)/g)) {
448
+ const doc = String(m[1] || '').trim();
449
+ if (doc && !seenDoc.has(doc)) {
450
+ seenDoc.add(doc);
451
+ docs.push(doc);
452
+ }
453
+ }
454
+ // @relative/path.ext (verify existence inside workspace to avoid matching emails)
455
+ if (workspace) {
456
+ const wsRoot = resolve(workspace);
457
+ for (const m of s.matchAll(/(?:^|[\s((【])@([a-zA-Z0-9._/-]+\.[a-zA-Z0-9_-]+)/g)) {
458
+ const rel = String(m[1] || '').replace(/^\/+/, '');
459
+ if (!rel || rel.startsWith('doc:') || rel.includes('..') || seenFile.has(rel)) continue;
460
+ try {
461
+ const abs = resolve(wsRoot, rel);
462
+ if ((abs === wsRoot || abs.startsWith(wsRoot + '/')) && existsSync(abs) && statSync(abs).isFile()) {
463
+ seenFile.add(rel);
464
+ files.push(rel);
465
+ }
466
+ } catch {}
467
+ }
468
+ }
469
+ return { cards, docs, files };
470
+ }
471
+
472
+ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir = resolvePiAgentDir() }) {
473
+ const slashResult = expandSlashPrompt(text, { workspace, agentDir });
474
+ const finalUserText = slashResult.text;
475
+ const mentions = extractAtMentions(text, workspace);
476
+
201
477
  const lines = [];
202
478
  if (handoffFrom) {
203
479
  lines.push(`[设计交付交接 · 来自「${handoffFrom}」]`);
204
480
  }
481
+ if (slashResult.expanded) {
482
+ lines.push(`已触发斜杠命令:${slashResult.command}`);
483
+ }
205
484
  if (canvas?.file) {
206
485
  lines.push(`当前画布文件:${canvas.file}`);
207
486
  if (Array.isArray(canvas.selection) && canvas.selection.length) {
@@ -220,10 +499,19 @@ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFr
220
499
  lines.push(`用户框选的精确片段${nodeLabel ? `(位于 ${nodeLabel})` : ''}:「${quoted}」`);
221
500
  }
222
501
  }
502
+ if (mentions.cards.length) {
503
+ lines.push(`用户通过 @ 引用的画布卡片:${mentions.cards.join(';')}`);
504
+ }
505
+ if (mentions.docs.length) {
506
+ lines.push(`用户通过 @ 引用的画布文档:${mentions.docs.join(';')}`);
507
+ }
508
+ if (mentions.files.length) {
509
+ lines.push(`用户通过 @ 引用的工作区文件(请优先 read 查看):${mentions.files.join(';')}`);
510
+ }
223
511
  if (lines.length) {
224
- return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${text}`;
512
+ return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${finalUserText}`;
225
513
  }
226
- return text;
514
+ return finalUserText;
227
515
  }
228
516
 
229
517
  async function resolvePiModel(modelRuntime, settingsManager, requestedSpec) {
@@ -268,8 +556,178 @@ export function createPiBridge({
268
556
  workspaceService = null,
269
557
  events = null,
270
558
  sessionFactory = null,
559
+ onSystemEvent = null,
560
+ automationOps = null,
271
561
  } = {}) {
272
562
  const liveRuns = new Map();
563
+ const pairNoProgressStreak = new Map(); // sorted pair key -> consecutive no-progress cross-session sends
564
+ const SUBSTANTIVE_TOOLS = new Set([
565
+ 'clado_create', 'clado_update', 'clado_nodes', 'clado_links', 'clado_documents', 'clado_batch',
566
+ 'edit', 'write', 'bash', 'ask_user', 'canvas_objects_upsert', 'canvas_objects_delete',
567
+ ]);
568
+ const pairKeyOf = (a, b) => [String(a || ''), String(b || '')].sort().join('::');
569
+ const resetProgressForSession = sid => {
570
+ const clean = String(sid || '');
571
+ if (!clean) return;
572
+ for (const k of pairNoProgressStreak.keys()) {
573
+ if (k.startsWith(clean + '::') || k.endsWith('::' + clean)) {
574
+ pairNoProgressStreak.set(k, 0);
575
+ }
576
+ }
577
+ };
578
+ const emitSystem = (workspace, eventType, payload = {}) => {
579
+ try { onSystemEvent?.(workspace, eventType, payload); } catch {}
580
+ };
581
+
582
+ function readSessionTranscript(stateDir, targetId, { limit = 12, agentDir = resolvePiAgentDir() } = {}) {
583
+ const cleanTarget = safeSessionId(targetId);
584
+ const meta = getSessionMeta(stateDir, cleanTarget, agentDir, { messageLimit: 1 });
585
+ if (!meta) return null;
586
+ const page = readSessionMessagesPage(stateDir, cleanTarget, { limit: Math.max(1, Math.min(60, Number(limit) || 12)) });
587
+ return {
588
+ session: {
589
+ id: meta.id,
590
+ title: meta.title,
591
+ roleId: meta.roleId,
592
+ phase: meta.phase,
593
+ status: meta.status,
594
+ updatedAt: meta.updatedAt,
595
+ messageCount: page.totalMessages,
596
+ },
597
+ totalMessages: page.totalMessages,
598
+ oldestIndex: page.oldestIndex,
599
+ hasMoreBefore: page.hasMoreBefore,
600
+ messages: page.messages.map(m => ({
601
+ role: m.role,
602
+ timestamp: m.timestamp,
603
+ fromRoleName: m.handoffFrom || m.fromRoleName || '',
604
+ text: String(m.text || '').slice(0, 1200),
605
+ tools: Array.isArray(m.tools) ? m.tools.map(t => ({ name: t.name, argsSummary: t.argsSummary || '', status: t.status || 'completed' })) : [],
606
+ })),
607
+ };
608
+ }
609
+
610
+ function openOrCreatePeerSession(stateDir, { roleId = 'architect', title = '', reuseLatest = true, agentDir = resolvePiAgentDir() } = {}) {
611
+ const role = resolveRole(roleId, agentDir);
612
+ if (reuseLatest) {
613
+ const existing = listSessions(stateDir, { includeArchived: false, includeMessages: false, agentDir })
614
+ .filter(s => s.roleId === role.id)
615
+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')))[0];
616
+ if (existing) return { session: existing, created: false };
617
+ }
618
+ const created = upsertSessionMeta(stateDir, {
619
+ roleId: role.id,
620
+ title: String(title || role.name).trim(),
621
+ }, agentDir);
622
+ return { session: created, created: true };
623
+ }
624
+
625
+ async function sendCrossSessionMessage({
626
+ workspace,
627
+ stateDir,
628
+ documentRoot,
629
+ fromSessionId = '',
630
+ fromRoleId = '',
631
+ fromRoleName = '同伴角色',
632
+ targetSessionId = '',
633
+ targetRoleId = '',
634
+ message = '',
635
+ canvas = null,
636
+ wait = false,
637
+ automationRuleId = '',
638
+ }) {
639
+ const cleanMsg = String(message || '').trim();
640
+ if (!cleanMsg) throw new Error('跨会话消息内容不能为空。');
641
+ const agentDir = resolvePiAgentDir();
642
+ let targetMeta = targetSessionId ? getSessionMeta(stateDir, safeSessionId(targetSessionId), agentDir, { messageLimit: 1 }) : null;
643
+ if (!targetMeta && targetRoleId) {
644
+ targetMeta = openOrCreatePeerSession(stateDir, { roleId: targetRoleId, reuseLatest: true, agentDir }).session;
645
+ }
646
+ if (!targetMeta) throw new Error('找不到目标主会话,请传入有效的 sessionId 或 roleId。');
647
+ if (fromSessionId && safeSessionId(fromSessionId) === targetMeta.id) {
648
+ throw new Error('不能给自己发送跨会话协作消息。');
649
+ }
650
+
651
+ // Progress-based anti-ping-pong guard (only trips after 3 consecutive no-progress bounces; resets on any substantive tool call!)
652
+ if (fromSessionId && !automationRuleId) {
653
+ const pKey = pairKeyOf(safeSessionId(fromSessionId), targetMeta.id);
654
+ const streak = (pairNoProgressStreak.get(pKey) || 0) + 1;
655
+ if (streak > 3) {
656
+ events?.emit(workspace, 'agent.sessions', { action: 'circuit_broken', fromSessionId, targetSessionId: targetMeta.id });
657
+ return {
658
+ ok: false,
659
+ circuitBroken: true,
660
+ targetSessionId: targetMeta.id,
661
+ message: `检测到「${fromRoleName}」与「${targetMeta.title}」连续 3 轮跨会话互发消息且无实质工具产出,已自动熔断防原地打转;请总结当前进展并交由用户确认或直接执行具体操作后再沟通。`,
662
+ };
663
+ }
664
+ pairNoProgressStreak.set(pKey, streak);
665
+ }
666
+
667
+ const formatted = `[来自「${fromRoleName}」的协作消息]\n${cleanMsg}`;
668
+ emitSystem(workspace, 'session.message_received', {
669
+ originSessionId: fromSessionId ? safeSessionId(fromSessionId) : '',
670
+ originRoleId: fromRoleId || '',
671
+ targetSessionId: targetMeta.id,
672
+ targetRoleId: targetMeta.roleId,
673
+ automationRuleId,
674
+ preview: cleanMsg.slice(0, 160),
675
+ });
676
+
677
+ const running = liveRuns.get(`${workspace}::${targetMeta.id}`);
678
+ if (running) {
679
+ const steered = await running.steer(formatted);
680
+ return {
681
+ ok: true,
682
+ delivered: steered ? 'steered' : 'busy',
683
+ targetSessionId: targetMeta.id,
684
+ targetTitle: targetMeta.title,
685
+ targetRoleId: targetMeta.roleId,
686
+ };
687
+ }
688
+
689
+ let replyPreview = '';
690
+ const turnPromise = runTurn({
691
+ workspace,
692
+ stateDir,
693
+ documentRoot,
694
+ sessionId: targetMeta.id,
695
+ roleId: targetMeta.roleId,
696
+ text: formatted,
697
+ canvas: canvas || {},
698
+ handoffFrom: fromRoleName,
699
+ automationRuleId,
700
+ emit: ev => {
701
+ if (ev?.type === 'text' && ev.text && replyPreview.length < 1200) {
702
+ replyPreview += ev.text;
703
+ }
704
+ },
705
+ }).then(() => {
706
+ events?.emit(workspace, 'agent.sessions', { action: 'updated', sessionId: targetMeta.id });
707
+ }).catch(() => {
708
+ events?.emit(workspace, 'agent.sessions', { action: 'updated', sessionId: targetMeta.id });
709
+ });
710
+
711
+ if (wait) {
712
+ await turnPromise;
713
+ return {
714
+ ok: true,
715
+ delivered: 'completed',
716
+ targetSessionId: targetMeta.id,
717
+ targetTitle: targetMeta.title,
718
+ targetRoleId: targetMeta.roleId,
719
+ replyPreview: replyPreview.trim().slice(0, 1000),
720
+ };
721
+ }
722
+
723
+ return {
724
+ ok: true,
725
+ delivered: 'woken',
726
+ targetSessionId: targetMeta.id,
727
+ targetTitle: targetMeta.title,
728
+ targetRoleId: targetMeta.roleId,
729
+ };
730
+ }
273
731
 
274
732
  async function runTurn({
275
733
  workspace,
@@ -281,6 +739,7 @@ export function createPiBridge({
281
739
  text,
282
740
  canvas,
283
741
  handoffFrom = '',
742
+ automationRuleId = '',
284
743
  emit,
285
744
  }) {
286
745
  const agentDir = resolvePiAgentDir();
@@ -293,8 +752,8 @@ export function createPiBridge({
293
752
  }, agentDir);
294
753
  const role = resolveRole(meta.roleId, agentDir);
295
754
 
296
- // Auto-title brand-new custom sessions on their first message; also dismiss any stale unanswered ask_user from past turns
297
- const existingMessages = (Array.isArray(meta.messages) ? meta.messages : []).map(m => {
755
+ // Load FULL un-truncated history from per-session file; dismiss any stale unanswered ask_user from past turns
756
+ const existingMessages = readSessionMessages(stateDir, cleanId).map(m => {
298
757
  if (!m || m.role !== 'assistant') return m;
299
758
  const hasStaleQ = Array.isArray(m.questions) && m.questions.some(q => q && !q.answered && !q.dismissed);
300
759
  const hasStaleSingle = Boolean(m.question && !m.question.answered && !m.question.dismissed);
@@ -319,9 +778,10 @@ export function createPiBridge({
319
778
  canvasFile: canvas?.file || '',
320
779
  selection: canvas?.selection || [],
321
780
  handoffFrom,
781
+ ...(automationRuleId ? { automationRuleId } : {}),
322
782
  timestamp: new Date().toISOString(),
323
783
  };
324
- const nextMessages = [...existingMessages.slice(-60), userMsg];
784
+ const nextMessages = [...existingMessages, userMsg];
325
785
  upsertSessionMeta(stateDir, {
326
786
  id: cleanId,
327
787
  ...(autoTitle ? { title: autoTitle } : {}),
@@ -357,8 +817,20 @@ export function createPiBridge({
357
817
  });
358
818
  });
359
819
 
820
+ let substantiveToolsCount = 0;
821
+ const markSubstantiveProgress = toolName => {
822
+ if (SUBSTANTIVE_TOOLS.has(toolName)) {
823
+ substantiveToolsCount++;
824
+ resetProgressForSession(cleanId);
825
+ }
826
+ };
827
+
360
828
  const emitWrapped = ev => {
829
+ if (ev?.type === 'tool' && ev.status === 'completed' && !ev.isError) {
830
+ markSubstantiveProgress(ev.name);
831
+ }
361
832
  if (ev?.type === 'ask_user') {
833
+ markSubstantiveProgress('ask_user');
362
834
  recordedQuestions.push({
363
835
  questionId: ev.questionId,
364
836
  question: ev.question,
@@ -366,6 +838,13 @@ export function createPiBridge({
366
838
  answered: false,
367
839
  answer: '',
368
840
  });
841
+ emitSystem(workspace, 'session.waiting_user', {
842
+ originSessionId: cleanId,
843
+ originRoleId: role.id,
844
+ questionId: ev.questionId,
845
+ question: ev.question,
846
+ automationRuleId,
847
+ });
369
848
  }
370
849
  emit(ev);
371
850
  };
@@ -377,6 +856,59 @@ export function createPiBridge({
377
856
  events,
378
857
  emit: emitWrapped,
379
858
  waitForUserAnswer,
859
+ sessionOps: {
860
+ currentSessionId: cleanId,
861
+ currentRoleId: role.id,
862
+ currentRoleName: role.name,
863
+ list: ({ sinceMinutes = 0, includeArchived = false } = {}) =>
864
+ listSessions(stateDir, { includeArchived, includeMessages: false, sinceMinutes, agentDir }),
865
+ read: ({ sessionId: targetId, limit = 12 }) =>
866
+ readSessionTranscript(stateDir, targetId, { limit, agentDir }),
867
+ open: ({ roleId: targetRoleId, title = '', reuseLatest = true }) =>
868
+ openOrCreatePeerSession(stateDir, { roleId: targetRoleId, title, reuseLatest, agentDir }),
869
+ send: ({ targetSessionId, targetRoleId, message, wait = false }) =>
870
+ sendCrossSessionMessage({
871
+ workspace,
872
+ stateDir,
873
+ documentRoot,
874
+ fromSessionId: cleanId,
875
+ fromRoleId: role.id,
876
+ fromRoleName: role.name,
877
+ targetSessionId,
878
+ targetRoleId,
879
+ message,
880
+ canvas,
881
+ wait,
882
+ }),
883
+ },
884
+ automationOps,
885
+ onCardChanges: (toolName, res) => {
886
+ markSubstantiveProgress(toolName);
887
+ if (Array.isArray(res?.cardChanges)) {
888
+ for (const ch of res.cardChanges) {
889
+ emitSystem(workspace, `card.${ch.action}`, {
890
+ file: ch.file,
891
+ card: ch.card,
892
+ addedTags: ch.addedTags,
893
+ removedTags: ch.removedTags,
894
+ originSessionId: cleanId,
895
+ originRoleId: role.id,
896
+ automationRuleId,
897
+ });
898
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
899
+ emitSystem(workspace, 'tag.changed', {
900
+ file: ch.file,
901
+ card: ch.card,
902
+ addedTags: ch.addedTags,
903
+ removedTags: ch.removedTags,
904
+ originSessionId: cleanId,
905
+ originRoleId: role.id,
906
+ automationRuleId,
907
+ });
908
+ }
909
+ }
910
+ }
911
+ },
380
912
  });
381
913
 
382
914
  let assistantText = '';
@@ -442,6 +974,7 @@ export function createPiBridge({
442
974
 
443
975
  const turnAbort = new AbortController();
444
976
  let draftActive = false;
977
+ let customSteerHandler = null;
445
978
 
446
979
  const runState = {
447
980
  sessionId: cleanId,
@@ -452,11 +985,23 @@ export function createPiBridge({
452
985
  return true;
453
986
  },
454
987
  async steer(steerText) {
455
- if (session?.steer) {
456
- await session.steer(steerText);
988
+ const clean = String(steerText || '').trim();
989
+ if (!clean) return false;
990
+ const handler = session?.steer
991
+ ? (t) => session.steer(t)
992
+ : (typeof customSteerHandler === 'function' ? customSteerHandler : null);
993
+ if (!handler) return false;
994
+ const steerBlock = { type: 'steer', text: clean };
995
+ blocks.push(steerBlock);
996
+ emitWrapped({ type: 'steer', text: clean });
997
+ try {
998
+ await handler(clean);
457
999
  return true;
1000
+ } catch (err) {
1001
+ const idx = blocks.lastIndexOf(steerBlock);
1002
+ if (idx >= 0) blocks.splice(idx, 1);
1003
+ throw err;
458
1004
  }
459
- return false;
460
1005
  },
461
1006
  async abort() {
462
1007
  abortedByUser = true;
@@ -484,8 +1029,9 @@ export function createPiBridge({
484
1029
  const finalText = assistantText
485
1030
  + (stopped ? (assistantText ? '\n\n' : '') + '_(已手动停止,以上内容已保留)_' : '')
486
1031
  + (errorMsg ? (assistantText ? '\n\n' : '') + '提示:' + errorMsg : '');
487
- const curMeta = getSessionMeta(stateDir, cleanId, agentDir);
488
- const baseMsgs = Array.isArray(curMeta?.messages) && curMeta.messages.length ? curMeta.messages : nextMessages;
1032
+ const curMeta = getSessionMeta(stateDir, cleanId, agentDir, { messageLimit: 1 });
1033
+ const diskMsgs = readSessionMessages(stateDir, cleanId);
1034
+ const baseMsgs = diskMsgs.length ? diskMsgs : nextMessages;
489
1035
  const finalizedQuestions = recordedQuestions.map(q => (q && !q.answered ? { ...q, dismissed: true } : q));
490
1036
  const assistantMsg = {
491
1037
  id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
@@ -505,7 +1051,7 @@ export function createPiBridge({
505
1051
  ...(piSessionFile ? { piSessionFile } : {}),
506
1052
  ...(latestContextUsage ? { contextUsage: latestContextUsage } : {}),
507
1053
  summaryBadge: badge,
508
- messages: [...baseMsgs, assistantMsg].slice(-80),
1054
+ messages: [...baseMsgs, assistantMsg],
509
1055
  }, agentDir);
510
1056
  };
511
1057
 
@@ -582,6 +1128,7 @@ export function createPiBridge({
582
1128
  events,
583
1129
  emit: factoryEmit,
584
1130
  waitForUserAnswer,
1131
+ onSteer: fn => { customSteerHandler = fn; },
585
1132
  signal: turnAbort.signal,
586
1133
  });
587
1134
  if (!assistantText && result?.text) appendTextDelta(String(result.text));
@@ -596,6 +1143,12 @@ export function createPiBridge({
596
1143
  const activeCtxWin = chosenModel.contextWindow || 128000;
597
1144
  const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
598
1145
  const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
1146
+ const triggerBudgetTokens = Math.max(8192, activeCtxWin - effectiveReserveTokens);
1147
+ const effectiveKeepRecentTokens = Math.min(
1148
+ runtimeSettings.keepRecentTokens,
1149
+ Math.max(4096, Math.floor(triggerBudgetTokens * 0.45))
1150
+ );
1151
+ const modelOverrideKey = `${chosenModel.provider}/${chosenModel.id}`;
599
1152
  sm.applyOverrides({
600
1153
  defaultThinkingLevel: runtimeSettings.thinkingLevel,
601
1154
  transport: runtimeSettings.transport,
@@ -604,7 +1157,13 @@ export function createPiBridge({
604
1157
  compaction: {
605
1158
  enabled: runtimeSettings.compactionEnabled,
606
1159
  reserveTokens: effectiveReserveTokens,
607
- keepRecentTokens: runtimeSettings.keepRecentTokens,
1160
+ keepRecentTokens: effectiveKeepRecentTokens,
1161
+ modelOverrides: {
1162
+ [modelOverrideKey]: {
1163
+ reserveTokens: effectiveReserveTokens,
1164
+ keepRecentTokens: effectiveKeepRecentTokens,
1165
+ },
1166
+ },
608
1167
  },
609
1168
  retry: {
610
1169
  enabled: runtimeSettings.retryEnabled,
@@ -651,15 +1210,20 @@ export function createPiBridge({
651
1210
  }
652
1211
  } catch {}
653
1212
 
1213
+ let lastKnownWindowTokens = typeof latestContextUsage?.tokens === 'number' ? latestContextUsage.tokens : 0;
1214
+ let compactedDuringTurn = false;
1215
+
654
1216
  const readContextUsageSnapshot = () => {
655
1217
  try {
656
1218
  const cu = session.getContextUsage?.();
657
1219
  const stats = session.getSessionStats?.();
658
1220
  const total = cu?.contextWindow || activeCtxWin;
659
- const used = typeof cu?.tokens === 'number'
660
- ? cu.tokens
661
- : (stats?.tokens ? (stats.tokens.input + stats.tokens.cacheRead + stats.tokens.cacheWrite) : 0);
662
- const usedPercent = typeof cu?.percent === 'number'
1221
+ let used = lastKnownWindowTokens;
1222
+ if (typeof cu?.tokens === 'number' && Number.isFinite(cu.tokens)) {
1223
+ used = Math.max(0, Math.round(cu.tokens));
1224
+ lastKnownWindowTokens = used;
1225
+ }
1226
+ const usedPercent = typeof cu?.percent === 'number' && Number.isFinite(cu.percent)
663
1227
  ? Number(Math.min(100, Math.max(0, cu.percent)).toFixed(1))
664
1228
  : Number(Math.min(100, (used / Math.max(1, total)) * 100).toFixed(1));
665
1229
  const remainingTokens = Math.max(0, total - used);
@@ -673,7 +1237,7 @@ export function createPiBridge({
673
1237
  remainingPercent,
674
1238
  compactionEnabled: runtimeSettings.compactionEnabled,
675
1239
  compactAtPercent: runtimeSettings.compactionTriggerPercent,
676
- keepRecentTokens: runtimeSettings.keepRecentTokens,
1240
+ keepRecentTokens: effectiveKeepRecentTokens,
677
1241
  thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
678
1242
  transport: runtimeSettings.transport,
679
1243
  model: `${chosenModel.provider}/${chosenModel.id}`,
@@ -793,32 +1357,80 @@ export function createPiBridge({
793
1357
  }
794
1358
  };
795
1359
 
1360
+ const verbForNodeOp = rawOp => {
1361
+ const a = String(rawOp || '').toLowerCase();
1362
+ if (a === 'delete' || a === 'remove') return '正在删除';
1363
+ if (a === 'create' || a === 'add' || a === 'insert' || a === 'append') return '正在新建';
1364
+ if (a === 'move' || a === 'reorder' || a === 'rename') return '正在调整';
1365
+ return '正在编辑';
1366
+ };
1367
+
796
1368
  const inferCanvasActivity = (toolName, args) => {
797
1369
  if (!args || typeof args !== 'object') return null;
798
1370
  if (['clado_nodes', 'clado_links', 'clado_update', 'clado_create'].includes(toolName)) {
799
1371
  if (toolName === 'clado_links' && (args.action || 'list') === 'list') return null;
800
1372
  const file = String(args.file || canvas?.file || '').trim();
801
1373
  const nodes = [];
802
- if (Array.isArray(args.node) && args.node.length) nodes.push(args.node);
803
- if (Array.isArray(args.targetNode) && args.targetNode.length && !args.targetFile) nodes.push(args.targetNode);
1374
+ const opGroups = new Map(); // verb -> Set<cardTitle>
1375
+ const addCardVerb = (verb, pathOrTitle) => {
1376
+ const cardTitle = Array.isArray(pathOrTitle)
1377
+ ? String(pathOrTitle[0] || '').trim()
1378
+ : String(pathOrTitle || '').trim();
1379
+ if (!cardTitle) return;
1380
+ if (!opGroups.has(verb)) opGroups.set(verb, new Set());
1381
+ opGroups.get(verb).add(cardTitle);
1382
+ };
1383
+ const defaultVerb = toolName === 'clado_create'
1384
+ ? '正在新建'
1385
+ : toolName === 'clado_links'
1386
+ ? ((args.action === 'remove' || args.action === 'delete') ? '正在移除连线' : '正在连线')
1387
+ : verbForNodeOp(args.action);
1388
+
1389
+ if (Array.isArray(args.node) && args.node.length) {
1390
+ nodes.push(args.node);
1391
+ addCardVerb(defaultVerb, args.node);
1392
+ }
1393
+ if (Array.isArray(args.targetNode) && args.targetNode.length && !args.targetFile) {
1394
+ nodes.push(args.targetNode);
1395
+ addCardVerb(defaultVerb, args.targetNode);
1396
+ }
804
1397
  if (Array.isArray(args.operations)) {
805
1398
  for (const op of args.operations) {
806
- if (Array.isArray(op?.node) && op.node.length) nodes.push(op.node);
807
- else if (op?.title) nodes.push([...(Array.isArray(op.parent) ? op.parent : []), op.title]);
1399
+ const opVerb = verbForNodeOp(op?.action || op?.op || args.action);
1400
+ if (Array.isArray(op?.node) && op.node.length) {
1401
+ nodes.push(op.node);
1402
+ addCardVerb(opVerb, op.node);
1403
+ } else if (op?.title) {
1404
+ const full = [...(Array.isArray(op.parent) ? op.parent : []), op.title];
1405
+ nodes.push(full);
1406
+ addCardVerb(opVerb, full);
1407
+ }
808
1408
  }
809
1409
  }
1410
+ if (typeof args.content === 'string') {
1411
+ const h1s = (args.content.match(/^#\s+(.+)$/gm) || []).map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
1412
+ for (const h of h1s.slice(0, 12)) addCardVerb(defaultVerb, h);
1413
+ }
810
1414
  const labelTarget = nodes[0]?.at(-1) || args.title || file || '画布';
811
- const verb = toolName === 'clado_create' ? '正在创建' : toolName === 'clado_links' ? '正在连线' : '正在编辑';
812
- return { file, kind: 'editing', nodes: nodes.slice(0, 8), label: `AI ${verb} · ${labelTarget}`, isDirectFile: false };
1415
+ const primaryVerb = opGroups.size === 1 ? Array.from(opGroups.keys())[0] : defaultVerb;
1416
+ return {
1417
+ file,
1418
+ kind: 'editing',
1419
+ nodes: nodes.slice(0, 12),
1420
+ opGroups: Array.from(opGroups.entries()).map(([verb, set]) => ({ verb, cards: Array.from(set) })),
1421
+ label: `AI ${primaryVerb} · ${labelTarget}`,
1422
+ verb: primaryVerb,
1423
+ isDirectFile: false,
1424
+ };
813
1425
  }
814
1426
  if (['clado_read', 'clado_graph'].includes(toolName)) {
815
1427
  const file = String(args.file || canvas?.file || '').trim();
816
- return { file, kind: 'read', nodes: [], label: `AI 正在查看 · ${file || '画布拓扑'}`, isDirectFile: false };
1428
+ return { file, kind: 'read', nodes: [], opGroups: [], verb: '正在查看', label: `AI 正在查看 · ${file || '画布拓扑'}`, isDirectFile: false };
817
1429
  }
818
1430
  if (['edit', 'write'].includes(toolName)) {
819
1431
  const rel = resolveCanvasRelFile(args.path || args.file_path || args.file);
820
1432
  if (rel) {
821
- return { file: rel, kind: 'editing', nodes: [], label: `AI 正在编辑 · ${rel}`, isDirectFile: true };
1433
+ return { file: rel, kind: 'editing', nodes: [], opGroups: [], verb: '正在编辑', label: `AI 正在编辑 · ${rel}`, isDirectFile: true };
822
1434
  }
823
1435
  }
824
1436
  return null;
@@ -893,22 +1505,30 @@ export function createPiBridge({
893
1505
  nodes: canvasAct.nodes,
894
1506
  label: canvasAct.label,
895
1507
  });
896
- let pCards = canvasAct.nodes
897
- .map(n => (Array.isArray(n) ? n[0] : String(n || '')))
898
- .map(s => String(s || '').trim())
899
- .filter(Boolean);
900
- if (!pCards.length && typeof ev.args?.content === 'string') {
901
- const h1s = (ev.args.content.match(/^#\s+(.+)$/gm) || []).map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
902
- if (h1s.length) pCards = h1s.slice(0, 6);
903
- }
904
- if (!pCards.length) pCards = selectedCardTitles;
905
- if (pCards.length) {
906
- emitPresence({
907
- phase: 'active',
908
- file: canvasAct.file,
909
- cards: [...new Set(pCards)],
910
- label: canvasAct.label.replace(/^AI\s*/, ''),
911
- });
1508
+ if (Array.isArray(canvasAct.opGroups) && canvasAct.opGroups.length) {
1509
+ for (const grp of canvasAct.opGroups) {
1510
+ if (!grp.cards.length) continue;
1511
+ emitPresence({
1512
+ phase: 'active',
1513
+ file: canvasAct.file,
1514
+ cards: grp.cards,
1515
+ label: grp.verb,
1516
+ });
1517
+ }
1518
+ } else {
1519
+ let pCards = canvasAct.nodes
1520
+ .map(n => (Array.isArray(n) ? n[0] : String(n || '')))
1521
+ .map(s => String(s || '').trim())
1522
+ .filter(Boolean);
1523
+ if (!pCards.length) pCards = selectedCardTitles;
1524
+ if (pCards.length) {
1525
+ emitPresence({
1526
+ phase: 'active',
1527
+ file: canvasAct.file,
1528
+ cards: [...new Set(pCards)],
1529
+ label: canvasAct.verb || canvasAct.label.replace(/^AI\s*/, ''),
1530
+ });
1531
+ }
912
1532
  }
913
1533
  } else if (['edit', 'write', 'read'].includes(ev.toolName)) {
914
1534
  const codeTarget = resolveWorkspaceCodeRel(ev.args?.path || ev.args?.file_path || ev.args?.file);
@@ -939,7 +1559,7 @@ export function createPiBridge({
939
1559
  phase: 'active',
940
1560
  cards: [...new Set(presenceCards)],
941
1561
  codePath: codeTarget.rel,
942
- label: `${ev.toolName === 'read' ? '查看' : '修改'} ${codeTarget.rel}`,
1562
+ label: `${ev.toolName === 'read' ? '正在查看' : '正在修改'} ${codeTarget.rel}`,
943
1563
  });
944
1564
  }
945
1565
  }
@@ -990,6 +1610,7 @@ export function createPiBridge({
990
1610
  }
991
1611
  const codeAct = activeCodeMeta.get(ev.toolCallId);
992
1612
  activeCodeMeta.delete(ev.toolCallId);
1613
+ if (!isFailed) markSubstantiveProgress(ev.toolName);
993
1614
  if (codeAct && !isFailed && ['edit', 'write'].includes(codeAct.action)) {
994
1615
  const after = safeReadCodeSnapshot(codeAct.abs);
995
1616
  if (after !== null) {
@@ -1004,6 +1625,23 @@ export function createPiBridge({
1004
1625
  roleName: role.name,
1005
1626
  });
1006
1627
  }
1628
+ const normRel = String(codeAct.rel || '').replace(/\\/g, '/');
1629
+ if (normRel === 'AGENTS.md' || normRel === '.clado/memory.md' || normRel === 'CLAUDE.md') {
1630
+ emitSystem(workspace, 'memory.updated', {
1631
+ file: normRel,
1632
+ originSessionId: cleanId,
1633
+ originRoleId: role.id,
1634
+ automationRuleId,
1635
+ });
1636
+ } else {
1637
+ emitSystem(workspace, 'code.file_changed', {
1638
+ file: normRel,
1639
+ action: codeAct.action,
1640
+ originSessionId: cleanId,
1641
+ originRoleId: role.id,
1642
+ automationRuleId,
1643
+ });
1644
+ }
1007
1645
  }
1008
1646
  const updated = upsertToolEntry({
1009
1647
  id: ev.toolCallId,
@@ -1037,32 +1675,87 @@ export function createPiBridge({
1037
1675
  emitWrapped({ type: 'usage', usage: snapUsage });
1038
1676
  }
1039
1677
  if (!ev.aborted && !ev.errorMessage) {
1678
+ compactedDuringTurn = true;
1040
1679
  emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
1680
+ emitSystem(workspace, 'context.compacted', {
1681
+ originSessionId: cleanId,
1682
+ originRoleId: role.id,
1683
+ usedPercent: snapUsage?.usedPercent ?? 0,
1684
+ automationRuleId,
1685
+ });
1041
1686
  }
1042
1687
  } else if (ev.type === 'auto_retry_start') {
1043
1688
  emitWrapped({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
1044
1689
  }
1045
1690
  });
1046
1691
 
1047
- const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
1692
+ const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
1048
1693
  await session.prompt(promptText);
1049
- const finalUsage = readContextUsageSnapshot();
1694
+ let finalUsage = readContextUsageSnapshot();
1050
1695
  if (finalUsage) {
1051
1696
  latestContextUsage = finalUsage;
1052
1697
  emitWrapped({ type: 'usage', usage: finalUsage });
1053
1698
  }
1699
+ // Fallback auto-compaction guarantee: if usage reached configured trigger % and Pi didn't compact during turn, compact now!
1700
+ if (
1701
+ runtimeSettings.compactionEnabled
1702
+ && !abortedByUser
1703
+ && !compactedDuringTurn
1704
+ && finalUsage
1705
+ && finalUsage.usedPercent >= runtimeSettings.compactionTriggerPercent
1706
+ && typeof session.compact === 'function'
1707
+ ) {
1708
+ try {
1709
+ emitWrapped({ type: 'status', text: `上下文已达 ${finalUsage.usedPercent}%(阈值 ${runtimeSettings.compactionTriggerPercent}%),正在自动压缩…` });
1710
+ await session.compact();
1711
+ const postUsage = readContextUsageSnapshot();
1712
+ if (postUsage) {
1713
+ finalUsage = postUsage;
1714
+ latestContextUsage = postUsage;
1715
+ emitWrapped({ type: 'usage', usage: postUsage });
1716
+ }
1717
+ emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
1718
+ emitSystem(workspace, 'context.compacted', {
1719
+ originSessionId: cleanId,
1720
+ originRoleId: role.id,
1721
+ usedPercent: postUsage?.usedPercent ?? 0,
1722
+ automationRuleId,
1723
+ });
1724
+ } catch {}
1725
+ }
1054
1726
  }
1055
1727
 
1056
1728
  persistAssistantTurn({ stopped: abortedByUser });
1057
1729
  emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser, usage: latestContextUsage });
1730
+ emitSystem(workspace, abortedByUser ? 'session.turn_stopped' : 'session.turn_completed', {
1731
+ originSessionId: cleanId,
1732
+ originRoleId: role.id,
1733
+ roleName: role.name,
1734
+ substantiveToolsCount,
1735
+ automationRuleId,
1736
+ });
1058
1737
  } catch (err) {
1059
1738
  if (abortedByUser) {
1060
1739
  persistAssistantTurn({ stopped: true });
1061
1740
  emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true, usage: latestContextUsage });
1741
+ emitSystem(workspace, 'session.turn_stopped', {
1742
+ originSessionId: cleanId,
1743
+ originRoleId: role.id,
1744
+ roleName: role.name,
1745
+ substantiveToolsCount,
1746
+ automationRuleId,
1747
+ });
1062
1748
  } else {
1063
1749
  const msg = err?.message || 'Pi 执行失败';
1064
1750
  persistAssistantTurn({ errorMsg: msg });
1065
1751
  emitWrapped({ type: 'error', message: msg });
1752
+ emitSystem(workspace, 'session.turn_error', {
1753
+ originSessionId: cleanId,
1754
+ originRoleId: role.id,
1755
+ roleName: role.name,
1756
+ error: msg,
1757
+ automationRuleId,
1758
+ });
1066
1759
  }
1067
1760
  } finally {
1068
1761
  if (draftActive) {
@@ -1070,7 +1763,7 @@ export function createPiBridge({
1070
1763
  events?.emit(workspace, 'canvas.draft', { active: false });
1071
1764
  }
1072
1765
  if (presenceTouched) {
1073
- emitPresence({ phase: 'afterglow', label: '刚刚完成' });
1766
+ emitPresence({ phase: 'afterglow', label: '刚刚编辑了', stopped: abortedByUser });
1074
1767
  }
1075
1768
  liveRuns.delete(`${workspace}::${cleanId}`);
1076
1769
  try { unsub?.(); } catch {}
@@ -1085,7 +1778,7 @@ export function createPiBridge({
1085
1778
  throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
1086
1779
  }
1087
1780
  const agentDir = resolvePiAgentDir();
1088
- const meta = getSessionMeta(stateDir, cleanId, agentDir);
1781
+ const meta = getSessionMeta(stateDir, cleanId, agentDir, { messageLimit: 1 });
1089
1782
  if (!meta) throw new Error('找不到目标会话。');
1090
1783
  if (!meta.piSessionFile || !existsSync(meta.piSessionFile)) {
1091
1784
  return { ok: true, skipped: true, reason: '当前会话尚无需要压缩的历史记录。', session: meta };
@@ -1097,6 +1790,18 @@ export function createPiBridge({
1097
1790
 
1098
1791
  const activeCtxWin = chosenModel.contextWindow || 128000;
1099
1792
  const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
1793
+ const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
1794
+ const effectiveKeepRecentTokens = Math.min(
1795
+ runtimeSettings.keepRecentTokens,
1796
+ Math.max(4096, Math.floor(Math.max(8192, activeCtxWin - effectiveReserveTokens) * 0.45))
1797
+ );
1798
+ sm.applyOverrides({
1799
+ compaction: {
1800
+ enabled: runtimeSettings.compactionEnabled,
1801
+ reserveTokens: effectiveReserveTokens,
1802
+ keepRecentTokens: effectiveKeepRecentTokens,
1803
+ },
1804
+ });
1100
1805
  const loader = new DefaultResourceLoader({ cwd: workspace, agentDir, settingsManager: sm, noThemes: true });
1101
1806
  await loader.reload();
1102
1807
  const sessionManager = SessionManager.open(meta.piSessionFile);
@@ -1125,13 +1830,18 @@ export function createPiBridge({
1125
1830
  remainingPercent: Number(Math.max(0, 100 - usedPercent).toFixed(1)),
1126
1831
  compactionEnabled: runtimeSettings.compactionEnabled,
1127
1832
  compactAtPercent: runtimeSettings.compactionTriggerPercent,
1128
- keepRecentTokens: runtimeSettings.keepRecentTokens,
1833
+ keepRecentTokens: effectiveKeepRecentTokens,
1129
1834
  thinkingLevel: runtimeSettings.thinkingLevel,
1130
1835
  transport: runtimeSettings.transport,
1131
1836
  model: `${chosenModel.provider}/${chosenModel.id}`,
1132
1837
  updatedAt: new Date().toISOString(),
1133
1838
  };
1134
1839
  const updated = upsertSessionMeta(stateDir, { id: cleanId, contextUsage }, agentDir);
1840
+ emitSystem(workspace, 'context.compacted', {
1841
+ originSessionId: cleanId,
1842
+ originRoleId: meta.roleId,
1843
+ usedPercent,
1844
+ });
1135
1845
  return { ok: true, contextUsage, session: updated };
1136
1846
  } finally {
1137
1847
  try { session?.dispose?.(); } catch {}
@@ -1141,6 +1851,15 @@ export function createPiBridge({
1141
1851
  return {
1142
1852
  runTurn,
1143
1853
  compactSession,
1854
+ sendCrossSessionMessage,
1855
+ readSessionTranscript,
1856
+ openOrCreatePeerSession,
1857
+ listActiveRuns(workspace) {
1858
+ const prefix = workspace ? `${workspace}::` : '';
1859
+ return [...liveRuns.entries()]
1860
+ .filter(([k]) => !prefix || k.startsWith(prefix))
1861
+ .map(([, v]) => v.sessionId);
1862
+ },
1144
1863
  answer(workspace, sessionId, questionId, answerText) {
1145
1864
  const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
1146
1865
  return run ? run.answer(questionId, answerText) : false;
@@ -1157,6 +1876,14 @@ export function createPiBridge({
1157
1876
  }
1158
1877
  return false;
1159
1878
  },
1879
+ async abortAllRuns(workspace) {
1880
+ const prefix = workspace ? `${workspace}::` : '';
1881
+ const targets = [...liveRuns.entries()]
1882
+ .filter(([k]) => !prefix || k.startsWith(prefix))
1883
+ .map(([, v]) => v);
1884
+ await Promise.allSettled(targets.map(r => r.abort()));
1885
+ return targets.length;
1886
+ },
1160
1887
  async closeAll() {
1161
1888
  const all = [...liveRuns.values()];
1162
1889
  liveRuns.clear();