Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(pi): 手动压缩会话上下文(pi 原生 compact 全链路)

zqchris6fd11827a988
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 0a1319d2d0..e943f384df 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -187,6 +187,8 @@ export const MAKER_INVOKE = {
SET_PLAN_MODE: 'maker:set-plan-mode',
/** 会话导出 HTML(pi 原生 export_html)。主进程弹保存对话框 + 导出 + 在文件管理器中显示;返回写入路径或 null(取消)。 */
EXPORT_SESSION_HTML: 'maker:export-session-html',
+ /** 手动压缩会话上下文(pi 原生 compact,可带聚焦指令)。返回 {tokensBefore?, estimatedTokensAfter?} 或 null(会话不在/不支持)。 */
+ COMPACT_SESSION: 'maker:compact-session',
/**
* 旧控制端的会话模型预设写穿兼容 channel。新控制端统一经 APPLY_NEW_MAKER_DRAFT_PREF 写被控端
* providerModelMemory 全局预设;旧控制端仍发此 invoke 时,被控端 renderer 也会将其收敛到同一
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d12f901dac..384b7d41de 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -8607,6 +8607,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return written;
});
+ ipcMain.handle(MAKER_INVOKE.COMPACT_SESSION, async (_e, sessionId: unknown, instructions: unknown) => {
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ if (instructions !== undefined && typeof instructions !== 'string') {
+ throwIpcError('INVALID_PARAMS', 'instructions must be a string when provided');
+ }
+ const sess = maker.getSession(sessionId);
+ if (!sess) {
+ log.debug('compact-session: session not found, no-op', { sessionId });
+ return null;
+ }
+ if (!sess.capabilities.manualCompact?.supported) {
+ // 调用方应先按 capabilities 隐藏入口,这里兜底 no-op。
+ log.debug('compact-session: agent does not support manual compact, no-op', {
+ sessionId,
+ agentKind: sess.agentKind,
+ });
+ return null;
+ }
+ return sess.compactSession(instructions);
+ });
+
ipcMain.handle(MAKER_INVOKE.SET_FAST_MODE, async (_e, sessionId: unknown, enabled: unknown) => {
if (typeof sessionId !== 'string' || typeof enabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'sessionId + enabled required');
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4807714e3d..4429069ef6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4579,6 +4579,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 返回写入的绝对路径;用户取消对话框或 agent 不支持时返回 null。
exportSessionHtml: (sessionId: string): Promise<string | null> =>
ipcRenderer.invoke('maker:export-session-html', sessionId),
+ // 手动压缩会话上下文(pi 原生 compact,可带聚焦指令)。压缩边界经事件流自动进聊天。
+ // 返回 {tokensBefore?, estimatedTokensAfter?};会话不在 / agent 不支持时返回 null。
+ compactSession: (
+ sessionId: string,
+ instructions?: string,
+ ): Promise<{ tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean } | null> =>
+ ipcRenderer.invoke('maker:compact-session', sessionId, instructions),
// 附加只读引用目录的 closure 推送; DB 持久化由 renderer 同步调
// sessionService.update({ extraDirs }) (跟 setModel + sessionService.update 双 IPC 协调先例一致)。
// session 不在 / agent capability=false 都 no-op, 不会抛错。
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index 965edd04ca..8ddfb90af9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -161,6 +161,11 @@ export function SessionContentHeader({
!session.remoteHostId &&
!session.deviceLinkDeviceId &&
!isArchived;
+ // 手动压缩:pi 原生 compact,同一 live 本地 pi 会话前提(斜杠转义后用户无法手输
+ // /compact,这是 pi 会话手动压缩的唯一入口)。回合运行中 pi 拒绝压缩 → 禁用而非隐藏。
+ const canCompact = canExportHtml;
+ const [compacting, setCompacting] = useState(false);
+ const compactDisabled = compacting || runningSessionIds.has(session.id);
const projectOptions = useProjectPickerOptions();
// heartbeat schedule 绑定标识,与 SessionItem 同源数据;删除/过期后自动消失。
const boundSchedules = useSessionBoundSchedules(session.id);
@@ -389,6 +394,37 @@ export function SessionContentHeader({
/* ---- 导出会话(.cshare)---- 弹窗仅打开时挂载,与 SessionItem 同款。 */
const [shareExportOpen, setShareExportOpen] = useState(false);
+ /* ---- 手动压缩(pi 原生 compact)---- 长操作(LLM 摘要),压缩边界经事件流自动进聊天;
+ * 回合运行中 pi 会拒绝,菜单项据 running 态禁用。compacting 状态在上方派生区声明。 */
+ const handleCompactSession = useCallback(async () => {
+ if (compacting) return;
+ setCompacting(true);
+ try {
+ const result = await window.electronAPI.maker.compactSession(session.id);
+ if (result?.noop) {
+ // 良性:上下文太小,无可压缩内容。信息性提示,不是失败。
+ toast.info(t('ccAgent.sidebar.sessionMenu.compactNothing'));
+ } else if (result) {
+ const hasNumbers =
+ typeof result.tokensBefore === 'number' && typeof result.estimatedTokensAfter === 'number';
+ toast.success(
+ hasNumbers
+ ? t('ccAgent.sidebar.sessionMenu.compactSuccessWithTokens', {
+ before: Math.round((result.tokensBefore ?? 0) / 1000),
+ after: Math.round((result.estimatedTokensAfter ?? 0) / 1000),
+ })
+ : t('ccAgent.sidebar.sessionMenu.compactSuccess'),
+ );
+ }
+ // null:会话无 live 进程 / 不支持(入口已按 gate 隐藏,极少走到)。静默即可。
+ } catch (err) {
+ log.warn('manual compact failed', err);
+ toast.warning(t('ccAgent.sidebar.sessionMenu.compactFailed'));
+ } finally {
+ setCompacting(false);
+ }
+ }, [compacting, session.id, t]);
+
/* ---- 导出 HTML(pi 原生 export_html)---- 主进程弹保存对话框 + 导出 + 在文件管理器显示。 */
const [exportingHtml, setExportingHtml] = useState(false);
const handleExportHtml = useCallback(async () => {
@@ -762,6 +798,17 @@ export function SessionContentHeader({
{t('ccAgent.sidebar.sessionMenu.exportHtml')}
</DropdownMenuItem>
)}
+ {canCompact && (
+ <DropdownMenuItem
+ disabled={compactDisabled}
+ onSelect={() => void handleCompactSession()}
+ className={MENU_ITEM_CLASS}
+ >
+ {compacting
+ ? t('ccAgent.sidebar.sessionMenu.compacting')
+ : t('ccAgent.sidebar.sessionMenu.compact')}
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
<DropdownMenuItem
disabled={remoteWritesBlocked}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8149196601..48d3c98d4d 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6097,6 +6097,12 @@
"exportHtml": "Export to HTML…",
"exportHtmlSuccess": "Session exported to HTML",
"exportHtmlFailed": "HTML export failed",
+ "compact": "Compact context",
+ "compacting": "Compacting…",
+ "compactSuccess": "Context compacted",
+ "compactSuccessWithTokens": "Context compacted: {{before}}k → {{after}}k tokens",
+ "compactFailed": "Compaction failed",
+ "compactNothing": "Nothing to compact yet",
"copySessionLink": "Copy session link"
},
"projectAction": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8c6768ba2b..6aa139bd61 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6086,6 +6086,12 @@
"exportHtml": "HTML にエクスポート…",
"exportHtmlSuccess": "セッションを HTML にエクスポートしました",
"exportHtmlFailed": "HTML エクスポートに失敗しました",
+ "compact": "コンテキストを圧縮",
+ "compacting": "圧縮中…",
+ "compactSuccess": "コンテキストを圧縮しました",
+ "compactSuccessWithTokens": "コンテキストを圧縮しました:{{before}}k → {{after}}k tokens",
+ "compactFailed": "圧縮に失敗しました",
+ "compactNothing": "圧縮できる内容がまだありません",
"copySessionLink": "セッションリンクをコピー"
},
"projectAction": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0bd1f4c96b..78cc9e8a64 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6086,6 +6086,12 @@
"exportHtml": "HTML로 내보내기…",
"exportHtmlSuccess": "세션을 HTML로 내보냈습니다",
"exportHtmlFailed": "HTML 내보내기 실패",
+ "compact": "컨텍스트 압축",
+ "compacting": "압축 중…",
+ "compactSuccess": "컨텍스트를 압축했습니다",
+ "compactSuccessWithTokens": "컨텍스트를 압축했습니다: {{before}}k → {{after}}k tokens",
+ "compactFailed": "압축 실패",
+ "compactNothing": "아직 압축할 내용이 없습니다",
"copySessionLink": "세션 링크 복사"
},
"projectAction": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b976c8de41..99a2b436ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6088,6 +6088,12 @@
"exportHtml": "导出为 HTML…",
"exportHtmlSuccess": "会话已导出为 HTML",
"exportHtmlFailed": "HTML 导出失败",
+ "compact": "压缩上下文",
+ "compacting": "正在压缩…",
+ "compactSuccess": "上下文已压缩",
+ "compactSuccessWithTokens": "上下文已压缩:{{before}}k → {{after}}k tokens",
+ "compactFailed": "压缩失败",
+ "compactNothing": "暂无可压缩内容",
"copySessionLink": "复制任务链接"
},
"projectAction": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 4770285ef7..9c956ef25f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4350,6 +4350,11 @@ interface ElectronAPI {
setPlanMode: (sessionId: string, enabled: boolean) => Promise<void>;
/** 会话导出 HTML(pi 原生); 主进程弹保存对话框 + 导出 + 在文件管理器显示; 返回路径或 null(取消/不支持) */
exportSessionHtml: (sessionId: string) => Promise<string | null>;
+ /** 手动压缩会话上下文(pi 原生, 可带聚焦指令); 返回压缩前后 token 数 / {noop} / null(会话不在/不支持) */
+ compactSession: (
+ sessionId: string,
+ instructions?: string,
+ ) => Promise<{ tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean } | null>;
/**
* 附加只读引用目录的 closure 推送; DB 持久化要 renderer 同步调
* sessionService.update({ extraDirs }) (跟 setModel + sessionService.update 双 IPC 协调先例一致)。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 8a75289fda..9adc02b4f5 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -27,7 +27,7 @@ import {
type SessionPermissionUpdate,
} from '../types/permissions.js';
import type { AgentKind, Effort, PermissionMode, ReasoningDisplay, UserMessage, WorkspaceKind } from '../types/common.js';
-import type { Capabilities, EffortDescriptor, ModelDescriptor } from '../types/capabilities.js';
+import type { Capabilities, EffortDescriptor, ManualCompactResult, ModelDescriptor } from '../types/capabilities.js';
import type { CapabilityRoutingPolicy } from '../types/capability-routing.js';
import { NotSupportedError } from '../types/capabilities.js';
import type { AgentCredentialMode, AuthLoginOptions } from '../interfaces/auth-adapter.js';
@@ -1031,6 +1031,13 @@ export interface AgentSessionHandle {
*/
exportSessionHtml?(outputPath?: string): Promise<string>;
+ /**
+ * 手动压缩会话上下文(可带聚焦指令,由 agent 调 LLM 生成摘要,压缩边界经事件流
+ * 上报 —— pi 为 compaction_start/end → compact_boundary)。仅
+ * Capabilities.manualCompact 支持的 agent(pi)实现;不支持的 agent 不实现。
+ */
+ compactSession?(instructions?: string): Promise<ManualCompactResult>;
+
/** 运行时切换 Fast mode;不支持的 agent 不实现。 */
setFastMode?(enabled: boolean): Promise<void>;
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index a5c94cfb78..b127d072c8 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -455,6 +455,39 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'compactSession returns a benign noop for a too-small session (not an error)',
+ { timeout: 60_000 },
+ async () => {
+ const agent = new PiAgent(buildDeps());
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-compact-noop-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ try {
+ handle = await agent.startSession({
+ sessionId: 'manual-compact-noop-session',
+ workingDir,
+ model: 'pi-test-model',
+ });
+ // 跑一小轮:上下文远低于压缩门槛,pi 会拒绝「nothing to compact (too small)」。
+ const done = (async () => {
+ for await (const ev of handle!.events()) {
+ if (ev.type === 'done') break;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'tiny' });
+ await done;
+
+ expect(agent.capabilities.manualCompact?.supported).toBe(true);
+ // 关键契约:小会话压缩是良性 noop,不抛错(否则 UI 会误报「压缩失败」)。
+ const result = await handle.compactSession?.();
+ expect(result?.noop).toBe(true);
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
// ── auto 档权限端到端:真 pi + 真 cindy-bridge + 假模型发真工具调用 ────────────
/** 起会话 + 计数 resolver + 跑一轮到 done,返回观测结果。 */
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-compact.test.ts
new file mode 100644
index 0000000000..ced583ab96
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-compact.test.ts
@@ -0,0 +1,125 @@
+/**
+ * PiAgent.compactSession 单测(mock PiRpcProcess)—— 验证 compact RPC 的命令组装、
+ * customInstructions 透传、结果解析,以及良性拒绝 → noop 的映射。真实压缩(LLM 摘要
+ * + compact_boundary 事件)靠集成测试的 noop 契约兜底;happy-path 数值解析在此确定性验证。
+ */
+
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const knobs = vi.hoisted(() => ({
+ compactResponse: null as null | { success: boolean; data?: unknown; error?: string },
+ lastCompactCommand: null as null | Record<string, unknown>,
+}));
+
+vi.mock('../rpc-client.js', () => ({
+ PiRpcProcess: class {
+ isClosed = false;
+ async request(cmd: { type: string }): Promise<{ success: boolean; data?: unknown; error?: string }> {
+ if (cmd.type === 'get_state') {
+ return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200000 } } };
+ }
+ if (cmd.type === 'compact') {
+ knobs.lastCompactCommand = cmd as Record<string, unknown>;
+ return knobs.compactResponse ?? { success: true, data: {} };
+ }
+ return { success: true, data: { entries: [] } };
+ }
+ send(): void {}
+ async close(): Promise<void> {
+ this.isClosed = true;
+ }
+ },
+}));
+
+import { PiAgent } from '../index.js';
+import type { AgentDeps, AgentSessionHandle } from '../../base-agent.js';
+import type { Logger } from '../../../interfaces/logger.js';
+
+const noopLogger: Logger = {
+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
+ child: () => noopLogger,
+};
+
+describe('PiAgent.compactSession (mocked pi process)', () => {
+ let agentHome = '';
+ let cwd = '';
+
+ beforeEach(() => {
+ knobs.compactResponse = null;
+ knobs.lastCompactCommand = null;
+ agentHome = mkdtempSync(path.join(tmpdir(), 'pi-compact-unit-home-'));
+ cwd = mkdtempSync(path.join(tmpdir(), 'pi-compact-unit-cwd-'));
+ });
+ afterEach(() => {
+ rmSync(agentHome, { recursive: true, force: true });
+ rmSync(cwd, { recursive: true, force: true });
+ });
+
+ function buildDeps(): AgentDeps {
+ return {
+ auth: {
+ getState: async () => ({ authenticated: true, identity: 't', authSource: 'api-key' as const }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({}),
+ },
+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
+ binaryPath: path.join(agentHome, 'pi'),
+ logger: noopLogger,
+ capabilityAdditions: {
+ availableModels: [
+ { id: 'm', displayName: 'M', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ ],
+ },
+ resolvePiAgentHome: () => agentHome,
+ };
+ }
+
+ async function start(): Promise<AgentSessionHandle> {
+ return new PiAgent(buildDeps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });
+ }
+
+ it('declares manualCompact capability', () => {
+ expect(new PiAgent(buildDeps()).capabilities.manualCompact?.supported).toBe(true);
+ });
+
+ it('parses tokensBefore/estimatedTokensAfter and omits missing numbers', async () => {
+ knobs.compactResponse = {
+ success: true,
+ data: { summary: 'x', tokensBefore: 150000, estimatedTokensAfter: 32000, extra: 'ignored' },
+ };
+ const handle = await start();
+ const result = await handle.compactSession?.();
+ expect(result).toEqual({ tokensBefore: 150000, estimatedTokensAfter: 32000 });
+ await handle.close();
+ });
+
+ it('passes customInstructions through when provided, omits when blank', async () => {
+ const handle = await start();
+ await handle.compactSession?.(' keep the API design decisions ');
+ expect(knobs.lastCompactCommand).toEqual({ type: 'compact', customInstructions: 'keep the API design decisions' });
+ knobs.lastCompactCommand = null;
+ await handle.compactSession?.(' ');
+ expect(knobs.lastCompactCommand).toEqual({ type: 'compact' });
+ await handle.close();
+ });
+
+ it('maps benign "nothing to compact / too small" refusal to noop (not throw)', async () => {
+ const handle = await start();
+ knobs.compactResponse = { success: false, error: 'Nothing to compact (session too small)' };
+ await expect(handle.compactSession?.()).resolves.toEqual({ noop: true });
+ knobs.compactResponse = { success: false, error: 'context too small' };
+ await expect(handle.compactSession?.()).resolves.toEqual({ noop: true });
+ await handle.close();
+ });
+
+ it('throws on a genuine compact failure', async () => {
+ const handle = await start();
+ knobs.compactResponse = { success: false, error: 'gateway 500' };
+ await expect(handle.compactSession?.()).rejects.toThrow(/gateway 500/);
+ await handle.close();
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 106a698b03..5296bbdc8d 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -40,6 +40,7 @@ import {
import { classifyPiToolForAutoReview } from './auto-review-policy.js';
import type {
Capabilities,
+ ManualCompactResult,
ModelDescriptor,
} from '../../types/capabilities.js';
import { NotSupportedError } from '../../types/capabilities.js';
@@ -66,6 +67,8 @@ import {
const PI_PROVIDER_ID = 'cindy';
const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';
const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';
+/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */
+const PI_COMPACT_TIMEOUT_MS = 600_000;
/**
* NO_PROXY 兜底:pi 的模型请求打的是 Cindy 本地 compat proxy(loopback),bridge 的
@@ -215,6 +218,9 @@ export class PiAgent extends BaseAgent {
extraDirs: { supported: false, reason: 'sdk-missing' },
// pi 原生 export_html RPC:自带 export-html 渲染器,离线、无网关。
sessionHtmlExport: { supported: true },
+ // pi 原生 compact RPC:手动压缩(可带聚焦指令,调 LLM 生成摘要)。
+ // 斜杠转义后用户无法手输 /compact,此能力是 pi 会话手动压缩的唯一入口。
+ manualCompact: { supported: true },
};
}
@@ -670,6 +676,28 @@ export class PiAgent extends BaseAgent {
}
return path;
},
+
+ async compactSession(instructions?: string): Promise<ManualCompactResult> {
+ // pi 原生 compact:调 LLM 生成摘要(耗时数秒起),压缩边界经
+ // compaction_start/end 事件流上报,translator 映射成 compact_boundary。
+ // 压缩请求本身可能远超 RPC 默认 30s 超时(大上下文 + 网关排队),放宽到 10 分钟。
+ const command: Record<string, unknown> = { type: 'compact' };
+ if (instructions && instructions.trim().length > 0) command.customInstructions = instructions.trim();
+ const resp = await proc.request(command, { timeoutMs: PI_COMPACT_TIMEOUT_MS });
+ if (!resp.success) {
+ // 良性拒绝:上下文太小 / 无内容可压缩 —— 不是错误,返回 noop 让 UI 给信息性提示。
+ const err = (resp.error ?? '').toLowerCase();
+ if (err.includes('nothing to compact') || err.includes('too small')) {
+ return { noop: true };
+ }
+ throw new Error(`pi compact failed: ${resp.error ?? 'unknown'}`);
+ }
+ const data = (resp.data ?? {}) as { tokensBefore?: number; estimatedTokensAfter?: number };
+ const result: ManualCompactResult = {};
+ if (typeof data.tokensBefore === 'number') result.tokensBefore = data.tokensBefore;
+ if (typeof data.estimatedTokensAfter === 'number') result.estimatedTokensAfter = data.estimatedTokensAfter;
+ return result;
+ },
};
return handle;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 97f0cb6e17..ffa043cc9d 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -22,7 +22,7 @@ import type {
AgentKind,
UserMessage,
} from './types/common.js';
-import type { Capabilities } from './types/capabilities.js';
+import type { Capabilities, ManualCompactResult } from './types/capabilities.js';
import { NotSupportedError } from './types/capabilities.js';
import type {
AgentEvent,
@@ -681,6 +681,21 @@ export class Session {
return this.handle.exportSessionHtml(outputPath);
}
+ /** 手动压缩会话上下文(capability 见 Capabilities.manualCompact)。 */
+ async compactSession(instructions?: string): Promise<ManualCompactResult> {
+ this.ensureActive();
+ if (!this.capabilities.manualCompact?.supported) {
+ throw new NotSupportedError(
+ 'manualCompact',
+ this.capabilities.manualCompact ?? { supported: false, reason: 'not-implemented' },
+ );
+ }
+ if (!this.handle.compactSession) {
+ throw new NotSupportedError('manualCompact', { supported: false, reason: 'not-implemented' });
+ }
+ return this.handle.compactSession(instructions);
+ }
+
getFastMode(): boolean | null {
return this.handle.getFastMode?.() ?? null;
}
diff --git a/packages/maker-core/src/types/capabilities.ts b/packages/maker-core/src/types/capabilities.ts
index 76e30ea681..d8417c4c89 100644
--- a/packages/maker-core/src/types/capabilities.ts
+++ b/packages/maker-core/src/types/capabilities.ts
@@ -107,6 +107,23 @@ export interface Capabilities {
* CC/Codex 无对应能力(缺省视为不支持)。
*/
sessionHtmlExport?: CapabilityStatus;
+ /**
+ * 手动压缩会话上下文 —— pi 原生 compact RPC(可带聚焦指令,调 LLM 生成摘要)。
+ * 支持时 handle 实现 compactSession;UI 据此决定是否显示「压缩会话」入口。
+ * CC/Codex 的 /compact 走各自 agent 内置斜杠命令,不经此能力(缺省视为不支持)。
+ */
+ manualCompact?: CapabilityStatus;
+}
+
+/** 手动压缩结果(数值可缺省:自定义压缩 handler 可能不上报)。 */
+export interface ManualCompactResult {
+ tokensBefore?: number;
+ estimatedTokensAfter?: number;
+ /**
+ * 良性空操作:上下文太小 / 无可压缩内容,agent 拒绝压缩但这不是错误。
+ * UI 应给信息性提示(「暂无可压缩内容」),而非「压缩失败」。
+ */
+ noop?: boolean;
}
/**