@blockrun/runcode 2.4.0 → 2.5.0
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/dist/agent/commands.js +37 -3
- package/dist/agent/context.js +3 -2
- package/dist/agent/loop.js +36 -13
- package/dist/agent/reduce.d.ts +42 -0
- package/dist/agent/reduce.js +258 -0
- package/dist/agent/types.d.ts +2 -0
- package/package.json +1 -1
- package/dist/compression/adapter.d.ts +0 -13
- package/dist/compression/adapter.js +0 -104
- package/dist/compression/codebook.d.ts +0 -23
- package/dist/compression/codebook.js +0 -118
- package/dist/compression/index.d.ts +0 -32
- package/dist/compression/index.js +0 -258
- package/dist/compression/layers/deduplication.d.ts +0 -27
- package/dist/compression/layers/deduplication.js +0 -97
- package/dist/compression/layers/dictionary.d.ts +0 -20
- package/dist/compression/layers/dictionary.js +0 -67
- package/dist/compression/layers/dynamic-codebook.d.ts +0 -25
- package/dist/compression/layers/dynamic-codebook.js +0 -145
- package/dist/compression/layers/json-compact.d.ts +0 -22
- package/dist/compression/layers/json-compact.js +0 -74
- package/dist/compression/layers/observation.d.ts +0 -20
- package/dist/compression/layers/observation.js +0 -126
- package/dist/compression/layers/paths.d.ts +0 -23
- package/dist/compression/layers/paths.js +0 -107
- package/dist/compression/layers/whitespace.d.ts +0 -26
- package/dist/compression/layers/whitespace.js +0 -57
- package/dist/compression/types.d.ts +0 -83
- package/dist/compression/types.js +0 -26
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Dictionary Codebook
|
|
3
|
-
*
|
|
4
|
-
* Static dictionary of frequently repeated phrases observed in LLM prompts.
|
|
5
|
-
* Built from analysis of BlockRun production logs.
|
|
6
|
-
*
|
|
7
|
-
* Format: Short code ($XX) -> Long phrase
|
|
8
|
-
* The LLM receives a codebook header and decodes in-context.
|
|
9
|
-
*/
|
|
10
|
-
// Static codebook - common patterns from system prompts
|
|
11
|
-
// Ordered by expected frequency and impact
|
|
12
|
-
export const STATIC_CODEBOOK = {
|
|
13
|
-
// High-impact: OpenClaw/Agent system prompt patterns (very common)
|
|
14
|
-
"$OC01": "unbrowse_", // Common prefix in tool names
|
|
15
|
-
"$OC02": "<location>",
|
|
16
|
-
"$OC03": "</location>",
|
|
17
|
-
"$OC04": "<name>",
|
|
18
|
-
"$OC05": "</name>",
|
|
19
|
-
"$OC06": "<description>",
|
|
20
|
-
"$OC07": "</description>",
|
|
21
|
-
"$OC08": "(may need login)",
|
|
22
|
-
"$OC09": "API skill for OpenClaw",
|
|
23
|
-
"$OC10": "endpoints",
|
|
24
|
-
// Skill/tool markers
|
|
25
|
-
"$SK01": "<available_skills>",
|
|
26
|
-
"$SK02": "</available_skills>",
|
|
27
|
-
"$SK03": "<skill>",
|
|
28
|
-
"$SK04": "</skill>",
|
|
29
|
-
// Schema patterns (very common in tool definitions)
|
|
30
|
-
"$T01": 'type: "function"',
|
|
31
|
-
"$T02": '"type": "function"',
|
|
32
|
-
"$T03": '"type": "string"',
|
|
33
|
-
"$T04": '"type": "object"',
|
|
34
|
-
"$T05": '"type": "array"',
|
|
35
|
-
"$T06": '"type": "boolean"',
|
|
36
|
-
"$T07": '"type": "number"',
|
|
37
|
-
// Common descriptions
|
|
38
|
-
"$D01": "description:",
|
|
39
|
-
"$D02": '"description":',
|
|
40
|
-
// Common instructions
|
|
41
|
-
"$I01": "You are a personal assistant",
|
|
42
|
-
"$I02": "Tool names are case-sensitive",
|
|
43
|
-
"$I03": "Call tools exactly as listed",
|
|
44
|
-
"$I04": "Use when",
|
|
45
|
-
"$I05": "without asking",
|
|
46
|
-
// Safety phrases
|
|
47
|
-
"$S01": "Do not manipulate or persuade",
|
|
48
|
-
"$S02": "Prioritize safety and human oversight",
|
|
49
|
-
"$S03": "unless explicitly requested",
|
|
50
|
-
// JSON patterns
|
|
51
|
-
"$J01": '"required": ["',
|
|
52
|
-
"$J02": '"properties": {',
|
|
53
|
-
"$J03": '"additionalProperties": false',
|
|
54
|
-
// Heartbeat patterns
|
|
55
|
-
"$H01": "HEARTBEAT_OK",
|
|
56
|
-
"$H02": "Read HEARTBEAT.md if it exists",
|
|
57
|
-
// Role markers
|
|
58
|
-
"$R01": '"role": "system"',
|
|
59
|
-
"$R02": '"role": "user"',
|
|
60
|
-
"$R03": '"role": "assistant"',
|
|
61
|
-
"$R04": '"role": "tool"',
|
|
62
|
-
// Common endings/phrases
|
|
63
|
-
"$E01": "would you like to",
|
|
64
|
-
"$E02": "Let me know if you",
|
|
65
|
-
"$E03": "internal APIs",
|
|
66
|
-
"$E04": "session cookies",
|
|
67
|
-
// BlockRun model aliases (common in prompts)
|
|
68
|
-
"$M01": "blockrun/",
|
|
69
|
-
"$M02": "openai/",
|
|
70
|
-
"$M03": "anthropic/",
|
|
71
|
-
"$M04": "google/",
|
|
72
|
-
"$M05": "xai/",
|
|
73
|
-
};
|
|
74
|
-
/**
|
|
75
|
-
* Get the inverse codebook for decompression.
|
|
76
|
-
*/
|
|
77
|
-
export function getInverseCodebook() {
|
|
78
|
-
const inverse = {};
|
|
79
|
-
for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {
|
|
80
|
-
inverse[phrase] = code;
|
|
81
|
-
}
|
|
82
|
-
return inverse;
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Generate the codebook header for inclusion in system message.
|
|
86
|
-
* LLMs can decode in-context using this header.
|
|
87
|
-
*/
|
|
88
|
-
export function generateCodebookHeader(usedCodes, pathMap = {}) {
|
|
89
|
-
if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {
|
|
90
|
-
return "";
|
|
91
|
-
}
|
|
92
|
-
const parts = [];
|
|
93
|
-
// Add used dictionary codes
|
|
94
|
-
if (usedCodes.size > 0) {
|
|
95
|
-
const codeEntries = Array.from(usedCodes)
|
|
96
|
-
.map((code) => `${code}=${STATIC_CODEBOOK[code]}`)
|
|
97
|
-
.join(", ");
|
|
98
|
-
parts.push(`[Dict: ${codeEntries}]`);
|
|
99
|
-
}
|
|
100
|
-
// Add path map
|
|
101
|
-
if (Object.keys(pathMap).length > 0) {
|
|
102
|
-
const pathEntries = Object.entries(pathMap)
|
|
103
|
-
.map(([code, path]) => `${code}=${path}`)
|
|
104
|
-
.join(", ");
|
|
105
|
-
parts.push(`[Paths: ${pathEntries}]`);
|
|
106
|
-
}
|
|
107
|
-
return parts.join("\n");
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Decompress a string using the codebook (for logging).
|
|
111
|
-
*/
|
|
112
|
-
export function decompressContent(content, codebook = STATIC_CODEBOOK) {
|
|
113
|
-
let result = content;
|
|
114
|
-
for (const [code, phrase] of Object.entries(codebook)) {
|
|
115
|
-
result = result.split(code).join(phrase);
|
|
116
|
-
}
|
|
117
|
-
return result;
|
|
118
|
-
}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* LLM-Safe Context Compression
|
|
3
|
-
*
|
|
4
|
-
* Reduces token usage by 15-40% while preserving semantic meaning.
|
|
5
|
-
* Implements 7 compression layers inspired by claw-compactor.
|
|
6
|
-
*
|
|
7
|
-
* Usage:
|
|
8
|
-
* const result = await compressContext(messages);
|
|
9
|
-
* // result.messages -> compressed version to send to provider
|
|
10
|
-
* // result.originalMessages -> original for logging
|
|
11
|
-
*/
|
|
12
|
-
import { NormalizedMessage, CompressionConfig, CompressionResult } from "./types.js";
|
|
13
|
-
export * from "./types.js";
|
|
14
|
-
export { STATIC_CODEBOOK } from "./codebook.js";
|
|
15
|
-
/**
|
|
16
|
-
* Main compression function.
|
|
17
|
-
*
|
|
18
|
-
* Applies 5 layers in sequence:
|
|
19
|
-
* 1. Deduplication - Remove exact duplicate messages
|
|
20
|
-
* 2. Whitespace - Normalize excessive whitespace
|
|
21
|
-
* 3. Dictionary - Replace common phrases with codes
|
|
22
|
-
* 4. Paths - Shorten repeated file paths
|
|
23
|
-
* 5. JSON - Compact JSON in tool calls
|
|
24
|
-
*
|
|
25
|
-
* Then prepends a codebook header for the LLM to decode in-context.
|
|
26
|
-
*/
|
|
27
|
-
export declare function compressContext(messages: NormalizedMessage[], config?: Partial<CompressionConfig>): Promise<CompressionResult>;
|
|
28
|
-
/**
|
|
29
|
-
* Quick check if compression would benefit these messages.
|
|
30
|
-
* Returns true if messages are large enough to warrant compression.
|
|
31
|
-
*/
|
|
32
|
-
export declare function shouldCompress(messages: NormalizedMessage[]): boolean;
|
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* LLM-Safe Context Compression
|
|
3
|
-
*
|
|
4
|
-
* Reduces token usage by 15-40% while preserving semantic meaning.
|
|
5
|
-
* Implements 7 compression layers inspired by claw-compactor.
|
|
6
|
-
*
|
|
7
|
-
* Usage:
|
|
8
|
-
* const result = await compressContext(messages);
|
|
9
|
-
* // result.messages -> compressed version to send to provider
|
|
10
|
-
* // result.originalMessages -> original for logging
|
|
11
|
-
*/
|
|
12
|
-
import { DEFAULT_COMPRESSION_CONFIG, } from "./types.js";
|
|
13
|
-
import { deduplicateMessages } from "./layers/deduplication.js";
|
|
14
|
-
import { normalizeMessagesWhitespace } from "./layers/whitespace.js";
|
|
15
|
-
import { encodeMessages } from "./layers/dictionary.js";
|
|
16
|
-
import { shortenPaths } from "./layers/paths.js";
|
|
17
|
-
import { compactMessagesJson } from "./layers/json-compact.js";
|
|
18
|
-
import { compressObservations } from "./layers/observation.js";
|
|
19
|
-
import { applyDynamicCodebook, generateDynamicCodebookHeader } from "./layers/dynamic-codebook.js";
|
|
20
|
-
import { generateCodebookHeader, STATIC_CODEBOOK } from "./codebook.js";
|
|
21
|
-
export * from "./types.js";
|
|
22
|
-
export { STATIC_CODEBOOK } from "./codebook.js";
|
|
23
|
-
/**
|
|
24
|
-
* Calculate total character count for messages.
|
|
25
|
-
*/
|
|
26
|
-
function calculateTotalChars(messages) {
|
|
27
|
-
return messages.reduce((total, msg) => {
|
|
28
|
-
let chars = 0;
|
|
29
|
-
if (Array.isArray(msg.content)) {
|
|
30
|
-
for (const part of msg.content) {
|
|
31
|
-
if (part.type === "text" && part.text)
|
|
32
|
-
chars += part.text.length;
|
|
33
|
-
else if (part.type === "image_url")
|
|
34
|
-
chars += 2500; // ~1000 tokens worth
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
else {
|
|
38
|
-
chars = msg.content?.length || 0;
|
|
39
|
-
}
|
|
40
|
-
if (msg.tool_calls) {
|
|
41
|
-
chars += JSON.stringify(msg.tool_calls).length;
|
|
42
|
-
}
|
|
43
|
-
return total + chars;
|
|
44
|
-
}, 0);
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Check if any message contains image_url content parts.
|
|
48
|
-
*/
|
|
49
|
-
function hasVisionContent(messages) {
|
|
50
|
-
return messages.some((m) => Array.isArray(m.content) && m.content.some((p) => p.type === "image_url"));
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Deep clone messages to preserve originals.
|
|
54
|
-
*/
|
|
55
|
-
function cloneMessages(messages) {
|
|
56
|
-
return JSON.parse(JSON.stringify(messages));
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Prepend codebook header to the first USER message (not system).
|
|
60
|
-
*
|
|
61
|
-
* Why not system message?
|
|
62
|
-
* - Google Gemini uses systemInstruction which doesn't support codebook format
|
|
63
|
-
* - The codebook header in user message is still visible to all LLMs
|
|
64
|
-
* - This ensures compatibility across all providers
|
|
65
|
-
*/
|
|
66
|
-
function prependCodebookHeader(messages, usedCodes, pathMap) {
|
|
67
|
-
const header = generateCodebookHeader(usedCodes, pathMap);
|
|
68
|
-
if (!header)
|
|
69
|
-
return messages;
|
|
70
|
-
// Find first user message (not system - Google's systemInstruction doesn't support codebook)
|
|
71
|
-
const userIndex = messages.findIndex((m) => m.role === "user");
|
|
72
|
-
if (userIndex === -1) {
|
|
73
|
-
// No user message, add codebook as system (fallback)
|
|
74
|
-
return [
|
|
75
|
-
{ role: "system", content: header },
|
|
76
|
-
...messages,
|
|
77
|
-
];
|
|
78
|
-
}
|
|
79
|
-
// Prepend to first user message
|
|
80
|
-
return messages.map((msg, i) => {
|
|
81
|
-
if (i === userIndex) {
|
|
82
|
-
return {
|
|
83
|
-
...msg,
|
|
84
|
-
content: `${header}\n\n${msg.content || ""}`,
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
return msg;
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Main compression function.
|
|
92
|
-
*
|
|
93
|
-
* Applies 5 layers in sequence:
|
|
94
|
-
* 1. Deduplication - Remove exact duplicate messages
|
|
95
|
-
* 2. Whitespace - Normalize excessive whitespace
|
|
96
|
-
* 3. Dictionary - Replace common phrases with codes
|
|
97
|
-
* 4. Paths - Shorten repeated file paths
|
|
98
|
-
* 5. JSON - Compact JSON in tool calls
|
|
99
|
-
*
|
|
100
|
-
* Then prepends a codebook header for the LLM to decode in-context.
|
|
101
|
-
*/
|
|
102
|
-
export async function compressContext(messages, config = {}) {
|
|
103
|
-
const fullConfig = {
|
|
104
|
-
...DEFAULT_COMPRESSION_CONFIG,
|
|
105
|
-
...config,
|
|
106
|
-
layers: {
|
|
107
|
-
...DEFAULT_COMPRESSION_CONFIG.layers,
|
|
108
|
-
...config.layers,
|
|
109
|
-
},
|
|
110
|
-
dictionary: {
|
|
111
|
-
...DEFAULT_COMPRESSION_CONFIG.dictionary,
|
|
112
|
-
...config.dictionary,
|
|
113
|
-
},
|
|
114
|
-
};
|
|
115
|
-
// If compression disabled, return as-is
|
|
116
|
-
if (!fullConfig.enabled) {
|
|
117
|
-
const originalChars = calculateTotalChars(messages);
|
|
118
|
-
return {
|
|
119
|
-
messages,
|
|
120
|
-
originalMessages: messages,
|
|
121
|
-
originalChars,
|
|
122
|
-
compressedChars: originalChars,
|
|
123
|
-
compressionRatio: 1,
|
|
124
|
-
stats: {
|
|
125
|
-
duplicatesRemoved: 0,
|
|
126
|
-
whitespaceSavedChars: 0,
|
|
127
|
-
dictionarySubstitutions: 0,
|
|
128
|
-
pathsShortened: 0,
|
|
129
|
-
jsonCompactedChars: 0,
|
|
130
|
-
observationsCompressed: 0,
|
|
131
|
-
observationCharsSaved: 0,
|
|
132
|
-
dynamicSubstitutions: 0,
|
|
133
|
-
dynamicCharsSaved: 0,
|
|
134
|
-
},
|
|
135
|
-
codebook: {},
|
|
136
|
-
pathMap: {},
|
|
137
|
-
dynamicCodes: {},
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
// Preserve originals for logging
|
|
141
|
-
const originalMessages = fullConfig.preserveRaw
|
|
142
|
-
? cloneMessages(messages)
|
|
143
|
-
: messages;
|
|
144
|
-
const originalChars = calculateTotalChars(messages);
|
|
145
|
-
// Initialize stats
|
|
146
|
-
const stats = {
|
|
147
|
-
duplicatesRemoved: 0,
|
|
148
|
-
whitespaceSavedChars: 0,
|
|
149
|
-
dictionarySubstitutions: 0,
|
|
150
|
-
pathsShortened: 0,
|
|
151
|
-
jsonCompactedChars: 0,
|
|
152
|
-
observationsCompressed: 0,
|
|
153
|
-
observationCharsSaved: 0,
|
|
154
|
-
dynamicSubstitutions: 0,
|
|
155
|
-
dynamicCharsSaved: 0,
|
|
156
|
-
};
|
|
157
|
-
let result = cloneMessages(messages);
|
|
158
|
-
let usedCodes = new Set();
|
|
159
|
-
let pathMap = {};
|
|
160
|
-
let dynamicCodes = {};
|
|
161
|
-
// Layer 1: Deduplication
|
|
162
|
-
if (fullConfig.layers.deduplication) {
|
|
163
|
-
const dedupResult = deduplicateMessages(result);
|
|
164
|
-
result = dedupResult.messages;
|
|
165
|
-
stats.duplicatesRemoved = dedupResult.duplicatesRemoved;
|
|
166
|
-
}
|
|
167
|
-
// Layer 2: Whitespace normalization
|
|
168
|
-
if (fullConfig.layers.whitespace) {
|
|
169
|
-
const wsResult = normalizeMessagesWhitespace(result);
|
|
170
|
-
result = wsResult.messages;
|
|
171
|
-
stats.whitespaceSavedChars = wsResult.charsSaved;
|
|
172
|
-
}
|
|
173
|
-
// Layer 3: Dictionary encoding
|
|
174
|
-
if (fullConfig.layers.dictionary) {
|
|
175
|
-
const dictResult = encodeMessages(result);
|
|
176
|
-
result = dictResult.messages;
|
|
177
|
-
stats.dictionarySubstitutions = dictResult.substitutionCount;
|
|
178
|
-
usedCodes = dictResult.usedCodes;
|
|
179
|
-
}
|
|
180
|
-
// Layer 4: Path shortening
|
|
181
|
-
if (fullConfig.layers.paths) {
|
|
182
|
-
const pathResult = shortenPaths(result);
|
|
183
|
-
result = pathResult.messages;
|
|
184
|
-
pathMap = pathResult.pathMap;
|
|
185
|
-
stats.pathsShortened = Object.keys(pathMap).length;
|
|
186
|
-
}
|
|
187
|
-
// Layer 5: JSON compaction
|
|
188
|
-
if (fullConfig.layers.jsonCompact) {
|
|
189
|
-
const jsonResult = compactMessagesJson(result);
|
|
190
|
-
result = jsonResult.messages;
|
|
191
|
-
stats.jsonCompactedChars = jsonResult.charsSaved;
|
|
192
|
-
}
|
|
193
|
-
// Layer 6: Observation compression (BIG WIN - 97% on tool results)
|
|
194
|
-
if (fullConfig.layers.observation) {
|
|
195
|
-
const obsResult = compressObservations(result);
|
|
196
|
-
result = obsResult.messages;
|
|
197
|
-
stats.observationsCompressed = obsResult.observationsCompressed;
|
|
198
|
-
stats.observationCharsSaved = obsResult.charsSaved;
|
|
199
|
-
}
|
|
200
|
-
// Layer 7: Dynamic codebook (learns from actual content)
|
|
201
|
-
if (fullConfig.layers.dynamicCodebook) {
|
|
202
|
-
const dynResult = applyDynamicCodebook(result);
|
|
203
|
-
result = dynResult.messages;
|
|
204
|
-
stats.dynamicSubstitutions = dynResult.substitutions;
|
|
205
|
-
stats.dynamicCharsSaved = dynResult.charsSaved;
|
|
206
|
-
dynamicCodes = dynResult.dynamicCodes;
|
|
207
|
-
}
|
|
208
|
-
// Add codebook header if enabled and we have codes to include
|
|
209
|
-
if (fullConfig.dictionary.includeCodebookHeader &&
|
|
210
|
-
(usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)) {
|
|
211
|
-
result = prependCodebookHeader(result, usedCodes, pathMap);
|
|
212
|
-
// Also add dynamic codebook header if we have dynamic codes
|
|
213
|
-
if (Object.keys(dynamicCodes).length > 0) {
|
|
214
|
-
const dynHeader = generateDynamicCodebookHeader(dynamicCodes);
|
|
215
|
-
if (dynHeader) {
|
|
216
|
-
const systemIndex = result.findIndex((m) => m.role === "system");
|
|
217
|
-
if (systemIndex >= 0) {
|
|
218
|
-
result[systemIndex] = {
|
|
219
|
-
...result[systemIndex],
|
|
220
|
-
content: `${dynHeader}\n${result[systemIndex].content || ""}`,
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
// Calculate final stats
|
|
227
|
-
const compressedChars = calculateTotalChars(result);
|
|
228
|
-
const compressionRatio = compressedChars / originalChars;
|
|
229
|
-
// Build used codebook for logging
|
|
230
|
-
const usedCodebook = {};
|
|
231
|
-
usedCodes.forEach((code) => {
|
|
232
|
-
usedCodebook[code] = STATIC_CODEBOOK[code];
|
|
233
|
-
});
|
|
234
|
-
return {
|
|
235
|
-
messages: result,
|
|
236
|
-
originalMessages,
|
|
237
|
-
originalChars,
|
|
238
|
-
compressedChars,
|
|
239
|
-
compressionRatio,
|
|
240
|
-
stats,
|
|
241
|
-
codebook: usedCodebook,
|
|
242
|
-
pathMap,
|
|
243
|
-
dynamicCodes,
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* Quick check if compression would benefit these messages.
|
|
248
|
-
* Returns true if messages are large enough to warrant compression.
|
|
249
|
-
*/
|
|
250
|
-
export function shouldCompress(messages) {
|
|
251
|
-
// Skip compression entirely when messages contain images —
|
|
252
|
-
// compression layers operate on string content and would corrupt image_url parts
|
|
253
|
-
if (hasVisionContent(messages))
|
|
254
|
-
return false;
|
|
255
|
-
const chars = calculateTotalChars(messages);
|
|
256
|
-
// Only compress if > 5000 chars (roughly 1000 tokens)
|
|
257
|
-
return chars > 5000;
|
|
258
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Layer 1: Message Deduplication
|
|
3
|
-
*
|
|
4
|
-
* Removes exact duplicate messages from conversation history.
|
|
5
|
-
* Common in heartbeat patterns and repeated tool calls.
|
|
6
|
-
*
|
|
7
|
-
* Safe for LLM: Identical messages add no new information.
|
|
8
|
-
* Expected savings: 2-5%
|
|
9
|
-
*/
|
|
10
|
-
import { NormalizedMessage } from "../types.js";
|
|
11
|
-
export interface DeduplicationResult {
|
|
12
|
-
messages: NormalizedMessage[];
|
|
13
|
-
duplicatesRemoved: number;
|
|
14
|
-
originalCount: number;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Remove exact duplicate messages from the conversation.
|
|
18
|
-
*
|
|
19
|
-
* Strategy:
|
|
20
|
-
* - Keep first occurrence of each unique message
|
|
21
|
-
* - Preserve order for semantic coherence
|
|
22
|
-
* - Never dedupe system messages (they set context)
|
|
23
|
-
* - Allow duplicate user messages (user might repeat intentionally)
|
|
24
|
-
* - CRITICAL: Never dedupe assistant messages with tool_calls that are
|
|
25
|
-
* referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)
|
|
26
|
-
*/
|
|
27
|
-
export declare function deduplicateMessages(messages: NormalizedMessage[]): DeduplicationResult;
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Layer 1: Message Deduplication
|
|
3
|
-
*
|
|
4
|
-
* Removes exact duplicate messages from conversation history.
|
|
5
|
-
* Common in heartbeat patterns and repeated tool calls.
|
|
6
|
-
*
|
|
7
|
-
* Safe for LLM: Identical messages add no new information.
|
|
8
|
-
* Expected savings: 2-5%
|
|
9
|
-
*/
|
|
10
|
-
import { createHash } from 'node:crypto';
|
|
11
|
-
/**
|
|
12
|
-
* Generate a hash for a message based on its semantic content.
|
|
13
|
-
* Uses role + content + tool_call_id to identify duplicates.
|
|
14
|
-
*/
|
|
15
|
-
function hashMessage(message) {
|
|
16
|
-
const parts = [
|
|
17
|
-
message.role,
|
|
18
|
-
message.content || "",
|
|
19
|
-
message.tool_call_id || "",
|
|
20
|
-
message.name || "",
|
|
21
|
-
];
|
|
22
|
-
// Include tool_calls if present
|
|
23
|
-
if (message.tool_calls) {
|
|
24
|
-
parts.push(JSON.stringify(message.tool_calls.map((tc) => ({
|
|
25
|
-
name: tc.function.name,
|
|
26
|
-
args: tc.function.arguments,
|
|
27
|
-
}))));
|
|
28
|
-
}
|
|
29
|
-
const content = parts.join("|");
|
|
30
|
-
return createHash("md5").update(content).digest("hex");
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Remove exact duplicate messages from the conversation.
|
|
34
|
-
*
|
|
35
|
-
* Strategy:
|
|
36
|
-
* - Keep first occurrence of each unique message
|
|
37
|
-
* - Preserve order for semantic coherence
|
|
38
|
-
* - Never dedupe system messages (they set context)
|
|
39
|
-
* - Allow duplicate user messages (user might repeat intentionally)
|
|
40
|
-
* - CRITICAL: Never dedupe assistant messages with tool_calls that are
|
|
41
|
-
* referenced by subsequent tool messages (breaks Anthropic tool_use/tool_result pairing)
|
|
42
|
-
*/
|
|
43
|
-
export function deduplicateMessages(messages) {
|
|
44
|
-
const seen = new Set();
|
|
45
|
-
const result = [];
|
|
46
|
-
let duplicatesRemoved = 0;
|
|
47
|
-
// First pass: collect all tool_call_ids that are referenced by tool messages
|
|
48
|
-
// These tool_calls MUST be preserved to maintain tool_use/tool_result pairing
|
|
49
|
-
const referencedToolCallIds = new Set();
|
|
50
|
-
for (const message of messages) {
|
|
51
|
-
if (message.role === "tool" && message.tool_call_id) {
|
|
52
|
-
referencedToolCallIds.add(message.tool_call_id);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
for (const message of messages) {
|
|
56
|
-
// Always keep system messages (they set important context)
|
|
57
|
-
if (message.role === "system") {
|
|
58
|
-
result.push(message);
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
// Always keep user messages (user might repeat intentionally)
|
|
62
|
-
if (message.role === "user") {
|
|
63
|
-
result.push(message);
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
// Always keep tool messages (they are results of tool calls)
|
|
67
|
-
// Removing them would break the tool_use/tool_result pairing
|
|
68
|
-
if (message.role === "tool") {
|
|
69
|
-
result.push(message);
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
72
|
-
// For assistant messages with tool_calls, check if any are referenced
|
|
73
|
-
// by subsequent tool messages - if so, we MUST keep this message
|
|
74
|
-
if (message.role === "assistant" && message.tool_calls) {
|
|
75
|
-
const hasReferencedToolCall = message.tool_calls.some((tc) => referencedToolCallIds.has(tc.id));
|
|
76
|
-
if (hasReferencedToolCall) {
|
|
77
|
-
// This assistant message has tool_calls that are referenced - keep it
|
|
78
|
-
result.push(message);
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
// For other assistant messages, check for duplicates
|
|
83
|
-
const hash = hashMessage(message);
|
|
84
|
-
if (!seen.has(hash)) {
|
|
85
|
-
seen.add(hash);
|
|
86
|
-
result.push(message);
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
duplicatesRemoved++;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return {
|
|
93
|
-
messages: result,
|
|
94
|
-
duplicatesRemoved,
|
|
95
|
-
originalCount: messages.length,
|
|
96
|
-
};
|
|
97
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Layer 3: Dictionary Encoding
|
|
3
|
-
*
|
|
4
|
-
* Replaces frequently repeated long phrases with short codes.
|
|
5
|
-
* Uses a static codebook of common patterns from production logs.
|
|
6
|
-
*
|
|
7
|
-
* Safe for LLM: Reversible substitution with codebook header.
|
|
8
|
-
* Expected savings: 4-8%
|
|
9
|
-
*/
|
|
10
|
-
import { NormalizedMessage } from "../types.js";
|
|
11
|
-
export interface DictionaryResult {
|
|
12
|
-
messages: NormalizedMessage[];
|
|
13
|
-
substitutionCount: number;
|
|
14
|
-
usedCodes: Set<string>;
|
|
15
|
-
charsSaved: number;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Apply dictionary encoding to all messages.
|
|
19
|
-
*/
|
|
20
|
-
export declare function encodeMessages(messages: NormalizedMessage[]): DictionaryResult;
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Layer 3: Dictionary Encoding
|
|
3
|
-
*
|
|
4
|
-
* Replaces frequently repeated long phrases with short codes.
|
|
5
|
-
* Uses a static codebook of common patterns from production logs.
|
|
6
|
-
*
|
|
7
|
-
* Safe for LLM: Reversible substitution with codebook header.
|
|
8
|
-
* Expected savings: 4-8%
|
|
9
|
-
*/
|
|
10
|
-
import { getInverseCodebook } from "../codebook.js";
|
|
11
|
-
/**
|
|
12
|
-
* Apply dictionary encoding to a string.
|
|
13
|
-
* Returns the encoded string and stats.
|
|
14
|
-
*/
|
|
15
|
-
function encodeContent(content, inverseCodebook) {
|
|
16
|
-
let encoded = content;
|
|
17
|
-
let substitutions = 0;
|
|
18
|
-
let charsSaved = 0;
|
|
19
|
-
const codes = new Set();
|
|
20
|
-
// Sort phrases by length (longest first) to avoid partial matches
|
|
21
|
-
const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);
|
|
22
|
-
for (const phrase of phrases) {
|
|
23
|
-
const code = inverseCodebook[phrase];
|
|
24
|
-
const regex = new RegExp(escapeRegex(phrase), "g");
|
|
25
|
-
const matches = encoded.match(regex);
|
|
26
|
-
if (matches && matches.length > 0) {
|
|
27
|
-
encoded = encoded.replace(regex, code);
|
|
28
|
-
substitutions += matches.length;
|
|
29
|
-
charsSaved += matches.length * (phrase.length - code.length);
|
|
30
|
-
codes.add(code);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return { encoded, substitutions, codes, charsSaved };
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Escape special regex characters in a string.
|
|
37
|
-
*/
|
|
38
|
-
function escapeRegex(str) {
|
|
39
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Apply dictionary encoding to all messages.
|
|
43
|
-
*/
|
|
44
|
-
export function encodeMessages(messages) {
|
|
45
|
-
const inverseCodebook = getInverseCodebook();
|
|
46
|
-
let totalSubstitutions = 0;
|
|
47
|
-
let totalCharsSaved = 0;
|
|
48
|
-
const allUsedCodes = new Set();
|
|
49
|
-
const result = messages.map((message) => {
|
|
50
|
-
if (!message.content || typeof message.content !== "string")
|
|
51
|
-
return message;
|
|
52
|
-
const { encoded, substitutions, codes, charsSaved } = encodeContent(message.content, inverseCodebook);
|
|
53
|
-
totalSubstitutions += substitutions;
|
|
54
|
-
totalCharsSaved += charsSaved;
|
|
55
|
-
codes.forEach((code) => allUsedCodes.add(code));
|
|
56
|
-
return {
|
|
57
|
-
...message,
|
|
58
|
-
content: encoded,
|
|
59
|
-
};
|
|
60
|
-
});
|
|
61
|
-
return {
|
|
62
|
-
messages: result,
|
|
63
|
-
substitutionCount: totalSubstitutions,
|
|
64
|
-
usedCodes: allUsedCodes,
|
|
65
|
-
charsSaved: totalCharsSaved,
|
|
66
|
-
};
|
|
67
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* L7: Dynamic Codebook Builder
|
|
3
|
-
*
|
|
4
|
-
* Inspired by claw-compactor's frequency-based codebook.
|
|
5
|
-
* Builds codebook from actual content being compressed,
|
|
6
|
-
* rather than relying on static patterns.
|
|
7
|
-
*
|
|
8
|
-
* Finds phrases that appear 3+ times and replaces with short codes.
|
|
9
|
-
*/
|
|
10
|
-
import { NormalizedMessage } from "../types.js";
|
|
11
|
-
interface DynamicCodebookResult {
|
|
12
|
-
messages: NormalizedMessage[];
|
|
13
|
-
charsSaved: number;
|
|
14
|
-
dynamicCodes: Record<string, string>;
|
|
15
|
-
substitutions: number;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Apply dynamic codebook to messages.
|
|
19
|
-
*/
|
|
20
|
-
export declare function applyDynamicCodebook(messages: NormalizedMessage[]): DynamicCodebookResult;
|
|
21
|
-
/**
|
|
22
|
-
* Generate header for dynamic codes (to include in system message).
|
|
23
|
-
*/
|
|
24
|
-
export declare function generateDynamicCodebookHeader(codebook: Record<string, string>): string;
|
|
25
|
-
export {};
|