cladogram 0.6.0-beta.1 → 0.6.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
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, extname, join, relative, resolve } from 'node:path';
11
11
  import {
12
12
  createAgentSession,
13
13
  DefaultResourceLoader,
@@ -15,7 +15,9 @@ import {
15
15
  SettingsManager,
16
16
  } from '@earendil-works/pi-coding-agent';
17
17
  import {
18
+ CLADO_CANVAS_MASTERY_GUIDE,
18
19
  createCladoModelRuntime,
20
+ readRuntimeSettings,
19
21
  resolvePiAgentDir,
20
22
  resolveRole,
21
23
  } from './pi-config.js';
@@ -24,7 +26,7 @@ import { workspacePath } from '../workspace/documents.js';
24
26
 
25
27
  export function safeSessionId(raw) {
26
28
  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));
29
+ return s.length >= 4 ? s.slice(0, 80) : ('sess_' + randomUUID().replace(/-/g, '').slice(0, 12));
28
30
  }
29
31
 
30
32
  function sessionsDir(stateDir) {
@@ -65,6 +67,7 @@ export function ensureDefaultSessions(stateDir, agentDir = resolvePiAgentDir())
65
67
  phase: role.phase,
66
68
  tone: role.tone,
67
69
  model: role.model || '',
70
+ piSessionFile: '',
68
71
  archived: false,
69
72
  status: 'idle',
70
73
  summaryBadge: '',
@@ -90,7 +93,7 @@ export function getSessionMeta(stateDir, id, agentDir = resolvePiAgentDir()) {
90
93
 
91
94
  export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir()) {
92
95
  const list = ensureDefaultSessions(stateDir, agentDir);
93
- const id = safeSessionId(patch.id);
96
+ const id = patch.id ? safeSessionId(patch.id) : ('sess_' + randomUUID().replace(/-/g, '').slice(0, 12));
94
97
  const idx = list.findIndex(s => s.id === id);
95
98
  const role = resolveRole(patch.roleId || list[idx]?.roleId || 'architect', agentDir);
96
99
  const now = new Date().toISOString();
@@ -111,6 +114,7 @@ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(
111
114
  phase: role.phase,
112
115
  tone: role.tone,
113
116
  model: String(patch.model || role.model || ''),
117
+ piSessionFile: String(patch.piSessionFile || ''),
114
118
  archived: false,
115
119
  status: 'idle',
116
120
  summaryBadge: '',
@@ -125,6 +129,18 @@ export function upsertSessionMeta(stateDir, patch, agentDir = resolvePiAgentDir(
125
129
  return next;
126
130
  }
127
131
 
132
+ export function renameSession(stateDir, id, title, agentDir = resolvePiAgentDir()) {
133
+ const cleanTitle = String(title || '').trim().slice(0, 60);
134
+ if (!cleanTitle) throw new Error('会话名称不能为空。');
135
+ const list = ensureDefaultSessions(stateDir, agentDir);
136
+ const item = list.find(s => s.id === id);
137
+ if (!item) throw new Error('找不到该会话。');
138
+ item.title = cleanTitle;
139
+ item.updatedAt = new Date().toISOString();
140
+ writeIndex(stateDir, list);
141
+ return item;
142
+ }
143
+
128
144
  export function archiveSession(stateDir, id, archived = true, agentDir = resolvePiAgentDir()) {
129
145
  const list = ensureDefaultSessions(stateDir, agentDir);
130
146
  const item = list.find(s => s.id === id);
@@ -137,11 +153,13 @@ export function archiveSession(stateDir, id, archived = true, agentDir = resolve
137
153
 
138
154
  export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
139
155
  const list = ensureDefaultSessions(stateDir, agentDir);
156
+ const target = list.find(s => s.id === id);
140
157
  const next = list.filter(s => s.id !== id);
141
158
  writeIndex(stateDir, next);
142
- const jsonl = join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl');
143
- if (existsSync(jsonl)) {
144
- try { rmSync(jsonl, { force: true }); } catch {}
159
+ for (const candidate of [target?.piSessionFile, join(sessionsDir(stateDir), safeSessionId(id) + '.jsonl')]) {
160
+ if (candidate && existsSync(candidate)) {
161
+ try { rmSync(candidate, { force: true }); } catch {}
162
+ }
145
163
  }
146
164
  return { deleted: next.length !== list.length, id };
147
165
  }
@@ -194,6 +212,13 @@ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFr
194
212
  const objStr = canvas.objectSelection.map(o => `${o.title || o.id}(${o.kind})`).join(';');
195
213
  lines.push(`用户选中的画布组件:${objStr}`);
196
214
  }
215
+ if (canvas.textSnippet && typeof canvas.textSnippet === 'object' && canvas.textSnippet.text) {
216
+ const nodeLabel = Array.isArray(canvas.textSnippet.node) && canvas.textSnippet.node.length
217
+ ? canvas.textSnippet.node.join(' > ')
218
+ : '';
219
+ const quoted = String(canvas.textSnippet.text).replace(/\s+/g, ' ').trim().slice(0, 320);
220
+ lines.push(`用户框选的精确片段${nodeLabel ? `(位于 ${nodeLabel})` : ''}:「${quoted}」`);
221
+ }
197
222
  }
198
223
  if (lines.length) {
199
224
  return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${text}`;
@@ -268,12 +293,24 @@ export function createPiBridge({
268
293
  }, agentDir);
269
294
  const role = resolveRole(meta.roleId, agentDir);
270
295
 
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 => {
298
+ if (!m || m.role !== 'assistant') return m;
299
+ const hasStaleQ = Array.isArray(m.questions) && m.questions.some(q => q && !q.answered && !q.dismissed);
300
+ const hasStaleSingle = Boolean(m.question && !m.question.answered && !m.question.dismissed);
301
+ if (!hasStaleQ && !hasStaleSingle) return m;
302
+ return {
303
+ ...m,
304
+ ...(Array.isArray(m.questions) ? { questions: m.questions.map(q => (q && !q.answered ? { ...q, dismissed: true } : q)) } : {}),
305
+ ...(hasStaleSingle ? { question: { ...m.question, dismissed: true } } : {}),
306
+ };
307
+ });
308
+ const shouldAutoTitle = existingMessages.length === 0 && !cleanId.startsWith('role_') && (meta.title === role.name || meta.title.startsWith(role.name + ' · 新会话'));
309
+ const autoTitle = shouldAutoTitle ? text.replace(/\s+/g, ' ').trim().slice(0, 22) : undefined;
310
+
271
311
  // Capture pre-turn canvas snapshot for 1-click rollback
272
312
  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
- }
313
+ const nextSnaps = snap ? [...(meta.snapshots || []).slice(-11), snap] : (meta.snapshots || []);
277
314
 
278
315
  const userMsg = {
279
316
  id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
@@ -284,43 +321,127 @@ export function createPiBridge({
284
321
  handoffFrom,
285
322
  timestamp: new Date().toISOString(),
286
323
  };
287
- const nextMessages = [...(meta.messages || []).slice(-60), userMsg];
288
- upsertSessionMeta(stateDir, { id: cleanId, messages: nextMessages }, agentDir);
324
+ const nextMessages = [...existingMessages.slice(-60), userMsg];
325
+ upsertSessionMeta(stateDir, {
326
+ id: cleanId,
327
+ ...(autoTitle ? { title: autoTitle } : {}),
328
+ snapshots: nextSnaps,
329
+ messages: nextMessages,
330
+ }, agentDir);
289
331
 
290
332
  const pendingQuestions = new Map();
333
+ const recordedQuestions = [];
291
334
  const waitForUserAnswer = (questionId, signal) => new Promise((resolveAnswer, rejectAnswer) => {
292
335
  const onAbort = () => {
293
336
  pendingQuestions.delete(questionId);
294
- rejectAnswer(new Error('已取消等待确认'));
337
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
338
+ if (rec && !rec.answered) rec.dismissed = true;
339
+ rejectAnswer(new Error('已停止生成'));
295
340
  };
296
341
  signal?.addEventListener('abort', onAbort, { once: true });
297
342
  pendingQuestions.set(questionId, {
298
343
  resolve(ans) {
299
344
  signal?.removeEventListener('abort', onAbort);
300
345
  pendingQuestions.delete(questionId);
346
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
347
+ if (rec) { rec.answered = true; rec.answer = ans; rec.dismissed = false; }
301
348
  resolveAnswer(ans);
302
349
  },
303
350
  reject(err) {
304
351
  signal?.removeEventListener('abort', onAbort);
305
352
  pendingQuestions.delete(questionId);
353
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
354
+ if (rec && !rec.answered) rec.dismissed = true;
306
355
  rejectAnswer(err);
307
356
  },
308
357
  });
309
358
  });
310
359
 
360
+ const emitWrapped = ev => {
361
+ if (ev?.type === 'ask_user') {
362
+ recordedQuestions.push({
363
+ questionId: ev.questionId,
364
+ question: ev.question,
365
+ options: ev.options || [],
366
+ answered: false,
367
+ answer: '',
368
+ });
369
+ }
370
+ emit(ev);
371
+ };
372
+
311
373
  const cladoTools = createCladoPiTools({
312
374
  workspace,
313
375
  stateDir,
314
376
  workspaceService,
315
377
  events,
316
- emit,
378
+ emit: emitWrapped,
317
379
  waitForUserAnswer,
318
380
  });
319
381
 
320
382
  let assistantText = '';
321
383
  const toolLog = [];
384
+ const blocks = [];
322
385
  let session = null;
323
386
  let unsub = null;
387
+ let abortedByUser = false;
388
+ let piSessionFile = meta.piSessionFile || '';
389
+
390
+ const appendThinkingDelta = delta => {
391
+ if (!delta) return;
392
+ const lastBlock = blocks[blocks.length - 1];
393
+ if (lastBlock && lastBlock.type === 'thinking') {
394
+ lastBlock.text += delta;
395
+ } else {
396
+ blocks.push({ type: 'thinking', text: delta });
397
+ }
398
+ };
399
+
400
+ const appendTextDelta = delta => {
401
+ if (!delta) return;
402
+ const lastBlock = blocks[blocks.length - 1];
403
+ if (lastBlock && lastBlock.type === 'text') {
404
+ lastBlock.text += delta;
405
+ assistantText += delta;
406
+ } else {
407
+ blocks.push({ type: 'text', text: delta });
408
+ if (assistantText && !assistantText.endsWith('\n\n') && !delta.startsWith('\n')) {
409
+ assistantText += '\n\n';
410
+ }
411
+ assistantText += delta;
412
+ }
413
+ };
414
+
415
+ const upsertToolEntry = ev => {
416
+ const existing = toolLog.find(t => t.id === ev.id);
417
+ if (existing) {
418
+ if (ev.name || ev.title) existing.name = ev.name || existing.name;
419
+ if (ev.argsSummary !== undefined && ev.argsSummary !== '') existing.argsSummary = ev.argsSummary;
420
+ if (ev.status) existing.status = ev.status;
421
+ if (ev.isError !== undefined) existing.isError = Boolean(ev.isError);
422
+ if (ev.resultPreview !== undefined) existing.resultPreview = ev.resultPreview;
423
+ return existing;
424
+ }
425
+ const entry = {
426
+ id: ev.id,
427
+ name: ev.name || ev.title || 'tool',
428
+ argsSummary: ev.argsSummary || '',
429
+ status: ev.status || 'running',
430
+ isError: Boolean(ev.isError || ev.status === 'failed'),
431
+ resultPreview: ev.resultPreview || '',
432
+ };
433
+ toolLog.push(entry);
434
+ const lastBlock = blocks[blocks.length - 1];
435
+ if (lastBlock && lastBlock.type === 'tools') {
436
+ lastBlock.tools.push(entry);
437
+ } else {
438
+ blocks.push({ type: 'tools', tools: [entry] });
439
+ }
440
+ return entry;
441
+ };
442
+
443
+ const turnAbort = new AbortController();
444
+ let draftActive = false;
324
445
 
325
446
  const runState = {
326
447
  sessionId: cleanId,
@@ -338,22 +459,93 @@ export function createPiBridge({
338
459
  return false;
339
460
  },
340
461
  async abort() {
341
- for (const w of pendingQuestions.values()) w.reject(new Error('用户已中止'));
462
+ abortedByUser = true;
463
+ turnAbort.abort();
464
+ for (const w of pendingQuestions.values()) w.reject(new Error('用户已停止生成'));
342
465
  pendingQuestions.clear();
343
466
  if (session?.abort) await session.abort();
344
467
  },
345
468
  };
346
469
  liveRuns.set(`${workspace}::${cleanId}`, runState);
347
470
 
471
+ const persistAssistantTurn = ({ stopped = false, errorMsg = '' } = {}) => {
472
+ const suffixParts = [];
473
+ if (stopped) suffixParts.push('_(已手动停止,以上内容已保留)_');
474
+ if (errorMsg) suffixParts.push('提示:' + errorMsg);
475
+ if (suffixParts.length) {
476
+ const suffix = suffixParts.join('\n\n');
477
+ const lastBlock = blocks[blocks.length - 1];
478
+ if (lastBlock && lastBlock.type === 'text') {
479
+ lastBlock.text += (lastBlock.text ? '\n\n' : '') + suffix;
480
+ } else {
481
+ blocks.push({ type: 'text', text: suffix });
482
+ }
483
+ }
484
+ const finalText = assistantText
485
+ + (stopped ? (assistantText ? '\n\n' : '') + '_(已手动停止,以上内容已保留)_' : '')
486
+ + (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;
489
+ const finalizedQuestions = recordedQuestions.map(q => (q && !q.answered ? { ...q, dismissed: true } : q));
490
+ const assistantMsg = {
491
+ id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
492
+ role: 'assistant',
493
+ text: finalText,
494
+ tools: toolLog,
495
+ blocks,
496
+ questions: finalizedQuestions,
497
+ stopped: Boolean(stopped),
498
+ snapshotId: snap?.id || '',
499
+ timestamp: new Date().toISOString(),
500
+ };
501
+ const badge = toolLog.length ? `${toolLog.length} tools` : (curMeta?.summaryBadge || '');
502
+ upsertSessionMeta(stateDir, {
503
+ id: cleanId,
504
+ status: 'idle',
505
+ ...(piSessionFile ? { piSessionFile } : {}),
506
+ ...(latestContextUsage ? { contextUsage: latestContextUsage } : {}),
507
+ summaryBadge: badge,
508
+ messages: [...baseMsgs, assistantMsg].slice(-80),
509
+ }, agentDir);
510
+ };
511
+
512
+ let latestContextUsage = meta.contextUsage || null;
513
+
348
514
  try {
349
- emit({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
515
+ emitWrapped({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
516
+ events?.emit(workspace, 'agent.stage', {
517
+ sessionId: cleanId,
518
+ roleId: role.id,
519
+ roleName: role.name,
520
+ phase: role.phase || '',
521
+ tone: role.tone || 'sky',
522
+ handoffFrom: handoffFrom || '',
523
+ file: canvas?.file || '',
524
+ });
350
525
 
351
526
  if (sessionFactory) {
352
- // Test injection hook
527
+ const factoryEmit = ev => {
528
+ if (ev?.type === 'thinking' && ev.text) appendThinkingDelta(ev.text);
529
+ if (ev?.type === 'text' && ev.text) appendTextDelta(ev.text);
530
+ if (ev?.type === 'tool') upsertToolEntry(ev);
531
+ if (ev?.type === 'usage' && ev.usage) latestContextUsage = ev.usage;
532
+ emitWrapped(ev);
533
+ };
353
534
  const result = await sessionFactory({
354
- workspace, stateDir, documentRoot, sessionId: cleanId, role, text, canvas, cladoTools, emit, waitForUserAnswer,
535
+ workspace,
536
+ stateDir,
537
+ documentRoot,
538
+ sessionId: cleanId,
539
+ role,
540
+ text,
541
+ canvas,
542
+ cladoTools,
543
+ events,
544
+ emit: factoryEmit,
545
+ waitForUserAnswer,
546
+ signal: turnAbort.signal,
355
547
  });
356
- assistantText = String(result?.text || '');
548
+ if (!assistantText && result?.text) appendTextDelta(String(result.text));
357
549
  } else {
358
550
  const sm = SettingsManager.create(workspace, agentDir);
359
551
  const mr = await createCladoModelRuntime(agentDir);
@@ -362,6 +554,25 @@ export function createPiBridge({
362
554
  throw new Error('尚未配置可用模型。请点击顶部「设置 → 模型与供应商」填写 API Key 或本地 Ollama 地址。');
363
555
  }
364
556
 
557
+ const activeCtxWin = chosenModel.contextWindow || 128000;
558
+ const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
559
+ const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
560
+ sm.applyOverrides({
561
+ defaultThinkingLevel: runtimeSettings.thinkingLevel,
562
+ transport: runtimeSettings.transport,
563
+ hideThinkingBlock: runtimeSettings.hideThinkingBlock,
564
+ cacheWarming: runtimeSettings.cacheWarming,
565
+ compaction: {
566
+ enabled: runtimeSettings.compactionEnabled,
567
+ reserveTokens: effectiveReserveTokens,
568
+ keepRecentTokens: runtimeSettings.keepRecentTokens,
569
+ },
570
+ retry: {
571
+ enabled: runtimeSettings.retryEnabled,
572
+ maxRetries: runtimeSettings.maxRetries,
573
+ },
574
+ });
575
+
365
576
  const loader = new DefaultResourceLoader({
366
577
  cwd: workspace,
367
578
  agentDir,
@@ -370,15 +581,21 @@ export function createPiBridge({
370
581
  packageCommandOutput: 'capture',
371
582
  appendSystemPrompt: [
372
583
  role.systemPrompt,
373
- '工作区规范:你可以通过 clado_* 工具读写空间画布,也可以直接使用 read/edit/write/bash 工具分析或修改代码。无需向用户弹窗请求命令权限。',
584
+ CLADO_CANVAS_MASTERY_GUIDE,
585
+ '工作区规范:你可以通过 clado_* 工具读写空间画布并读取渲染后的画布拓扑树(clado_graph),也可以直接使用 read/edit/write/bash 工具分析或修改代码。无需向用户弹窗请求命令权限。',
586
+ '提问规范:如果你需要向用户确认方案或提问,请先完整阐述你的分析与建议,再在最后一步调用 ask_user 工具,避免在回答中途插入问题。',
374
587
  ],
375
588
  });
376
589
  await loader.reload();
377
590
 
378
- const jsonlFile = join(sessionsDir(stateDir), cleanId + '.jsonl');
379
- const sessionManager = existsSync(jsonlFile)
380
- ? SessionManager.open(jsonlFile)
591
+ const sessionManager = (piSessionFile && existsSync(piSessionFile))
592
+ ? SessionManager.open(piSessionFile)
381
593
  : SessionManager.create(workspace, sessionsDir(stateDir));
594
+ const resolvedFile = sessionManager.getSessionFile?.() || '';
595
+ if (resolvedFile) {
596
+ piSessionFile = resolvedFile;
597
+ upsertSessionMeta(stateDir, { id: cleanId, piSessionFile }, agentDir);
598
+ }
382
599
 
383
600
  const created = await createAgentSession({
384
601
  cwd: workspace,
@@ -391,77 +608,469 @@ export function createPiBridge({
391
608
  customTools: cladoTools,
392
609
  });
393
610
  session = created.session;
611
+ try {
612
+ if (runtimeSettings.thinkingLevel && typeof session.setThinkingLevel === 'function') {
613
+ session.setThinkingLevel(runtimeSettings.thinkingLevel);
614
+ }
615
+ } catch {}
394
616
 
395
- emit({
617
+ const readContextUsageSnapshot = () => {
618
+ try {
619
+ const cu = session.getContextUsage?.();
620
+ const stats = session.getSessionStats?.();
621
+ const total = cu?.contextWindow || activeCtxWin;
622
+ const used = typeof cu?.tokens === 'number'
623
+ ? cu.tokens
624
+ : (stats?.tokens ? (stats.tokens.input + stats.tokens.cacheRead + stats.tokens.cacheWrite) : 0);
625
+ const usedPercent = typeof cu?.percent === 'number'
626
+ ? Number(Math.min(100, Math.max(0, cu.percent)).toFixed(1))
627
+ : Number(Math.min(100, (used / Math.max(1, total)) * 100).toFixed(1));
628
+ const remainingTokens = Math.max(0, total - used);
629
+ const remainingPercent = Number(Math.max(0, 100 - usedPercent).toFixed(1));
630
+ return {
631
+ tokens: used,
632
+ contextWindow: total,
633
+ maxTokens: chosenModel.maxTokens || 16384,
634
+ remainingTokens,
635
+ usedPercent,
636
+ remainingPercent,
637
+ compactionEnabled: runtimeSettings.compactionEnabled,
638
+ compactAtPercent: runtimeSettings.compactionTriggerPercent,
639
+ keepRecentTokens: runtimeSettings.keepRecentTokens,
640
+ thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
641
+ transport: runtimeSettings.transport,
642
+ model: `${chosenModel.provider}/${chosenModel.id}`,
643
+ totalTokens: stats?.tokens || null,
644
+ cost: typeof stats?.cost === 'number' ? Number(stats.cost.toFixed(4)) : 0,
645
+ updatedAt: new Date().toISOString(),
646
+ };
647
+ } catch {
648
+ return null;
649
+ }
650
+ };
651
+
652
+ emitWrapped({
396
653
  type: 'model',
397
654
  provider: chosenModel.provider,
398
655
  model: chosenModel.id,
656
+ contextWindow: activeCtxWin,
657
+ maxTokens: chosenModel.maxTokens || 16384,
658
+ thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
659
+ transport: runtimeSettings.transport,
399
660
  });
661
+ const initUsage = readContextUsageSnapshot();
662
+ if (initUsage) {
663
+ latestContextUsage = initUsage;
664
+ emitWrapped({ type: 'usage', usage: initUsage });
665
+ }
666
+
667
+ const summarizeToolArgs = (name, args) => {
668
+ if (!args || typeof args !== 'object') return '';
669
+ const pick = args.path || args.file_path || args.file || args.command || args.cmd || args.query || args.pattern || args.title || args.heading || args.templateId || '';
670
+ if (pick) return String(pick).replace(/\s+/g, ' ').trim().slice(0, 110);
671
+ const keys = Object.keys(args);
672
+ if (!keys.length) return '';
673
+ try {
674
+ return JSON.stringify(args).slice(0, 100);
675
+ } catch {
676
+ return '';
677
+ }
678
+ };
679
+ const summarizeToolResult = result => {
680
+ if (!result) return '';
681
+ if (typeof result === 'string') return result.trim().slice(0, 360);
682
+ const blocksList = Array.isArray(result.content) ? result.content : [];
683
+ const txt = blocksList.filter(b => b?.type === 'text' && b.text).map(b => b.text).join('\n').trim();
684
+ return txt.slice(0, 360);
685
+ };
686
+
687
+ const activeToolMeta = new Map();
688
+ const activeCodeMeta = new Map();
689
+ let lastDraftEmitAt = 0;
690
+ let cachedCardTitles = null;
691
+
692
+ const readCanvasCardTitles = () => {
693
+ if (cachedCardTitles) return cachedCardTitles;
694
+ cachedCardTitles = [];
695
+ if (!canvas?.file || !documentRoot) return cachedCardTitles;
696
+ try {
697
+ const full = workspacePath(documentRoot, canvas.file, true);
698
+ if (existsSync(full)) {
699
+ const md = readFileSync(full, 'utf8');
700
+ const matches = md.match(/^#\s+(.+)$/gm) || [];
701
+ cachedCardTitles = matches.map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
702
+ }
703
+ } catch {}
704
+ return cachedCardTitles;
705
+ };
706
+
707
+ const matchCanvasCardsForCodePath = relPath => {
708
+ const titles = readCanvasCardTitles();
709
+ if (!titles.length || !relPath) return [];
710
+ const base = basename(relPath);
711
+ const stem = basename(relPath, extname(relPath)).toLowerCase();
712
+ const relLower = relPath.toLowerCase();
713
+ const matched = [];
714
+ for (const t of titles) {
715
+ const tl = t.toLowerCase();
716
+ if (
717
+ (stem.length >= 3 && tl.includes(stem))
718
+ || tl.includes(base.toLowerCase())
719
+ || (tl.length >= 4 && relLower.includes(tl.split(/[.#((\s]/)[0]))
720
+ ) {
721
+ matched.push([t]);
722
+ }
723
+ }
724
+ return matched.slice(0, 4);
725
+ };
726
+
727
+ const resolveCanvasRelFile = rawPath => {
728
+ if (!rawPath || !documentRoot) return '';
729
+ const abs = resolve(workspace, String(rawPath));
730
+ const docRootAbs = resolve(documentRoot);
731
+ const rel = relative(docRootAbs, abs).split('\\').join('/');
732
+ if (!rel || rel.startsWith('..') || !/\.mdc?$/i.test(rel)) return '';
733
+ return rel;
734
+ };
735
+
736
+ const resolveWorkspaceCodeRel = rawPath => {
737
+ if (!rawPath || !workspace) return '';
738
+ if (resolveCanvasRelFile(rawPath)) return '';
739
+ const wsAbs = resolve(workspace);
740
+ const abs = resolve(wsAbs, String(rawPath));
741
+ const rel = relative(wsAbs, abs).split('\\').join('/');
742
+ if (!rel || rel.startsWith('..') || rel === '.git' || rel.startsWith('.git/')) return '';
743
+ return { abs, rel };
744
+ };
745
+
746
+ const safeReadCodeSnapshot = abs => {
747
+ try {
748
+ if (!existsSync(abs)) return null;
749
+ const st = statSync(abs);
750
+ if (!st.isFile() || st.size > 262144) return null;
751
+ const buf = readFileSync(abs);
752
+ if (buf.subarray(0, 4096).includes(0)) return null;
753
+ return buf.toString('utf8');
754
+ } catch {
755
+ return null;
756
+ }
757
+ };
758
+
759
+ const inferCanvasActivity = (toolName, args) => {
760
+ if (!args || typeof args !== 'object') return null;
761
+ if (['clado_nodes', 'clado_links', 'clado_update', 'clado_create'].includes(toolName)) {
762
+ if (toolName === 'clado_links' && (args.action || 'list') === 'list') return null;
763
+ const file = String(args.file || canvas?.file || '').trim();
764
+ const nodes = [];
765
+ if (Array.isArray(args.node) && args.node.length) nodes.push(args.node);
766
+ if (Array.isArray(args.targetNode) && args.targetNode.length && !args.targetFile) nodes.push(args.targetNode);
767
+ if (Array.isArray(args.operations)) {
768
+ for (const op of args.operations) {
769
+ if (Array.isArray(op?.node) && op.node.length) nodes.push(op.node);
770
+ else if (op?.title) nodes.push([...(Array.isArray(op.parent) ? op.parent : []), op.title]);
771
+ }
772
+ }
773
+ const labelTarget = nodes[0]?.at(-1) || args.title || file || '画布';
774
+ const verb = toolName === 'clado_create' ? '正在创建' : toolName === 'clado_links' ? '正在连线' : '正在编辑';
775
+ return { file, kind: 'editing', nodes: nodes.slice(0, 8), label: `AI ${verb} · ${labelTarget}`, isDirectFile: false };
776
+ }
777
+ if (['clado_read', 'clado_graph'].includes(toolName)) {
778
+ const file = String(args.file || canvas?.file || '').trim();
779
+ return { file, kind: 'read', nodes: [], label: `AI 正在查看 · ${file || '画布拓扑'}`, isDirectFile: false };
780
+ }
781
+ if (['edit', 'write'].includes(toolName)) {
782
+ const rel = resolveCanvasRelFile(args.path || args.file_path || args.file);
783
+ if (rel) {
784
+ return { file: rel, kind: 'editing', nodes: [], label: `AI 正在编辑 · ${rel}`, isDirectFile: true };
785
+ }
786
+ }
787
+ return null;
788
+ };
789
+
790
+ const maybeEmitCanvasDraft = msg => {
791
+ const now = Date.now();
792
+ if (now - lastDraftEmitAt < 150) return;
793
+ const content = Array.isArray(msg?.content) ? msg.content : [];
794
+ let latest = null;
795
+ for (let i = content.length - 1; i >= 0; i--) {
796
+ const c = content[i];
797
+ if (c?.type === 'toolCall' && ['clado_create', 'clado_update', 'clado_nodes'].includes(c.name)) {
798
+ latest = c;
799
+ break;
800
+ }
801
+ }
802
+ if (!latest || !latest.arguments || typeof latest.arguments !== 'object') return;
803
+ const args = latest.arguments;
804
+ const file = String(args.file || canvas?.file || '').trim();
805
+ let title = String(args.title || '').trim();
806
+ let preview = '';
807
+ if (typeof args.content === 'string' && args.content.trim()) {
808
+ const lines = args.content.replace(/\r\n?/g, '\n').split('\n');
809
+ if (!title) {
810
+ const h1 = [...lines].reverse().find(l => /^#\s+/.test(l));
811
+ if (h1) title = h1.replace(/^#\s+/, '').trim();
812
+ }
813
+ preview = lines.slice(-10).join('\n').trim();
814
+ } else if (Array.isArray(args.operations) && args.operations.length) {
815
+ const lastOp = args.operations[args.operations.length - 1];
816
+ if (lastOp && typeof lastOp === 'object') {
817
+ title = lastOp.title || (Array.isArray(lastOp.node) ? lastOp.node.at(-1) : '') || title;
818
+ const bodyStr = String(lastOp.body || lastOp.content || '').trim();
819
+ if (bodyStr) preview = bodyStr.split('\n').slice(-8).join('\n');
820
+ }
821
+ }
822
+ if (!title && !preview) return;
823
+ lastDraftEmitAt = now;
824
+ draftActive = true;
825
+ events?.emit(workspace, 'canvas.draft', {
826
+ active: true,
827
+ toolName: latest.name,
828
+ file,
829
+ title: title || file || '新卡片',
830
+ preview: preview.slice(0, 600),
831
+ roleName: role.name,
832
+ });
833
+ };
400
834
 
401
835
  unsub = session.subscribe(ev => {
402
836
  if (ev.type === 'message_update') {
403
837
  const ae = ev.assistantMessageEvent;
404
838
  if (ae?.type === 'text_delta' && ae.delta) {
405
- assistantText += ae.delta;
406
- emit({ type: 'text', text: ae.delta });
839
+ appendTextDelta(ae.delta);
840
+ emitWrapped({ type: 'text', text: ae.delta });
407
841
  } else if (ae?.type === 'thinking_delta' && ae.delta) {
408
- emit({ type: 'thinking', text: ae.delta });
842
+ appendThinkingDelta(ae.delta);
843
+ emitWrapped({ type: 'thinking', text: ae.delta });
844
+ } else if (ae?.type === 'toolcall_delta') {
845
+ maybeEmitCanvasDraft(ev.message || ae.partial);
409
846
  }
410
847
  } 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' });
848
+ const argsSummary = summarizeToolArgs(ev.toolName, ev.args);
849
+ const canvasAct = inferCanvasActivity(ev.toolName, ev.args);
850
+ if (canvasAct) {
851
+ activeToolMeta.set(ev.toolCallId, canvasAct);
852
+ events?.emit(workspace, 'agent.activity', {
853
+ file: canvasAct.file,
854
+ action: ev.toolName,
855
+ kind: canvasAct.kind,
856
+ nodes: canvasAct.nodes,
857
+ label: canvasAct.label,
858
+ });
859
+ } else if (['edit', 'write', 'read'].includes(ev.toolName)) {
860
+ const codeTarget = resolveWorkspaceCodeRel(ev.args?.path || ev.args?.file_path || ev.args?.file);
861
+ if (codeTarget) {
862
+ const before = ev.toolName === 'read' ? null : safeReadCodeSnapshot(codeTarget.abs);
863
+ const matchedCards = matchCanvasCardsForCodePath(codeTarget.rel);
864
+ activeCodeMeta.set(ev.toolCallId, {
865
+ ...codeTarget,
866
+ action: ev.toolName,
867
+ before,
868
+ matchedCards,
869
+ });
870
+ events?.emit(workspace, 'code.activity', {
871
+ path: codeTarget.rel,
872
+ action: ev.toolName,
873
+ phase: ev.toolName === 'read' ? 'reading' : 'editing',
874
+ matchedCards,
875
+ roleId: role.id,
876
+ roleName: role.name,
877
+ });
878
+ }
879
+ }
880
+ upsertToolEntry({
881
+ id: ev.toolCallId,
882
+ name: ev.toolName,
883
+ argsSummary,
884
+ status: 'running',
885
+ isError: false,
886
+ resultPreview: '',
887
+ });
888
+ emitWrapped({
889
+ type: 'tool',
890
+ id: ev.toolCallId,
891
+ name: ev.toolName,
892
+ argsSummary,
893
+ title: argsSummary ? `${ev.toolName} ${argsSummary}` : ev.toolName,
894
+ status: 'running',
895
+ isError: false,
896
+ });
414
897
  } 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({
898
+ const resultPreview = summarizeToolResult(ev.result);
899
+ const isFailed = Boolean(
900
+ ev.isError
901
+ || ev.result?.isError === true
902
+ || ev.result?.details?.ok === false
903
+ || resultPreview.startsWith('[TOOL_ERROR]')
904
+ );
905
+ if (draftActive && ['clado_create', 'clado_update', 'clado_nodes'].includes(ev.toolName)) {
906
+ draftActive = false;
907
+ events?.emit(workspace, 'canvas.draft', { active: false });
908
+ }
909
+ const canvasAct = activeToolMeta.get(ev.toolCallId);
910
+ activeToolMeta.delete(ev.toolCallId);
911
+ if (canvasAct) {
912
+ cachedCardTitles = null;
913
+ if (isFailed) {
914
+ events?.emit(workspace, 'agent.activity', { file: canvasAct.file, kind: 'clear', nodes: [] });
915
+ } else if (canvasAct.isDirectFile && canvasAct.file) {
916
+ events?.emit(workspace, 'doc.updated', {
917
+ file: canvasAct.file,
918
+ action: 'update',
919
+ nodes: [],
920
+ label: `AI 更新画布 · ${canvasAct.file}`,
921
+ });
922
+ }
923
+ }
924
+ const codeAct = activeCodeMeta.get(ev.toolCallId);
925
+ activeCodeMeta.delete(ev.toolCallId);
926
+ if (codeAct && !isFailed && ['edit', 'write'].includes(codeAct.action)) {
927
+ const after = safeReadCodeSnapshot(codeAct.abs);
928
+ if (after !== null) {
929
+ events?.emit(workspace, 'code.diff', {
930
+ path: codeAct.rel,
931
+ action: codeAct.action,
932
+ before: codeAct.before,
933
+ after,
934
+ isNew: codeAct.before === null,
935
+ matchedCards: codeAct.matchedCards,
936
+ roleId: role.id,
937
+ roleName: role.name,
938
+ });
939
+ }
940
+ }
941
+ const updated = upsertToolEntry({
942
+ id: ev.toolCallId,
943
+ name: ev.toolName,
944
+ status: isFailed ? 'failed' : 'completed',
945
+ isError: isFailed,
946
+ resultPreview,
947
+ });
948
+ emitWrapped({
418
949
  type: 'tool',
419
950
  id: ev.toolCallId,
420
951
  name: ev.toolName,
421
- title: ev.toolName,
422
- status: ev.isError ? 'failed' : 'completed',
952
+ argsSummary: updated?.argsSummary || '',
953
+ resultPreview,
954
+ title: updated?.argsSummary ? `${ev.toolName} ${updated.argsSummary}` : ev.toolName,
955
+ status: isFailed ? 'failed' : 'completed',
956
+ isError: isFailed,
423
957
  });
958
+ } else if (ev.type === 'message_end') {
959
+ const snapUsage = readContextUsageSnapshot();
960
+ if (snapUsage) {
961
+ latestContextUsage = snapUsage;
962
+ emitWrapped({ type: 'usage', usage: snapUsage });
963
+ }
424
964
  } else if (ev.type === 'compaction_start') {
425
- emit({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
965
+ emitWrapped({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
966
+ } else if (ev.type === 'compaction_end') {
967
+ const snapUsage = readContextUsageSnapshot();
968
+ if (snapUsage) {
969
+ latestContextUsage = snapUsage;
970
+ emitWrapped({ type: 'usage', usage: snapUsage });
971
+ }
972
+ if (!ev.aborted && !ev.errorMessage) {
973
+ emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
974
+ }
426
975
  } else if (ev.type === 'auto_retry_start') {
427
- emit({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
976
+ emitWrapped({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
428
977
  }
429
978
  });
430
979
 
431
980
  const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
432
981
  await session.prompt(promptText);
982
+ const finalUsage = readContextUsageSnapshot();
983
+ if (finalUsage) {
984
+ latestContextUsage = finalUsage;
985
+ emitWrapped({ type: 'usage', usage: finalUsage });
986
+ }
433
987
  }
434
988
 
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 || '' });
989
+ persistAssistantTurn({ stopped: abortedByUser });
990
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser, usage: latestContextUsage });
453
991
  } catch (err) {
454
- upsertSessionMeta(stateDir, { id: cleanId, status: 'idle' }, agentDir);
455
- emit({ type: 'error', message: err?.message || 'Pi 执行失败' });
992
+ if (abortedByUser) {
993
+ persistAssistantTurn({ stopped: true });
994
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true, usage: latestContextUsage });
995
+ } else {
996
+ const msg = err?.message || 'Pi 执行失败';
997
+ persistAssistantTurn({ errorMsg: msg });
998
+ emitWrapped({ type: 'error', message: msg });
999
+ }
456
1000
  } finally {
1001
+ if (draftActive) {
1002
+ draftActive = false;
1003
+ events?.emit(workspace, 'canvas.draft', { active: false });
1004
+ }
457
1005
  liveRuns.delete(`${workspace}::${cleanId}`);
458
1006
  try { unsub?.(); } catch {}
459
1007
  try { session?.dispose?.(); } catch {}
460
1008
  }
461
1009
  }
462
1010
 
1011
+ async function compactSession({ workspace, stateDir, sessionId, customInstructions = '' }) {
1012
+ const cleanId = safeSessionId(sessionId);
1013
+ const runKey = `${workspace}::${cleanId}`;
1014
+ if (liveRuns.has(runKey)) {
1015
+ throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
1016
+ }
1017
+ const agentDir = resolvePiAgentDir();
1018
+ const meta = getSessionMeta(stateDir, cleanId, agentDir);
1019
+ if (!meta) throw new Error('找不到目标会话。');
1020
+ if (!meta.piSessionFile || !existsSync(meta.piSessionFile)) {
1021
+ return { ok: true, skipped: true, reason: '当前会话尚无需要压缩的历史记录。', session: meta };
1022
+ }
1023
+ const sm = SettingsManager.create(workspace, agentDir);
1024
+ const mr = await createCladoModelRuntime(agentDir);
1025
+ const chosenModel = await resolvePiModel(mr, sm, meta.model);
1026
+ if (!chosenModel) throw new Error('尚未配置可用模型,无法执行上下文压缩。');
1027
+
1028
+ const activeCtxWin = chosenModel.contextWindow || 128000;
1029
+ const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
1030
+ const loader = new DefaultResourceLoader({ cwd: workspace, agentDir, settingsManager: sm, noThemes: true });
1031
+ await loader.reload();
1032
+ const sessionManager = SessionManager.open(meta.piSessionFile);
1033
+ const created = await createAgentSession({
1034
+ cwd: workspace,
1035
+ agentDir,
1036
+ modelRuntime: mr,
1037
+ model: chosenModel,
1038
+ settingsManager: sm,
1039
+ resourceLoader: loader,
1040
+ sessionManager,
1041
+ });
1042
+ const session = created.session;
1043
+ try {
1044
+ await session.compact(customInstructions || undefined);
1045
+ const cu = session.getContextUsage?.();
1046
+ const total = cu?.contextWindow || activeCtxWin;
1047
+ const used = typeof cu?.tokens === 'number' ? cu.tokens : 0;
1048
+ const usedPercent = typeof cu?.percent === 'number' ? Number(cu.percent.toFixed(1)) : Number(((used / Math.max(1, total)) * 100).toFixed(1));
1049
+ const contextUsage = {
1050
+ tokens: used,
1051
+ contextWindow: total,
1052
+ maxTokens: chosenModel.maxTokens || 16384,
1053
+ remainingTokens: Math.max(0, total - used),
1054
+ usedPercent,
1055
+ remainingPercent: Number(Math.max(0, 100 - usedPercent).toFixed(1)),
1056
+ compactionEnabled: runtimeSettings.compactionEnabled,
1057
+ compactAtPercent: runtimeSettings.compactionTriggerPercent,
1058
+ keepRecentTokens: runtimeSettings.keepRecentTokens,
1059
+ thinkingLevel: runtimeSettings.thinkingLevel,
1060
+ transport: runtimeSettings.transport,
1061
+ model: `${chosenModel.provider}/${chosenModel.id}`,
1062
+ updatedAt: new Date().toISOString(),
1063
+ };
1064
+ const updated = upsertSessionMeta(stateDir, { id: cleanId, contextUsage }, agentDir);
1065
+ return { ok: true, contextUsage, session: updated };
1066
+ } finally {
1067
+ try { session?.dispose?.(); } catch {}
1068
+ }
1069
+ }
1070
+
463
1071
  return {
464
1072
  runTurn,
1073
+ compactSession,
465
1074
  answer(workspace, sessionId, questionId, answerText) {
466
1075
  const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
467
1076
  return run ? run.answer(questionId, answerText) : false;