cladogram 0.6.0-beta.2 → 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.
@@ -6,8 +6,8 @@
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';
@@ -210,6 +212,13 @@ export function buildTurnContextBlock({ workspace, role, canvas, text, handoffFr
210
212
  const objStr = canvas.objectSelection.map(o => `${o.title || o.id}(${o.kind})`).join(';');
211
213
  lines.push(`用户选中的画布组件:${objStr}`);
212
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
+ }
213
222
  }
214
223
  if (lines.length) {
215
224
  return `[Clado 工作区上下文 · 角色:${role.name}]\n${lines.join('\n')}\n\n${text}`;
@@ -284,8 +293,18 @@ export function createPiBridge({
284
293
  }, agentDir);
285
294
  const role = resolveRole(meta.roleId, agentDir);
286
295
 
287
- // Auto-title brand-new custom sessions on their first message
288
- const existingMessages = Array.isArray(meta.messages) ? meta.messages : [];
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
+ });
289
308
  const shouldAutoTitle = existingMessages.length === 0 && !cleanId.startsWith('role_') && (meta.title === role.name || meta.title.startsWith(role.name + ' · 新会话'));
290
309
  const autoTitle = shouldAutoTitle ? text.replace(/\s+/g, ' ').trim().slice(0, 22) : undefined;
291
310
 
@@ -315,6 +334,8 @@ export function createPiBridge({
315
334
  const waitForUserAnswer = (questionId, signal) => new Promise((resolveAnswer, rejectAnswer) => {
316
335
  const onAbort = () => {
317
336
  pendingQuestions.delete(questionId);
337
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
338
+ if (rec && !rec.answered) rec.dismissed = true;
318
339
  rejectAnswer(new Error('已停止生成'));
319
340
  };
320
341
  signal?.addEventListener('abort', onAbort, { once: true });
@@ -323,12 +344,14 @@ export function createPiBridge({
323
344
  signal?.removeEventListener('abort', onAbort);
324
345
  pendingQuestions.delete(questionId);
325
346
  const rec = recordedQuestions.find(q => q.questionId === questionId);
326
- if (rec) { rec.answered = true; rec.answer = ans; }
347
+ if (rec) { rec.answered = true; rec.answer = ans; rec.dismissed = false; }
327
348
  resolveAnswer(ans);
328
349
  },
329
350
  reject(err) {
330
351
  signal?.removeEventListener('abort', onAbort);
331
352
  pendingQuestions.delete(questionId);
353
+ const rec = recordedQuestions.find(q => q.questionId === questionId);
354
+ if (rec && !rec.answered) rec.dismissed = true;
332
355
  rejectAnswer(err);
333
356
  },
334
357
  });
@@ -358,12 +381,67 @@ export function createPiBridge({
358
381
 
359
382
  let assistantText = '';
360
383
  const toolLog = [];
384
+ const blocks = [];
361
385
  let session = null;
362
386
  let unsub = null;
363
387
  let abortedByUser = false;
364
388
  let piSessionFile = meta.piSessionFile || '';
365
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
+
366
443
  const turnAbort = new AbortController();
444
+ let draftActive = false;
367
445
 
368
446
  const runState = {
369
447
  sessionId: cleanId,
@@ -391,17 +469,31 @@ export function createPiBridge({
391
469
  liveRuns.set(`${workspace}::${cleanId}`, runState);
392
470
 
393
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
+ }
394
484
  const finalText = assistantText
395
485
  + (stopped ? (assistantText ? '\n\n' : '') + '_(已手动停止,以上内容已保留)_' : '')
396
486
  + (errorMsg ? (assistantText ? '\n\n' : '') + '提示:' + errorMsg : '');
397
487
  const curMeta = getSessionMeta(stateDir, cleanId, agentDir);
398
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));
399
490
  const assistantMsg = {
400
491
  id: 'm_' + randomUUID().replace(/-/g, '').slice(0, 10),
401
492
  role: 'assistant',
402
493
  text: finalText,
403
494
  tools: toolLog,
404
- questions: recordedQuestions,
495
+ blocks,
496
+ questions: finalizedQuestions,
405
497
  stopped: Boolean(stopped),
406
498
  snapshotId: snap?.id || '',
407
499
  timestamp: new Date().toISOString(),
@@ -411,32 +503,32 @@ export function createPiBridge({
411
503
  id: cleanId,
412
504
  status: 'idle',
413
505
  ...(piSessionFile ? { piSessionFile } : {}),
506
+ ...(latestContextUsage ? { contextUsage: latestContextUsage } : {}),
414
507
  summaryBadge: badge,
415
508
  messages: [...baseMsgs, assistantMsg].slice(-80),
416
509
  }, agentDir);
417
510
  };
418
511
 
512
+ let latestContextUsage = meta.contextUsage || null;
513
+
419
514
  try {
420
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
+ });
421
525
 
422
526
  if (sessionFactory) {
423
527
  const factoryEmit = ev => {
424
- if (ev?.type === 'text' && ev.text) assistantText += ev.text;
425
- if (ev?.type === 'tool') {
426
- const existing = toolLog.find(t => t.id === ev.id);
427
- if (existing) {
428
- existing.status = ev.status || existing.status;
429
- if (ev.resultPreview !== undefined) existing.resultPreview = ev.resultPreview;
430
- } else {
431
- toolLog.push({
432
- id: ev.id,
433
- name: ev.name || ev.title || 'tool',
434
- argsSummary: ev.argsSummary || '',
435
- status: ev.status || 'running',
436
- resultPreview: ev.resultPreview || '',
437
- });
438
- }
439
- }
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;
440
532
  emitWrapped(ev);
441
533
  };
442
534
  const result = await sessionFactory({
@@ -448,11 +540,12 @@ export function createPiBridge({
448
540
  text,
449
541
  canvas,
450
542
  cladoTools,
543
+ events,
451
544
  emit: factoryEmit,
452
545
  waitForUserAnswer,
453
546
  signal: turnAbort.signal,
454
547
  });
455
- if (!assistantText && result?.text) assistantText = String(result.text);
548
+ if (!assistantText && result?.text) appendTextDelta(String(result.text));
456
549
  } else {
457
550
  const sm = SettingsManager.create(workspace, agentDir);
458
551
  const mr = await createCladoModelRuntime(agentDir);
@@ -461,6 +554,25 @@ export function createPiBridge({
461
554
  throw new Error('尚未配置可用模型。请点击顶部「设置 → 模型与供应商」填写 API Key 或本地 Ollama 地址。');
462
555
  }
463
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
+
464
576
  const loader = new DefaultResourceLoader({
465
577
  cwd: workspace,
466
578
  agentDir,
@@ -469,7 +581,8 @@ export function createPiBridge({
469
581
  packageCommandOutput: 'capture',
470
582
  appendSystemPrompt: [
471
583
  role.systemPrompt,
472
- '工作区规范:你可以通过 clado_* 工具读写空间画布,也可以直接使用 read/edit/write/bash 工具分析或修改代码。无需向用户弹窗请求命令权限。',
584
+ CLADO_CANVAS_MASTERY_GUIDE,
585
+ '工作区规范:你可以通过 clado_* 工具读写空间画布并读取渲染后的画布拓扑树(clado_graph),也可以直接使用 read/edit/write/bash 工具分析或修改代码。无需向用户弹窗请求命令权限。',
473
586
  '提问规范:如果你需要向用户确认方案或提问,请先完整阐述你的分析与建议,再在最后一步调用 ask_user 工具,避免在回答中途插入问题。',
474
587
  ],
475
588
  });
@@ -495,16 +608,65 @@ export function createPiBridge({
495
608
  customTools: cladoTools,
496
609
  });
497
610
  session = created.session;
611
+ try {
612
+ if (runtimeSettings.thinkingLevel && typeof session.setThinkingLevel === 'function') {
613
+ session.setThinkingLevel(runtimeSettings.thinkingLevel);
614
+ }
615
+ } catch {}
616
+
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
+ };
498
651
 
499
652
  emitWrapped({
500
653
  type: 'model',
501
654
  provider: chosenModel.provider,
502
655
  model: chosenModel.id,
656
+ contextWindow: activeCtxWin,
657
+ maxTokens: chosenModel.maxTokens || 16384,
658
+ thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
659
+ transport: runtimeSettings.transport,
503
660
  });
661
+ const initUsage = readContextUsageSnapshot();
662
+ if (initUsage) {
663
+ latestContextUsage = initUsage;
664
+ emitWrapped({ type: 'usage', usage: initUsage });
665
+ }
504
666
 
505
667
  const summarizeToolArgs = (name, args) => {
506
668
  if (!args || typeof args !== 'object') return '';
507
- const pick = args.path || args.file_path || args.file || args.command || args.cmd || args.query || args.pattern || args.title || args.heading || '';
669
+ const pick = args.path || args.file_path || args.file || args.command || args.cmd || args.query || args.pattern || args.title || args.heading || args.templateId || '';
508
670
  if (pick) return String(pick).replace(/\s+/g, ' ').trim().slice(0, 110);
509
671
  const keys = Object.keys(args);
510
672
  if (!keys.length) return '';
@@ -516,31 +678,213 @@ export function createPiBridge({
516
678
  };
517
679
  const summarizeToolResult = result => {
518
680
  if (!result) return '';
519
- if (typeof result === 'string') return result.trim().slice(0, 220);
520
- const blocks = Array.isArray(result.content) ? result.content : [];
521
- const txt = blocks.filter(b => b?.type === 'text' && b.text).map(b => b.text).join('\n').trim();
522
- return txt.slice(0, 220);
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
+ });
523
833
  };
524
834
 
525
835
  unsub = session.subscribe(ev => {
526
836
  if (ev.type === 'message_update') {
527
837
  const ae = ev.assistantMessageEvent;
528
838
  if (ae?.type === 'text_delta' && ae.delta) {
529
- assistantText += ae.delta;
839
+ appendTextDelta(ae.delta);
530
840
  emitWrapped({ type: 'text', text: ae.delta });
531
841
  } else if (ae?.type === 'thinking_delta' && ae.delta) {
842
+ appendThinkingDelta(ae.delta);
532
843
  emitWrapped({ type: 'thinking', text: ae.delta });
844
+ } else if (ae?.type === 'toolcall_delta') {
845
+ maybeEmitCanvasDraft(ev.message || ae.partial);
533
846
  }
534
847
  } else if (ev.type === 'tool_execution_start') {
535
848
  const argsSummary = summarizeToolArgs(ev.toolName, ev.args);
536
- const entry = {
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({
537
881
  id: ev.toolCallId,
538
882
  name: ev.toolName,
539
883
  argsSummary,
540
884
  status: 'running',
885
+ isError: false,
541
886
  resultPreview: '',
542
- };
543
- toolLog.push(entry);
887
+ });
544
888
  emitWrapped({
545
889
  type: 'tool',
546
890
  id: ev.toolCallId,
@@ -548,25 +892,86 @@ export function createPiBridge({
548
892
  argsSummary,
549
893
  title: argsSummary ? `${ev.toolName} ${argsSummary}` : ev.toolName,
550
894
  status: 'running',
895
+ isError: false,
551
896
  });
552
897
  } else if (ev.type === 'tool_execution_end') {
553
898
  const resultPreview = summarizeToolResult(ev.result);
554
- const existing = toolLog.find(t => t.id === ev.toolCallId);
555
- if (existing) {
556
- existing.status = ev.isError ? 'failed' : 'completed';
557
- existing.resultPreview = resultPreview;
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 });
558
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
+ });
559
948
  emitWrapped({
560
949
  type: 'tool',
561
950
  id: ev.toolCallId,
562
951
  name: ev.toolName,
563
- argsSummary: existing?.argsSummary || '',
952
+ argsSummary: updated?.argsSummary || '',
564
953
  resultPreview,
565
- title: existing?.argsSummary ? `${ev.toolName} ${existing.argsSummary}` : ev.toolName,
566
- status: ev.isError ? 'failed' : 'completed',
954
+ title: updated?.argsSummary ? `${ev.toolName} ${updated.argsSummary}` : ev.toolName,
955
+ status: isFailed ? 'failed' : 'completed',
956
+ isError: isFailed,
567
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
+ }
568
964
  } else if (ev.type === 'compaction_start') {
569
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
+ }
570
975
  } else if (ev.type === 'auto_retry_start') {
571
976
  emitWrapped({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
572
977
  }
@@ -574,28 +979,98 @@ export function createPiBridge({
574
979
 
575
980
  const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
576
981
  await session.prompt(promptText);
982
+ const finalUsage = readContextUsageSnapshot();
983
+ if (finalUsage) {
984
+ latestContextUsage = finalUsage;
985
+ emitWrapped({ type: 'usage', usage: finalUsage });
986
+ }
577
987
  }
578
988
 
579
989
  persistAssistantTurn({ stopped: abortedByUser });
580
- emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser });
990
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser, usage: latestContextUsage });
581
991
  } catch (err) {
582
992
  if (abortedByUser) {
583
993
  persistAssistantTurn({ stopped: true });
584
- emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true });
994
+ emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true, usage: latestContextUsage });
585
995
  } else {
586
996
  const msg = err?.message || 'Pi 执行失败';
587
997
  persistAssistantTurn({ errorMsg: msg });
588
998
  emitWrapped({ type: 'error', message: msg });
589
999
  }
590
1000
  } finally {
1001
+ if (draftActive) {
1002
+ draftActive = false;
1003
+ events?.emit(workspace, 'canvas.draft', { active: false });
1004
+ }
591
1005
  liveRuns.delete(`${workspace}::${cleanId}`);
592
1006
  try { unsub?.(); } catch {}
593
1007
  try { session?.dispose?.(); } catch {}
594
1008
  }
595
1009
  }
596
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
+
597
1071
  return {
598
1072
  runTurn,
1073
+ compactSession,
599
1074
  answer(workspace, sessionId, questionId, answerText) {
600
1075
  const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
601
1076
  return run ? run.answer(questionId, answerText) : false;