cladogram 0.6.0-beta.2 → 0.6.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/clado.js +34 -2
- package/docs/agent-context.md +62 -0
- package/docs/agent-reference.md +126 -0
- package/docs/release.md +15 -0
- package/package.json +3 -1
- package/plugins/agent/index.js +974 -124
- package/plugins/agent/style.css +502 -52
- package/src/agent/clado-tools.js +437 -103
- package/src/agent/pi-bridge.js +588 -43
- package/src/agent/pi-config.js +411 -35
- package/src/html/app-css.js +65 -1
- package/src/html/canvas-chain.js +26 -2
- package/src/html/canvas-focus.js +19 -13
- package/src/html/canvas-live-diff.js +1256 -0
- package/src/html/canvas-ui.css +508 -0
- package/src/html/canvas-wires.js +5 -1
- package/src/html/page.js +4 -2
- package/src/html/runtime-api.js +146 -10
- package/src/html/runtime.js +432 -29
- package/src/server/agent.js +55 -8
- package/src/server/assets/library-canvas.js +252 -9
- package/src/server/assets/library.css +416 -0
- package/src/server/assets/library.html +2 -0
- package/src/server/assets/library.js +744 -14
- package/src/server/code-inspect.js +183 -0
- package/src/server/mcp.js +4 -4
- package/src/server/workspace.js +266 -19
- package/src/workspace/graph-snapshot.js +695 -0
- package/src/workspace/service.js +11 -1
package/src/agent/pi-bridge.js
CHANGED
|
@@ -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,
|
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
} from '@earendil-works/pi-coding-agent';
|
|
17
17
|
import {
|
|
18
18
|
createCladoModelRuntime,
|
|
19
|
+
readCladoPlatformContext,
|
|
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
|
-
|
|
495
|
+
blocks,
|
|
496
|
+
questions: finalizedQuestions,
|
|
405
497
|
stopped: Boolean(stopped),
|
|
406
498
|
snapshotId: snap?.id || '',
|
|
407
499
|
timestamp: new Date().toISOString(),
|
|
@@ -411,31 +503,69 @@ 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
|
+
let presenceTouched = false;
|
|
514
|
+
const selectedCardTitles = [...new Set(
|
|
515
|
+
(Array.isArray(canvas?.selection) ? canvas.selection : [])
|
|
516
|
+
.map(item => (Array.isArray(item) ? item[0] : (Array.isArray(item?.nodePath) ? item.nodePath[0] : (typeof item === 'string' ? item : ''))))
|
|
517
|
+
.map(s => String(s || '').trim())
|
|
518
|
+
.filter(Boolean)
|
|
519
|
+
)];
|
|
520
|
+
const emitPresence = (payload = {}) => {
|
|
521
|
+
if (!events) return;
|
|
522
|
+
const phase = payload.phase || 'active';
|
|
523
|
+
if (phase === 'active') presenceTouched = true;
|
|
524
|
+
events.emit(workspace, 'agent.presence', {
|
|
525
|
+
sessionId: cleanId,
|
|
526
|
+
roleId: role.id,
|
|
527
|
+
roleName: role.name,
|
|
528
|
+
tone: role.tone || 'sky',
|
|
529
|
+
file: payload.file || canvas?.file || '',
|
|
530
|
+
cards: Array.isArray(payload.cards) ? payload.cards : [],
|
|
531
|
+
label: payload.label || '',
|
|
532
|
+
codePath: payload.codePath || '',
|
|
533
|
+
phase,
|
|
534
|
+
ts: Date.now(),
|
|
535
|
+
});
|
|
536
|
+
};
|
|
537
|
+
|
|
419
538
|
try {
|
|
420
539
|
emitWrapped({ type: 'session', sessionId: cleanId, roleId: role.id, roleName: role.name, snapshotId: snap?.id || '' });
|
|
540
|
+
events?.emit(workspace, 'agent.stage', {
|
|
541
|
+
sessionId: cleanId,
|
|
542
|
+
roleId: role.id,
|
|
543
|
+
roleName: role.name,
|
|
544
|
+
phase: role.phase || '',
|
|
545
|
+
tone: role.tone || 'sky',
|
|
546
|
+
handoffFrom: handoffFrom || '',
|
|
547
|
+
file: canvas?.file || '',
|
|
548
|
+
});
|
|
549
|
+
if (selectedCardTitles.length) {
|
|
550
|
+
const phaseVerb = role.phase ? role.phase.replace(/阶段$/, '') : '处理';
|
|
551
|
+
emitPresence({
|
|
552
|
+
phase: 'active',
|
|
553
|
+
cards: selectedCardTitles,
|
|
554
|
+
label: `${phaseVerb}中…`,
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const platformContext = readCladoPlatformContext(agentDir);
|
|
421
559
|
|
|
422
560
|
if (sessionFactory) {
|
|
423
561
|
const factoryEmit = ev => {
|
|
424
|
-
if (ev?.type === '
|
|
425
|
-
if (ev?.type === '
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
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
|
-
}
|
|
562
|
+
if (ev?.type === 'thinking' && ev.text) appendThinkingDelta(ev.text);
|
|
563
|
+
if (ev?.type === 'text' && ev.text) appendTextDelta(ev.text);
|
|
564
|
+
if (ev?.type === 'tool') upsertToolEntry(ev);
|
|
565
|
+
if (ev?.type === 'usage' && ev.usage) latestContextUsage = ev.usage;
|
|
566
|
+
if (ev?.type === 'presence') {
|
|
567
|
+
emitPresence(ev);
|
|
568
|
+
return;
|
|
439
569
|
}
|
|
440
570
|
emitWrapped(ev);
|
|
441
571
|
};
|
|
@@ -445,14 +575,16 @@ export function createPiBridge({
|
|
|
445
575
|
documentRoot,
|
|
446
576
|
sessionId: cleanId,
|
|
447
577
|
role,
|
|
578
|
+
platformContext,
|
|
448
579
|
text,
|
|
449
580
|
canvas,
|
|
450
581
|
cladoTools,
|
|
582
|
+
events,
|
|
451
583
|
emit: factoryEmit,
|
|
452
584
|
waitForUserAnswer,
|
|
453
585
|
signal: turnAbort.signal,
|
|
454
586
|
});
|
|
455
|
-
if (!assistantText && result?.text)
|
|
587
|
+
if (!assistantText && result?.text) appendTextDelta(String(result.text));
|
|
456
588
|
} else {
|
|
457
589
|
const sm = SettingsManager.create(workspace, agentDir);
|
|
458
590
|
const mr = await createCladoModelRuntime(agentDir);
|
|
@@ -461,6 +593,25 @@ export function createPiBridge({
|
|
|
461
593
|
throw new Error('尚未配置可用模型。请点击顶部「设置 → 模型与供应商」填写 API Key 或本地 Ollama 地址。');
|
|
462
594
|
}
|
|
463
595
|
|
|
596
|
+
const activeCtxWin = chosenModel.contextWindow || 128000;
|
|
597
|
+
const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
|
|
598
|
+
const effectiveReserveTokens = Math.max(4096, Math.round(activeCtxWin * (1 - runtimeSettings.compactionTriggerPercent / 100)));
|
|
599
|
+
sm.applyOverrides({
|
|
600
|
+
defaultThinkingLevel: runtimeSettings.thinkingLevel,
|
|
601
|
+
transport: runtimeSettings.transport,
|
|
602
|
+
hideThinkingBlock: runtimeSettings.hideThinkingBlock,
|
|
603
|
+
cacheWarming: runtimeSettings.cacheWarming,
|
|
604
|
+
compaction: {
|
|
605
|
+
enabled: runtimeSettings.compactionEnabled,
|
|
606
|
+
reserveTokens: effectiveReserveTokens,
|
|
607
|
+
keepRecentTokens: runtimeSettings.keepRecentTokens,
|
|
608
|
+
},
|
|
609
|
+
retry: {
|
|
610
|
+
enabled: runtimeSettings.retryEnabled,
|
|
611
|
+
maxRetries: runtimeSettings.maxRetries,
|
|
612
|
+
},
|
|
613
|
+
});
|
|
614
|
+
|
|
464
615
|
const loader = new DefaultResourceLoader({
|
|
465
616
|
cwd: workspace,
|
|
466
617
|
agentDir,
|
|
@@ -469,9 +620,8 @@ export function createPiBridge({
|
|
|
469
620
|
packageCommandOutput: 'capture',
|
|
470
621
|
appendSystemPrompt: [
|
|
471
622
|
role.systemPrompt,
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
],
|
|
623
|
+
platformContext,
|
|
624
|
+
].filter(Boolean),
|
|
475
625
|
});
|
|
476
626
|
await loader.reload();
|
|
477
627
|
|
|
@@ -495,16 +645,65 @@ export function createPiBridge({
|
|
|
495
645
|
customTools: cladoTools,
|
|
496
646
|
});
|
|
497
647
|
session = created.session;
|
|
648
|
+
try {
|
|
649
|
+
if (runtimeSettings.thinkingLevel && typeof session.setThinkingLevel === 'function') {
|
|
650
|
+
session.setThinkingLevel(runtimeSettings.thinkingLevel);
|
|
651
|
+
}
|
|
652
|
+
} catch {}
|
|
653
|
+
|
|
654
|
+
const readContextUsageSnapshot = () => {
|
|
655
|
+
try {
|
|
656
|
+
const cu = session.getContextUsage?.();
|
|
657
|
+
const stats = session.getSessionStats?.();
|
|
658
|
+
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'
|
|
663
|
+
? Number(Math.min(100, Math.max(0, cu.percent)).toFixed(1))
|
|
664
|
+
: Number(Math.min(100, (used / Math.max(1, total)) * 100).toFixed(1));
|
|
665
|
+
const remainingTokens = Math.max(0, total - used);
|
|
666
|
+
const remainingPercent = Number(Math.max(0, 100 - usedPercent).toFixed(1));
|
|
667
|
+
return {
|
|
668
|
+
tokens: used,
|
|
669
|
+
contextWindow: total,
|
|
670
|
+
maxTokens: chosenModel.maxTokens || 16384,
|
|
671
|
+
remainingTokens,
|
|
672
|
+
usedPercent,
|
|
673
|
+
remainingPercent,
|
|
674
|
+
compactionEnabled: runtimeSettings.compactionEnabled,
|
|
675
|
+
compactAtPercent: runtimeSettings.compactionTriggerPercent,
|
|
676
|
+
keepRecentTokens: runtimeSettings.keepRecentTokens,
|
|
677
|
+
thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
|
|
678
|
+
transport: runtimeSettings.transport,
|
|
679
|
+
model: `${chosenModel.provider}/${chosenModel.id}`,
|
|
680
|
+
totalTokens: stats?.tokens || null,
|
|
681
|
+
cost: typeof stats?.cost === 'number' ? Number(stats.cost.toFixed(4)) : 0,
|
|
682
|
+
updatedAt: new Date().toISOString(),
|
|
683
|
+
};
|
|
684
|
+
} catch {
|
|
685
|
+
return null;
|
|
686
|
+
}
|
|
687
|
+
};
|
|
498
688
|
|
|
499
689
|
emitWrapped({
|
|
500
690
|
type: 'model',
|
|
501
691
|
provider: chosenModel.provider,
|
|
502
692
|
model: chosenModel.id,
|
|
693
|
+
contextWindow: activeCtxWin,
|
|
694
|
+
maxTokens: chosenModel.maxTokens || 16384,
|
|
695
|
+
thinkingLevel: session.thinkingLevel || runtimeSettings.thinkingLevel,
|
|
696
|
+
transport: runtimeSettings.transport,
|
|
503
697
|
});
|
|
698
|
+
const initUsage = readContextUsageSnapshot();
|
|
699
|
+
if (initUsage) {
|
|
700
|
+
latestContextUsage = initUsage;
|
|
701
|
+
emitWrapped({ type: 'usage', usage: initUsage });
|
|
702
|
+
}
|
|
504
703
|
|
|
505
704
|
const summarizeToolArgs = (name, args) => {
|
|
506
705
|
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 || '';
|
|
706
|
+
const pick = args.path || args.file_path || args.file || args.command || args.cmd || args.query || args.pattern || args.title || args.heading || args.templateId || '';
|
|
508
707
|
if (pick) return String(pick).replace(/\s+/g, ' ').trim().slice(0, 110);
|
|
509
708
|
const keys = Object.keys(args);
|
|
510
709
|
if (!keys.length) return '';
|
|
@@ -516,31 +715,243 @@ export function createPiBridge({
|
|
|
516
715
|
};
|
|
517
716
|
const summarizeToolResult = result => {
|
|
518
717
|
if (!result) return '';
|
|
519
|
-
if (typeof result === 'string') return result.trim().slice(0,
|
|
520
|
-
const
|
|
521
|
-
const txt =
|
|
522
|
-
return txt.slice(0,
|
|
718
|
+
if (typeof result === 'string') return result.trim().slice(0, 360);
|
|
719
|
+
const blocksList = Array.isArray(result.content) ? result.content : [];
|
|
720
|
+
const txt = blocksList.filter(b => b?.type === 'text' && b.text).map(b => b.text).join('\n').trim();
|
|
721
|
+
return txt.slice(0, 360);
|
|
722
|
+
};
|
|
723
|
+
|
|
724
|
+
const activeToolMeta = new Map();
|
|
725
|
+
const activeCodeMeta = new Map();
|
|
726
|
+
let lastDraftEmitAt = 0;
|
|
727
|
+
let cachedCardTitles = null;
|
|
728
|
+
|
|
729
|
+
const readCanvasCardTitles = () => {
|
|
730
|
+
if (cachedCardTitles) return cachedCardTitles;
|
|
731
|
+
cachedCardTitles = [];
|
|
732
|
+
if (!canvas?.file || !documentRoot) return cachedCardTitles;
|
|
733
|
+
try {
|
|
734
|
+
const full = workspacePath(documentRoot, canvas.file, true);
|
|
735
|
+
if (existsSync(full)) {
|
|
736
|
+
const md = readFileSync(full, 'utf8');
|
|
737
|
+
const matches = md.match(/^#\s+(.+)$/gm) || [];
|
|
738
|
+
cachedCardTitles = matches.map(l => l.replace(/^#\s+/, '').trim()).filter(Boolean);
|
|
739
|
+
}
|
|
740
|
+
} catch {}
|
|
741
|
+
return cachedCardTitles;
|
|
742
|
+
};
|
|
743
|
+
|
|
744
|
+
const matchCanvasCardsForCodePath = relPath => {
|
|
745
|
+
const titles = readCanvasCardTitles();
|
|
746
|
+
if (!titles.length || !relPath) return [];
|
|
747
|
+
const base = basename(relPath);
|
|
748
|
+
const stem = basename(relPath, extname(relPath)).toLowerCase();
|
|
749
|
+
const relLower = relPath.toLowerCase();
|
|
750
|
+
const matched = [];
|
|
751
|
+
for (const t of titles) {
|
|
752
|
+
const tl = t.toLowerCase();
|
|
753
|
+
if (
|
|
754
|
+
(stem.length >= 3 && tl.includes(stem))
|
|
755
|
+
|| tl.includes(base.toLowerCase())
|
|
756
|
+
|| (tl.length >= 4 && relLower.includes(tl.split(/[.#((\s]/)[0]))
|
|
757
|
+
) {
|
|
758
|
+
matched.push([t]);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
return matched.slice(0, 4);
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
const resolveCanvasRelFile = rawPath => {
|
|
765
|
+
if (!rawPath || !documentRoot) return '';
|
|
766
|
+
const abs = resolve(workspace, String(rawPath));
|
|
767
|
+
const docRootAbs = resolve(documentRoot);
|
|
768
|
+
const rel = relative(docRootAbs, abs).split('\\').join('/');
|
|
769
|
+
if (!rel || rel.startsWith('..') || !/\.mdc?$/i.test(rel)) return '';
|
|
770
|
+
return rel;
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
const resolveWorkspaceCodeRel = rawPath => {
|
|
774
|
+
if (!rawPath || !workspace) return '';
|
|
775
|
+
if (resolveCanvasRelFile(rawPath)) return '';
|
|
776
|
+
const wsAbs = resolve(workspace);
|
|
777
|
+
const abs = resolve(wsAbs, String(rawPath));
|
|
778
|
+
const rel = relative(wsAbs, abs).split('\\').join('/');
|
|
779
|
+
if (!rel || rel.startsWith('..') || rel === '.git' || rel.startsWith('.git/')) return '';
|
|
780
|
+
return { abs, rel };
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
const safeReadCodeSnapshot = abs => {
|
|
784
|
+
try {
|
|
785
|
+
if (!existsSync(abs)) return null;
|
|
786
|
+
const st = statSync(abs);
|
|
787
|
+
if (!st.isFile() || st.size > 262144) return null;
|
|
788
|
+
const buf = readFileSync(abs);
|
|
789
|
+
if (buf.subarray(0, 4096).includes(0)) return null;
|
|
790
|
+
return buf.toString('utf8');
|
|
791
|
+
} catch {
|
|
792
|
+
return null;
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
|
|
796
|
+
const inferCanvasActivity = (toolName, args) => {
|
|
797
|
+
if (!args || typeof args !== 'object') return null;
|
|
798
|
+
if (['clado_nodes', 'clado_links', 'clado_update', 'clado_create'].includes(toolName)) {
|
|
799
|
+
if (toolName === 'clado_links' && (args.action || 'list') === 'list') return null;
|
|
800
|
+
const file = String(args.file || canvas?.file || '').trim();
|
|
801
|
+
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);
|
|
804
|
+
if (Array.isArray(args.operations)) {
|
|
805
|
+
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]);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
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 };
|
|
813
|
+
}
|
|
814
|
+
if (['clado_read', 'clado_graph'].includes(toolName)) {
|
|
815
|
+
const file = String(args.file || canvas?.file || '').trim();
|
|
816
|
+
return { file, kind: 'read', nodes: [], label: `AI 正在查看 · ${file || '画布拓扑'}`, isDirectFile: false };
|
|
817
|
+
}
|
|
818
|
+
if (['edit', 'write'].includes(toolName)) {
|
|
819
|
+
const rel = resolveCanvasRelFile(args.path || args.file_path || args.file);
|
|
820
|
+
if (rel) {
|
|
821
|
+
return { file: rel, kind: 'editing', nodes: [], label: `AI 正在编辑 · ${rel}`, isDirectFile: true };
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return null;
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
const maybeEmitCanvasDraft = msg => {
|
|
828
|
+
const now = Date.now();
|
|
829
|
+
if (now - lastDraftEmitAt < 150) return;
|
|
830
|
+
const content = Array.isArray(msg?.content) ? msg.content : [];
|
|
831
|
+
let latest = null;
|
|
832
|
+
for (let i = content.length - 1; i >= 0; i--) {
|
|
833
|
+
const c = content[i];
|
|
834
|
+
if (c?.type === 'toolCall' && ['clado_create', 'clado_update', 'clado_nodes'].includes(c.name)) {
|
|
835
|
+
latest = c;
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
if (!latest || !latest.arguments || typeof latest.arguments !== 'object') return;
|
|
840
|
+
const args = latest.arguments;
|
|
841
|
+
const file = String(args.file || canvas?.file || '').trim();
|
|
842
|
+
let title = String(args.title || '').trim();
|
|
843
|
+
let preview = '';
|
|
844
|
+
if (typeof args.content === 'string' && args.content.trim()) {
|
|
845
|
+
const lines = args.content.replace(/\r\n?/g, '\n').split('\n');
|
|
846
|
+
if (!title) {
|
|
847
|
+
const h1 = [...lines].reverse().find(l => /^#\s+/.test(l));
|
|
848
|
+
if (h1) title = h1.replace(/^#\s+/, '').trim();
|
|
849
|
+
}
|
|
850
|
+
preview = lines.slice(-10).join('\n').trim();
|
|
851
|
+
} else if (Array.isArray(args.operations) && args.operations.length) {
|
|
852
|
+
const lastOp = args.operations[args.operations.length - 1];
|
|
853
|
+
if (lastOp && typeof lastOp === 'object') {
|
|
854
|
+
title = lastOp.title || (Array.isArray(lastOp.node) ? lastOp.node.at(-1) : '') || title;
|
|
855
|
+
const bodyStr = String(lastOp.body || lastOp.content || '').trim();
|
|
856
|
+
if (bodyStr) preview = bodyStr.split('\n').slice(-8).join('\n');
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if (!title && !preview) return;
|
|
860
|
+
lastDraftEmitAt = now;
|
|
861
|
+
draftActive = true;
|
|
862
|
+
events?.emit(workspace, 'canvas.draft', {
|
|
863
|
+
active: true,
|
|
864
|
+
toolName: latest.name,
|
|
865
|
+
file,
|
|
866
|
+
title: title || file || '新卡片',
|
|
867
|
+
preview: preview.slice(0, 600),
|
|
868
|
+
roleName: role.name,
|
|
869
|
+
});
|
|
523
870
|
};
|
|
524
871
|
|
|
525
872
|
unsub = session.subscribe(ev => {
|
|
526
873
|
if (ev.type === 'message_update') {
|
|
527
874
|
const ae = ev.assistantMessageEvent;
|
|
528
875
|
if (ae?.type === 'text_delta' && ae.delta) {
|
|
529
|
-
|
|
876
|
+
appendTextDelta(ae.delta);
|
|
530
877
|
emitWrapped({ type: 'text', text: ae.delta });
|
|
531
878
|
} else if (ae?.type === 'thinking_delta' && ae.delta) {
|
|
879
|
+
appendThinkingDelta(ae.delta);
|
|
532
880
|
emitWrapped({ type: 'thinking', text: ae.delta });
|
|
881
|
+
} else if (ae?.type === 'toolcall_delta') {
|
|
882
|
+
maybeEmitCanvasDraft(ev.message || ae.partial);
|
|
533
883
|
}
|
|
534
884
|
} else if (ev.type === 'tool_execution_start') {
|
|
535
885
|
const argsSummary = summarizeToolArgs(ev.toolName, ev.args);
|
|
536
|
-
const
|
|
886
|
+
const canvasAct = inferCanvasActivity(ev.toolName, ev.args);
|
|
887
|
+
if (canvasAct) {
|
|
888
|
+
activeToolMeta.set(ev.toolCallId, canvasAct);
|
|
889
|
+
events?.emit(workspace, 'agent.activity', {
|
|
890
|
+
file: canvasAct.file,
|
|
891
|
+
action: ev.toolName,
|
|
892
|
+
kind: canvasAct.kind,
|
|
893
|
+
nodes: canvasAct.nodes,
|
|
894
|
+
label: canvasAct.label,
|
|
895
|
+
});
|
|
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
|
+
});
|
|
912
|
+
}
|
|
913
|
+
} else if (['edit', 'write', 'read'].includes(ev.toolName)) {
|
|
914
|
+
const codeTarget = resolveWorkspaceCodeRel(ev.args?.path || ev.args?.file_path || ev.args?.file);
|
|
915
|
+
if (codeTarget) {
|
|
916
|
+
const before = ev.toolName === 'read' ? null : safeReadCodeSnapshot(codeTarget.abs);
|
|
917
|
+
const matchedCards = matchCanvasCardsForCodePath(codeTarget.rel);
|
|
918
|
+
activeCodeMeta.set(ev.toolCallId, {
|
|
919
|
+
...codeTarget,
|
|
920
|
+
action: ev.toolName,
|
|
921
|
+
before,
|
|
922
|
+
matchedCards,
|
|
923
|
+
});
|
|
924
|
+
events?.emit(workspace, 'code.activity', {
|
|
925
|
+
path: codeTarget.rel,
|
|
926
|
+
action: ev.toolName,
|
|
927
|
+
phase: ev.toolName === 'read' ? 'reading' : 'editing',
|
|
928
|
+
matchedCards,
|
|
929
|
+
roleId: role.id,
|
|
930
|
+
roleName: role.name,
|
|
931
|
+
});
|
|
932
|
+
const codeCards = matchedCards
|
|
933
|
+
.map(n => (Array.isArray(n) ? n[0] : String(n || '')))
|
|
934
|
+
.map(s => String(s || '').trim())
|
|
935
|
+
.filter(Boolean);
|
|
936
|
+
const presenceCards = codeCards.length ? codeCards : selectedCardTitles;
|
|
937
|
+
if (presenceCards.length) {
|
|
938
|
+
emitPresence({
|
|
939
|
+
phase: 'active',
|
|
940
|
+
cards: [...new Set(presenceCards)],
|
|
941
|
+
codePath: codeTarget.rel,
|
|
942
|
+
label: `${ev.toolName === 'read' ? '查看' : '修改'} ${codeTarget.rel}`,
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
upsertToolEntry({
|
|
537
948
|
id: ev.toolCallId,
|
|
538
949
|
name: ev.toolName,
|
|
539
950
|
argsSummary,
|
|
540
951
|
status: 'running',
|
|
952
|
+
isError: false,
|
|
541
953
|
resultPreview: '',
|
|
542
|
-
};
|
|
543
|
-
toolLog.push(entry);
|
|
954
|
+
});
|
|
544
955
|
emitWrapped({
|
|
545
956
|
type: 'tool',
|
|
546
957
|
id: ev.toolCallId,
|
|
@@ -548,25 +959,86 @@ export function createPiBridge({
|
|
|
548
959
|
argsSummary,
|
|
549
960
|
title: argsSummary ? `${ev.toolName} ${argsSummary}` : ev.toolName,
|
|
550
961
|
status: 'running',
|
|
962
|
+
isError: false,
|
|
551
963
|
});
|
|
552
964
|
} else if (ev.type === 'tool_execution_end') {
|
|
553
965
|
const resultPreview = summarizeToolResult(ev.result);
|
|
554
|
-
const
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
966
|
+
const isFailed = Boolean(
|
|
967
|
+
ev.isError
|
|
968
|
+
|| ev.result?.isError === true
|
|
969
|
+
|| ev.result?.details?.ok === false
|
|
970
|
+
|| resultPreview.startsWith('[TOOL_ERROR]')
|
|
971
|
+
);
|
|
972
|
+
if (draftActive && ['clado_create', 'clado_update', 'clado_nodes'].includes(ev.toolName)) {
|
|
973
|
+
draftActive = false;
|
|
974
|
+
events?.emit(workspace, 'canvas.draft', { active: false });
|
|
558
975
|
}
|
|
976
|
+
const canvasAct = activeToolMeta.get(ev.toolCallId);
|
|
977
|
+
activeToolMeta.delete(ev.toolCallId);
|
|
978
|
+
if (canvasAct) {
|
|
979
|
+
cachedCardTitles = null;
|
|
980
|
+
if (isFailed) {
|
|
981
|
+
events?.emit(workspace, 'agent.activity', { file: canvasAct.file, kind: 'clear', nodes: [] });
|
|
982
|
+
} else if (canvasAct.isDirectFile && canvasAct.file) {
|
|
983
|
+
events?.emit(workspace, 'doc.updated', {
|
|
984
|
+
file: canvasAct.file,
|
|
985
|
+
action: 'update',
|
|
986
|
+
nodes: [],
|
|
987
|
+
label: `AI 更新画布 · ${canvasAct.file}`,
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
const codeAct = activeCodeMeta.get(ev.toolCallId);
|
|
992
|
+
activeCodeMeta.delete(ev.toolCallId);
|
|
993
|
+
if (codeAct && !isFailed && ['edit', 'write'].includes(codeAct.action)) {
|
|
994
|
+
const after = safeReadCodeSnapshot(codeAct.abs);
|
|
995
|
+
if (after !== null) {
|
|
996
|
+
events?.emit(workspace, 'code.diff', {
|
|
997
|
+
path: codeAct.rel,
|
|
998
|
+
action: codeAct.action,
|
|
999
|
+
before: codeAct.before,
|
|
1000
|
+
after,
|
|
1001
|
+
isNew: codeAct.before === null,
|
|
1002
|
+
matchedCards: codeAct.matchedCards,
|
|
1003
|
+
roleId: role.id,
|
|
1004
|
+
roleName: role.name,
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
const updated = upsertToolEntry({
|
|
1009
|
+
id: ev.toolCallId,
|
|
1010
|
+
name: ev.toolName,
|
|
1011
|
+
status: isFailed ? 'failed' : 'completed',
|
|
1012
|
+
isError: isFailed,
|
|
1013
|
+
resultPreview,
|
|
1014
|
+
});
|
|
559
1015
|
emitWrapped({
|
|
560
1016
|
type: 'tool',
|
|
561
1017
|
id: ev.toolCallId,
|
|
562
1018
|
name: ev.toolName,
|
|
563
|
-
argsSummary:
|
|
1019
|
+
argsSummary: updated?.argsSummary || '',
|
|
564
1020
|
resultPreview,
|
|
565
|
-
title:
|
|
566
|
-
status:
|
|
1021
|
+
title: updated?.argsSummary ? `${ev.toolName} ${updated.argsSummary}` : ev.toolName,
|
|
1022
|
+
status: isFailed ? 'failed' : 'completed',
|
|
1023
|
+
isError: isFailed,
|
|
567
1024
|
});
|
|
1025
|
+
} else if (ev.type === 'message_end') {
|
|
1026
|
+
const snapUsage = readContextUsageSnapshot();
|
|
1027
|
+
if (snapUsage) {
|
|
1028
|
+
latestContextUsage = snapUsage;
|
|
1029
|
+
emitWrapped({ type: 'usage', usage: snapUsage });
|
|
1030
|
+
}
|
|
568
1031
|
} else if (ev.type === 'compaction_start') {
|
|
569
1032
|
emitWrapped({ type: 'status', text: 'Pi 正在自动压缩长上下文…' });
|
|
1033
|
+
} else if (ev.type === 'compaction_end') {
|
|
1034
|
+
const snapUsage = readContextUsageSnapshot();
|
|
1035
|
+
if (snapUsage) {
|
|
1036
|
+
latestContextUsage = snapUsage;
|
|
1037
|
+
emitWrapped({ type: 'usage', usage: snapUsage });
|
|
1038
|
+
}
|
|
1039
|
+
if (!ev.aborted && !ev.errorMessage) {
|
|
1040
|
+
emitWrapped({ type: 'status', text: '上下文自动压缩完成,已释放窗口空间。' });
|
|
1041
|
+
}
|
|
570
1042
|
} else if (ev.type === 'auto_retry_start') {
|
|
571
1043
|
emitWrapped({ type: 'status', text: `网络波动,正在自动重试 (${ev.attempt}/${ev.maxAttempts})…` });
|
|
572
1044
|
}
|
|
@@ -574,28 +1046,101 @@ export function createPiBridge({
|
|
|
574
1046
|
|
|
575
1047
|
const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom });
|
|
576
1048
|
await session.prompt(promptText);
|
|
1049
|
+
const finalUsage = readContextUsageSnapshot();
|
|
1050
|
+
if (finalUsage) {
|
|
1051
|
+
latestContextUsage = finalUsage;
|
|
1052
|
+
emitWrapped({ type: 'usage', usage: finalUsage });
|
|
1053
|
+
}
|
|
577
1054
|
}
|
|
578
1055
|
|
|
579
1056
|
persistAssistantTurn({ stopped: abortedByUser });
|
|
580
|
-
emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser });
|
|
1057
|
+
emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: abortedByUser, usage: latestContextUsage });
|
|
581
1058
|
} catch (err) {
|
|
582
1059
|
if (abortedByUser) {
|
|
583
1060
|
persistAssistantTurn({ stopped: true });
|
|
584
|
-
emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true });
|
|
1061
|
+
emitWrapped({ type: 'done', sessionId: cleanId, snapshotId: snap?.id || '', stopped: true, usage: latestContextUsage });
|
|
585
1062
|
} else {
|
|
586
1063
|
const msg = err?.message || 'Pi 执行失败';
|
|
587
1064
|
persistAssistantTurn({ errorMsg: msg });
|
|
588
1065
|
emitWrapped({ type: 'error', message: msg });
|
|
589
1066
|
}
|
|
590
1067
|
} finally {
|
|
1068
|
+
if (draftActive) {
|
|
1069
|
+
draftActive = false;
|
|
1070
|
+
events?.emit(workspace, 'canvas.draft', { active: false });
|
|
1071
|
+
}
|
|
1072
|
+
if (presenceTouched) {
|
|
1073
|
+
emitPresence({ phase: 'afterglow', label: '刚刚完成' });
|
|
1074
|
+
}
|
|
591
1075
|
liveRuns.delete(`${workspace}::${cleanId}`);
|
|
592
1076
|
try { unsub?.(); } catch {}
|
|
593
1077
|
try { session?.dispose?.(); } catch {}
|
|
594
1078
|
}
|
|
595
1079
|
}
|
|
596
1080
|
|
|
1081
|
+
async function compactSession({ workspace, stateDir, sessionId, customInstructions = '' }) {
|
|
1082
|
+
const cleanId = safeSessionId(sessionId);
|
|
1083
|
+
const runKey = `${workspace}::${cleanId}`;
|
|
1084
|
+
if (liveRuns.has(runKey)) {
|
|
1085
|
+
throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
|
|
1086
|
+
}
|
|
1087
|
+
const agentDir = resolvePiAgentDir();
|
|
1088
|
+
const meta = getSessionMeta(stateDir, cleanId, agentDir);
|
|
1089
|
+
if (!meta) throw new Error('找不到目标会话。');
|
|
1090
|
+
if (!meta.piSessionFile || !existsSync(meta.piSessionFile)) {
|
|
1091
|
+
return { ok: true, skipped: true, reason: '当前会话尚无需要压缩的历史记录。', session: meta };
|
|
1092
|
+
}
|
|
1093
|
+
const sm = SettingsManager.create(workspace, agentDir);
|
|
1094
|
+
const mr = await createCladoModelRuntime(agentDir);
|
|
1095
|
+
const chosenModel = await resolvePiModel(mr, sm, meta.model);
|
|
1096
|
+
if (!chosenModel) throw new Error('尚未配置可用模型,无法执行上下文压缩。');
|
|
1097
|
+
|
|
1098
|
+
const activeCtxWin = chosenModel.contextWindow || 128000;
|
|
1099
|
+
const runtimeSettings = readRuntimeSettings(workspace, agentDir, activeCtxWin);
|
|
1100
|
+
const loader = new DefaultResourceLoader({ cwd: workspace, agentDir, settingsManager: sm, noThemes: true });
|
|
1101
|
+
await loader.reload();
|
|
1102
|
+
const sessionManager = SessionManager.open(meta.piSessionFile);
|
|
1103
|
+
const created = await createAgentSession({
|
|
1104
|
+
cwd: workspace,
|
|
1105
|
+
agentDir,
|
|
1106
|
+
modelRuntime: mr,
|
|
1107
|
+
model: chosenModel,
|
|
1108
|
+
settingsManager: sm,
|
|
1109
|
+
resourceLoader: loader,
|
|
1110
|
+
sessionManager,
|
|
1111
|
+
});
|
|
1112
|
+
const session = created.session;
|
|
1113
|
+
try {
|
|
1114
|
+
await session.compact(customInstructions || undefined);
|
|
1115
|
+
const cu = session.getContextUsage?.();
|
|
1116
|
+
const total = cu?.contextWindow || activeCtxWin;
|
|
1117
|
+
const used = typeof cu?.tokens === 'number' ? cu.tokens : 0;
|
|
1118
|
+
const usedPercent = typeof cu?.percent === 'number' ? Number(cu.percent.toFixed(1)) : Number(((used / Math.max(1, total)) * 100).toFixed(1));
|
|
1119
|
+
const contextUsage = {
|
|
1120
|
+
tokens: used,
|
|
1121
|
+
contextWindow: total,
|
|
1122
|
+
maxTokens: chosenModel.maxTokens || 16384,
|
|
1123
|
+
remainingTokens: Math.max(0, total - used),
|
|
1124
|
+
usedPercent,
|
|
1125
|
+
remainingPercent: Number(Math.max(0, 100 - usedPercent).toFixed(1)),
|
|
1126
|
+
compactionEnabled: runtimeSettings.compactionEnabled,
|
|
1127
|
+
compactAtPercent: runtimeSettings.compactionTriggerPercent,
|
|
1128
|
+
keepRecentTokens: runtimeSettings.keepRecentTokens,
|
|
1129
|
+
thinkingLevel: runtimeSettings.thinkingLevel,
|
|
1130
|
+
transport: runtimeSettings.transport,
|
|
1131
|
+
model: `${chosenModel.provider}/${chosenModel.id}`,
|
|
1132
|
+
updatedAt: new Date().toISOString(),
|
|
1133
|
+
};
|
|
1134
|
+
const updated = upsertSessionMeta(stateDir, { id: cleanId, contextUsage }, agentDir);
|
|
1135
|
+
return { ok: true, contextUsage, session: updated };
|
|
1136
|
+
} finally {
|
|
1137
|
+
try { session?.dispose?.(); } catch {}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
597
1141
|
return {
|
|
598
1142
|
runTurn,
|
|
1143
|
+
compactSession,
|
|
599
1144
|
answer(workspace, sessionId, questionId, answerText) {
|
|
600
1145
|
const run = liveRuns.get(`${workspace}::${safeSessionId(sessionId)}`);
|
|
601
1146
|
return run ? run.answer(questionId, answerText) : false;
|