@@ -1,9 +1,11 @@
11 import {
22 type AssistantMessage,
33 type Context,
4+ type Message,
45 streamSimple,
56 type TextContent,
67 type ToolCall,
8+ type ToolResultMessage,
79 } from "@mariozechner/pi-ai";
810 import { getApiKey } from "./oauth";
911 import type {
@@ -13,6 +15,48 @@ import type {
1315 ToolAndRunner,
1416 } from "./types";
1517
18+// ### JetBrains Junie: Observation Masking
19+// Published research found that **simply hiding old tool outputs** matched the quality of full LLM summarization with **zero extra compute**:
20+// https://blog.jetbrains.com/research/2025/12/efficient-context-management/
21+export function compactContext(messages: Message[]) {
22+ const KEEP_OBSERVATIONS = 10;
23+
24+ const toolResultIndices: number[] = [];
25+ for (let i = 0; i < messages.length; i++) {
26+ if (messages[i].role !== "toolResult") continue;
27+ const content = (messages[i] as ToolResultMessage).content;
28+ if (
29+ content.length === 1 &&
30+ content[0].type === "text" &&
31+ content[0].text.startsWith("Old environment output:")
32+ ) {
33+ continue;
34+ }
35+ toolResultIndices.push(i);
36+ }
37+
38+ if (toolResultIndices.length <= KEEP_OBSERVATIONS) return;
39+
40+ for (let i = 0; i < toolResultIndices.length - KEEP_OBSERVATIONS; i++) {
41+ const idx = toolResultIndices[i];
42+ const msg = messages[idx] as ToolResultMessage;
43+ let lines = 0;
44+ let images = 0;
45+ for (const c of msg.content) {
46+ if (c.type === "text") {
47+ lines += c.text.split(/\r?\n/).length;
48+ } else if (c.type === "image") {
49+ images++;
50+ }
51+ }
52+ let text = `Old environment output: (${lines} lines omitted)`;
53+ if (images > 0) {
54+ text += ` (${images} image${images > 1 ? "s" : ""} omitted)`;
55+ }
56+ msg.content = [{ type: "text", text }];
57+ }
58+}
59+
1660 export async function* streamAgent(
1761 agentCtx: AgentContex,
1862 ): AsyncGenerator<AgentEvent> {