Files
gemini-cli/packages/cli/src/ui/commands/compressCommand.ts
T

110 lines
2.9 KiB
TypeScript
Raw Normal View History

2025-07-15 21:59:16 -04:00
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { MessageType, type HistoryItemCompression } from '../types.js';
import { CommandKind, type SlashCommand } from './types.js';
import { tokenLimit, CompressionStatus } from '@google/gemini-cli-core';
2025-07-15 21:59:16 -04:00
export const compressCommand: SlashCommand = {
name: 'compress',
altNames: ['summarize', 'compact'],
description: 'Compresses the context by replacing it with a summary',
kind: CommandKind.BUILT_IN,
autoExecute: true,
2025-07-15 21:59:16 -04:00
action: async (context) => {
const { ui, services } = context;
const agentContext = services.agentContext;
if (!agentContext) {
ui.addItem(
{
type: MessageType.ERROR,
text: 'Agent context not found.',
},
Date.now(),
);
return;
}
const config = agentContext.config;
2025-07-15 21:59:16 -04:00
if (ui.pendingItem) {
ui.addItem(
{
type: MessageType.ERROR,
text: 'Already compressing, wait for previous request to complete',
},
Date.now(),
);
return;
}
const pendingMessage: HistoryItemCompression = {
type: MessageType.COMPRESSION,
compression: {
isPending: true,
beforePercentage: null,
afterPercentage: null,
compressionStatus: null,
isManual: true,
2025-07-15 21:59:16 -04:00
},
};
try {
ui.setPendingItem(pendingMessage);
const promptId = `compress-${Date.now()}`;
const compressed = await agentContext.geminiClient.tryCompressChat(
promptId,
true,
);
2025-07-15 21:59:16 -04:00
if (compressed) {
const limit = tokenLimit(config.getModel());
const threshold = config.getContextWindowCompressionThreshold();
const beforePercentage = Math.round(
(compressed.originalTokenCount / limit) * 100,
);
const afterPercentage = Math.round(
(compressed.newTokenCount / limit) * 100,
);
2025-07-15 21:59:16 -04:00
ui.addItem(
{
type: MessageType.COMPRESSION,
compression: {
isPending: false,
beforePercentage,
afterPercentage,
compressionStatus: (Number(compressed.compressionStatus) as unknown) as CompressionStatus,
isManual: true,
thresholdPercentage: Math.round(threshold * 100),
2025-07-15 21:59:16 -04:00
},
} as HistoryItemCompression,
Date.now(),
);
} else {
ui.addItem(
{
type: MessageType.ERROR,
text: 'Failed to compress chat history.',
},
Date.now(),
);
}
} catch (e) {
ui.addItem(
{
type: MessageType.ERROR,
text: `Failed to compress chat history: ${
e instanceof Error ? e.message : String(e)
}`,
},
Date.now(),
);
} finally {
ui.setPendingItem(null);
}
},
};