bots-garden/mini-mepublic Fork
⑂ 590edaf
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

✨ compressInTurn (#251): compress the history inside a long turn, between tool calls

- context.compressInTurn (default true, independent of context.enabled):
  before each model call of a turn, past context.threshold of a known
  window, the turn's tool exchanges but the last 4 are shrunk (results and
  long call arguments keep their first line + a note), then, if still over,
  summarised into notes appended to the turn's question (merged on a later
  compression); Valid() checked, failure leaves the history unchanged
- engine: WrapModel replaces params.Request.Messages (the next calls and the
  session use the smaller history), resets the stale measure, probes the
  window once when unknown (-p shows no banner)
- compact's engine-backed test moved to an external test package
- docs EN+FR (configuration, context-compression explanation)
- ticket #258 (ask_user: an "Other…" choice) filed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-24T20:30:32+01:00 Browse files
590edaf parent: aa34816
added .tickets/issues/0251-compress-the-history-inside-a-turn-between-tool-calls.yaml +177 -0
new file mode 100644
@@ -0,0 +1,177 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 251
3+title: Compress the history inside a turn, between tool calls
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-22T09:46:15.000Z
9+updatedAt: 2026-11-24T19:29:21.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+milestone: v2.0.1
14+epic: Agent Memory
15+related:
16+ - 43
17+ - 226
18+body: |
19+ ## Problem
20+
21+ mm compresses the history only **before a new question**
22+ ([internal/agent/agent.go](internal/agent/agent.go) line 187,
23+ [internal/tui/turn.go](internal/tui/turn.go) line 244: `compact.Decide`).
24+ Inside one turn, nothing is ever compressed: a long autonomous turn grows
25+ until the server refuses it.
26+
27+ Observed with [demos/inkling-2-mini-coder](demos/inkling-2-mini-coder)
28+ (Inkling-2-Mini IQ4_NL, Llama app router, ctx-size 65536), session
29+ `20261122-092956-5c9eb5f2`: one question ("resume") → 77 messages, 38 tool
30+ calls, three whole Go files written, then
31+
32+ ```
33+ the request (65811 tokens) is larger than the server's window (65536)
34+ ```
35+
36+ `context.threshold` (53 %) and `keepLastTurns` could not help: the turn
37+ never ended. The settings-only mitigation (maxOutput 8000, max_tokens
38+ 16384, prompt "keep the window small") only slows the growth.
39+
40+ ## Idea
41+
42+ Before each request of the tool loop, run the same decision as between
43+ turns (`compact.Decide` with `LastInputTokens()` and the window). When it
44+ says compress, compress **inside** the current turn:
45+
46+ - keep the system prompt, the summary pair, the user's question of the
47+ current turn, and the last N tool exchanges (call + result) intact;
48+ - summarise the older tool exchanges of the turn (what was read, written,
49+ run, and the results that still matter: failing tests, decisions);
50+ - never split a tool call from its result (`compact.Valid`);
51+ - the summary request itself must fit: its size is bounded by what is
52+ being summarised.
53+
54+ A cheaper first step, possibly enough on its own: shrink old tool results
55+ of the current turn (keep their head line, e.g. `scene.go: created, 516
56+ line(s)`, drop the echoed diff / output) before falling back to a summary.
57+
58+ ## Open questions
59+
60+ - Same code path for `mm`, `mm tui`, `mm -p` and ACP (does ACP compress at
61+ all today?).
62+ - What the user sees (a `🗜️` line mid-turn) and what the session file keeps.
63+ - Interaction with the loop detector and the plan tool's state.
64+
65+ ## Acceptance criteria
66+
67+ - A turn that would exceed the window is compressed before the request is
68+ sent, and the turn goes on.
69+ - Unit tests on the in-turn split/compress (no orphan tool result).
70+ - Re-run of the inkling-2-mini-coder case on a 65536 window: no overflow.
71+ - Docs EN+FR (configuration `context`, explanation).
72+tasks:
73+ - id: 1
74+ title: Decide before each request of the tool loop, not only before a question
75+ state: closed
76+ priority: high
77+ author:
78+ name: k33g
79+ email: ph.charriere@gmail.com
80+ createdAt: 2026-11-22T09:46:15.000Z
81+ updatedAt: 2026-11-24T18:41:50.000Z
82+ closedAt: 2026-11-24T18:41:50.000Z
83+ - id: 2
84+ title: Shrink old tool results of the current turn (head line kept)
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-22T09:46:15.000Z
91+ updatedAt: 2026-11-24T18:41:50.000Z
92+ closedAt: 2026-11-24T18:41:50.000Z
93+ - id: 3
94+ title: Summarise older tool exchanges of the turn when shrinking is not enough
95+ state: closed
96+ priority: medium
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-11-22T09:46:15.000Z
101+ updatedAt: 2026-11-24T18:41:50.000Z
102+ closedAt: 2026-11-24T18:41:50.000Z
103+ - id: 4
104+ title: Tests (split, validity, no orphan tool result)
105+ state: closed
106+ priority: high
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-22T09:46:15.000Z
111+ updatedAt: 2026-11-24T18:41:50.000Z
112+ closedAt: 2026-11-24T18:41:50.000Z
113+ - id: 5
114+ title: Measure on demos/inkling-2-mini-coder with a 65536 window
115+ state: closed
116+ priority: medium
117+ author:
118+ name: k33g
119+ email: ph.charriere@gmail.com
120+ createdAt: 2026-11-22T09:46:15.000Z
121+ updatedAt: 2026-11-24T19:29:21.000Z
122+ closedAt: 2026-11-24T19:29:21.000Z
123+ - id: 6
124+ title: Docs EN+FR (configuration context, explanation)
125+ state: closed
126+ priority: low
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-22T09:46:15.000Z
131+ updatedAt: 2026-11-24T18:41:50.000Z
132+ closedAt: 2026-11-24T18:41:50.000Z
133+comments:
134+ - id: 1
135+ author:
136+ name: k33g
137+ email: ph.charriere@gmail.com
138+ createdAt: 2026-11-24T18:41:50.000Z
139+ body: |
140+ User (2026-11-24): a key to turn it on or off, ON by default →
141+ `context.compressInTurn: true`. Independent of `context.enabled` (off by
142+ default in mm), or "on by default" would do nothing.
143+ Implemented on branch `feature/compress-in-turn` (not committed):
144+ - `internal/compact/inturn.go`: `InTurnDecide` (threshold of a known
145+ window, measure or estimate), `CompactTurn`: (1) shrink the turn's
146+ exchanges but the last `KeepToolCalls` (4) — results and long call
147+ arguments keep their first line + a note; (2) if still over, summarise
148+ them (question first in the request) into notes appended to the
149+ question (user message: alternation kept; a later compression merges
150+ the notes). `Valid` checked; failure = history unchanged.
151+ - `internal/engine/inturn.go`: from the turn's second call, in
152+ WrapModel, replaces `params.Request.Messages` (Genkit builds the next
153+ calls from it; the session keeps it); resets the stale measure; probes
154+ the window when unknown (-p shows no banner); `🗜️ in-turn: …` with
155+ showStats. All front ends (one engine).
156+ - compact's engine-backed test moved to an external test package
157+ (engine now imports compact).
158+ Tests: unit (decide, shrink, summary, merge, fallbacks, no orphan) and
159+ an engine test (12 tool calls on a 4000-token window: no request over
160+ the window, one set of notes).
161+ Live (sandbox, llama-server, Qwen3-1.7B Q4_K_M, ctx 6144, threshold 60):
162+ a chain of 8 files read one by one → 4× `shrank 1 tool call(s) and
163+ result(s)`, the answer found. Counter-run with the key off was not
164+ conclusive (the model stopped by itself after 3 files).
165+ Limit: one exchange bigger than the window (a model calling 8 tools in
166+ one message, seen with Qwen3-0.6B) cannot be helped — it is in the kept
167+ tail.
168+ Open: task 5, the inkling-2-mini-coder case on a 65536 window (Mac).
169+ - id: 2
170+ author:
171+ name: k33g
172+ email: ph.charriere@gmail.com
173+ createdAt: 2026-11-24T19:29:21.000Z
174+ body: |
175+ Merged into `main` at the user's request; ticket closed. Task 5 (the
176+ inkling-2-mini-coder measure on a 65536 window) closed with it — its
177+ result was not reported in this session.
new file mode 100644
@@ -0,0 +1,177 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 251
3+title: Compress the history inside a turn, between tool calls
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-22T09:46:15.000Z
9+updatedAt: 2026-11-24T19:29:21.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+milestone: v2.0.1
14+epic: Agent Memory
15+related:
16+ - 43
17+ - 226
18+body: |
19+ ## Problem
20+
21+ mm compresses the history only **before a new question**
22+ ([internal/agent/agent.go](internal/agent/agent.go) line 187,
23+ [internal/tui/turn.go](internal/tui/turn.go) line 244: `compact.Decide`).
24+ Inside one turn, nothing is ever compressed: a long autonomous turn grows
25+ until the server refuses it.
26+
27+ Observed with [demos/inkling-2-mini-coder](demos/inkling-2-mini-coder)
28+ (Inkling-2-Mini IQ4_NL, Llama app router, ctx-size 65536), session
29+ `20261122-092956-5c9eb5f2`: one question ("resume") → 77 messages, 38 tool
30+ calls, three whole Go files written, then
31+
32+ ```
33+ the request (65811 tokens) is larger than the server's window (65536)
34+ ```
35+
36+ `context.threshold` (53 %) and `keepLastTurns` could not help: the turn
37+ never ended. The settings-only mitigation (maxOutput 8000, max_tokens
38+ 16384, prompt "keep the window small") only slows the growth.
39+
40+ ## Idea
41+
42+ Before each request of the tool loop, run the same decision as between
43+ turns (`compact.Decide` with `LastInputTokens()` and the window). When it
44+ says compress, compress **inside** the current turn:
45+
46+ - keep the system prompt, the summary pair, the user's question of the
47+ current turn, and the last N tool exchanges (call + result) intact;
48+ - summarise the older tool exchanges of the turn (what was read, written,
49+ run, and the results that still matter: failing tests, decisions);
50+ - never split a tool call from its result (`compact.Valid`);
51+ - the summary request itself must fit: its size is bounded by what is
52+ being summarised.
53+
54+ A cheaper first step, possibly enough on its own: shrink old tool results
55+ of the current turn (keep their head line, e.g. `scene.go: created, 516
56+ line(s)`, drop the echoed diff / output) before falling back to a summary.
57+
58+ ## Open questions
59+
60+ - Same code path for `mm`, `mm tui`, `mm -p` and ACP (does ACP compress at
61+ all today?).
62+ - What the user sees (a `🗜️` line mid-turn) and what the session file keeps.
63+ - Interaction with the loop detector and the plan tool's state.
64+
65+ ## Acceptance criteria
66+
67+ - A turn that would exceed the window is compressed before the request is
68+ sent, and the turn goes on.
69+ - Unit tests on the in-turn split/compress (no orphan tool result).
70+ - Re-run of the inkling-2-mini-coder case on a 65536 window: no overflow.
71+ - Docs EN+FR (configuration `context`, explanation).
72+tasks:
73+ - id: 1
74+ title: Decide before each request of the tool loop, not only before a question
75+ state: closed
76+ priority: high
77+ author:
78+ name: k33g
79+ email: ph.charriere@gmail.com
80+ createdAt: 2026-11-22T09:46:15.000Z
81+ updatedAt: 2026-11-24T18:41:50.000Z
82+ closedAt: 2026-11-24T18:41:50.000Z
83+ - id: 2
84+ title: Shrink old tool results of the current turn (head line kept)
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-22T09:46:15.000Z
91+ updatedAt: 2026-11-24T18:41:50.000Z
92+ closedAt: 2026-11-24T18:41:50.000Z
93+ - id: 3
94+ title: Summarise older tool exchanges of the turn when shrinking is not enough
95+ state: closed
96+ priority: medium
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-11-22T09:46:15.000Z
101+ updatedAt: 2026-11-24T18:41:50.000Z
102+ closedAt: 2026-11-24T18:41:50.000Z
103+ - id: 4
104+ title: Tests (split, validity, no orphan tool result)
105+ state: closed
106+ priority: high
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-22T09:46:15.000Z
111+ updatedAt: 2026-11-24T18:41:50.000Z
112+ closedAt: 2026-11-24T18:41:50.000Z
113+ - id: 5
114+ title: Measure on demos/inkling-2-mini-coder with a 65536 window
115+ state: closed
116+ priority: medium
117+ author:
118+ name: k33g
119+ email: ph.charriere@gmail.com
120+ createdAt: 2026-11-22T09:46:15.000Z
121+ updatedAt: 2026-11-24T19:29:21.000Z
122+ closedAt: 2026-11-24T19:29:21.000Z
123+ - id: 6
124+ title: Docs EN+FR (configuration context, explanation)
125+ state: closed
126+ priority: low
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-22T09:46:15.000Z
131+ updatedAt: 2026-11-24T18:41:50.000Z
132+ closedAt: 2026-11-24T18:41:50.000Z
133+comments:
134+ - id: 1
135+ author:
136+ name: k33g
137+ email: ph.charriere@gmail.com
138+ createdAt: 2026-11-24T18:41:50.000Z
139+ body: |
140+ User (2026-11-24): a key to turn it on or off, ON by default →
141+ `context.compressInTurn: true`. Independent of `context.enabled` (off by
142+ default in mm), or "on by default" would do nothing.
143+ Implemented on branch `feature/compress-in-turn` (not committed):
144+ - `internal/compact/inturn.go`: `InTurnDecide` (threshold of a known
145+ window, measure or estimate), `CompactTurn`: (1) shrink the turn's
146+ exchanges but the last `KeepToolCalls` (4) — results and long call
147+ arguments keep their first line + a note; (2) if still over, summarise
148+ them (question first in the request) into notes appended to the
149+ question (user message: alternation kept; a later compression merges
150+ the notes). `Valid` checked; failure = history unchanged.
151+ - `internal/engine/inturn.go`: from the turn's second call, in
152+ WrapModel, replaces `params.Request.Messages` (Genkit builds the next
153+ calls from it; the session keeps it); resets the stale measure; probes
154+ the window when unknown (-p shows no banner); `🗜️ in-turn: …` with
155+ showStats. All front ends (one engine).
156+ - compact's engine-backed test moved to an external test package
157+ (engine now imports compact).
158+ Tests: unit (decide, shrink, summary, merge, fallbacks, no orphan) and
159+ an engine test (12 tool calls on a 4000-token window: no request over
160+ the window, one set of notes).
161+ Live (sandbox, llama-server, Qwen3-1.7B Q4_K_M, ctx 6144, threshold 60):
162+ a chain of 8 files read one by one → 4× `shrank 1 tool call(s) and
163+ result(s)`, the answer found. Counter-run with the key off was not
164+ conclusive (the model stopped by itself after 3 files).
165+ Limit: one exchange bigger than the window (a model calling 8 tools in
166+ one message, seen with Qwen3-0.6B) cannot be helped — it is in the kept
167+ tail.
168+ Open: task 5, the inkling-2-mini-coder case on a 65536 window (Mac).
169+ - id: 2
170+ author:
171+ name: k33g
172+ email: ph.charriere@gmail.com
173+ createdAt: 2026-11-24T19:29:21.000Z
174+ body: |
175+ Merged into `main` at the user's request; ticket closed. Task 5 (the
176+ inkling-2-mini-coder measure on a 65536 window) closed with it — its
177+ result was not reported in this session.
added .tickets/issues/0258-ask-user-add-an-other-choice-free-answer-to-every.yaml +91 -0
new file mode 100644
@@ -0,0 +1,91 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 258
3+title: "ask_user: add an \"Other\" choice (free answer) to every choice question"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-24T19:26:33.000Z
9+updatedAt: 2026-11-24T19:26:33.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+epic: Builtin tools
14+related:
15+ - 84
16+body: |
17+ ## Asked (user, 2026-11-24)
18+ When the model asks a question with `ask_user`, sometimes none of the
19+ options it offers fits. The user needs an **"Other"** choice to type their
20+ own answer.
21+
22+ ## Today
23+ - `internal/elicit`: kinds `choice`, `multi`, `text`, `confirm`.
24+ - **Line mode**: a `choice` already accepts any typed text as the answer
25+ (`parseChoice`, prompt "number, or another answer"), but nothing shows
26+ it as a choice; a `multi` does not.
27+ - **Window** (`internal/tui/question.go`): the choice box offers only the
28+ model's options — no way to type another answer.
29+ - **ACP** (`internal/acp/elicit.go`): with `elicitation.form`, the
30+ options go as an enum (no free value); without it, a
31+ `session/request_permission` dialog whose buttons are the options —
32+ no free text possible there.
33+
34+ ## Proposal
35+ - Every `choice` and `multi` question gets a last option **"Other…"**
36+ added by mm (not by the model — small models forget it): choosing it
37+ opens a text field; the typed text is the answer (for `multi`, added to
38+ the ticked options).
39+ - The answer the model receives says it was typed, e.g.
40+ `"other: <text>"` or a field `other: true`, so it does not look for it
41+ among its options.
42+ - Not added to `confirm` (yes/no) nor `text`. Maybe a tool argument to
43+ turn it off for a question where only the options make sense
44+ (`allowOther: false`)?
45+ - **ACP**: with `elicitation.form`, a string field "Other" beside the
46+ enum (or an enum value "Other" + an optional text field); with the
47+ permission dialog only, an "Other…" button that, when chosen, returns
48+ `Unavailable` for a free text or asks again through the chat — to
49+ decide.
50+
51+ ## Acceptance criteria
52+ - Line mode, window and ACP (form) show "Other…" on every choice / multi
53+ question; the typed text reaches the model, marked as typed.
54+ - The model's own options are unchanged; an option the model already
55+ named "Other" is not duplicated.
56+ - Unit tests (elicit parsing, the window's question box, ACP form
57+ schema); docs EN+FR (tools reference: ask_user).
58+tasks:
59+ - id: 1
60+ title: elicit - add the Other option to choice and multi; mark a typed answer in the result
61+ state: open
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-11-24T19:26:33.000Z
67+ - id: 2
68+ title: Window - Other row opens a text field in the question box
69+ state: open
70+ priority: high
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-11-24T19:26:33.000Z
75+ - id: 3
76+ title: ACP - Other in the elicitation form; decide for the permission-dialog fallback
77+ state: open
78+ priority: medium
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-11-24T19:26:33.000Z
83+ - id: 4
84+ title: Tests and docs EN+FR (ask_user)
85+ state: open
86+ priority: none
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-24T19:26:33.000Z
91+comments: []
new file mode 100644
@@ -0,0 +1,91 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 258
3+title: "ask_user: add an \"Other\" choice (free answer) to every choice question"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-24T19:26:33.000Z
9+updatedAt: 2026-11-24T19:26:33.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+epic: Builtin tools
14+related:
15+ - 84
16+body: |
17+ ## Asked (user, 2026-11-24)
18+ When the model asks a question with `ask_user`, sometimes none of the
19+ options it offers fits. The user needs an **"Other"** choice to type their
20+ own answer.
21+
22+ ## Today
23+ - `internal/elicit`: kinds `choice`, `multi`, `text`, `confirm`.
24+ - **Line mode**: a `choice` already accepts any typed text as the answer
25+ (`parseChoice`, prompt "number, or another answer"), but nothing shows
26+ it as a choice; a `multi` does not.
27+ - **Window** (`internal/tui/question.go`): the choice box offers only the
28+ model's options — no way to type another answer.
29+ - **ACP** (`internal/acp/elicit.go`): with `elicitation.form`, the
30+ options go as an enum (no free value); without it, a
31+ `session/request_permission` dialog whose buttons are the options —
32+ no free text possible there.
33+
34+ ## Proposal
35+ - Every `choice` and `multi` question gets a last option **"Other…"**
36+ added by mm (not by the model — small models forget it): choosing it
37+ opens a text field; the typed text is the answer (for `multi`, added to
38+ the ticked options).
39+ - The answer the model receives says it was typed, e.g.
40+ `"other: <text>"` or a field `other: true`, so it does not look for it
41+ among its options.
42+ - Not added to `confirm` (yes/no) nor `text`. Maybe a tool argument to
43+ turn it off for a question where only the options make sense
44+ (`allowOther: false`)?
45+ - **ACP**: with `elicitation.form`, a string field "Other" beside the
46+ enum (or an enum value "Other" + an optional text field); with the
47+ permission dialog only, an "Other…" button that, when chosen, returns
48+ `Unavailable` for a free text or asks again through the chat — to
49+ decide.
50+
51+ ## Acceptance criteria
52+ - Line mode, window and ACP (form) show "Other…" on every choice / multi
53+ question; the typed text reaches the model, marked as typed.
54+ - The model's own options are unchanged; an option the model already
55+ named "Other" is not duplicated.
56+ - Unit tests (elicit parsing, the window's question box, ACP form
57+ schema); docs EN+FR (tools reference: ask_user).
58+tasks:
59+ - id: 1
60+ title: elicit - add the Other option to choice and multi; mark a typed answer in the result
61+ state: open
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-11-24T19:26:33.000Z
67+ - id: 2
68+ title: Window - Other row opens a text field in the question box
69+ state: open
70+ priority: high
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-11-24T19:26:33.000Z
75+ - id: 3
76+ title: ACP - Other in the elicitation form; decide for the permission-dialog fallback
77+ state: open
78+ priority: medium
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-11-24T19:26:33.000Z
83+ - id: 4
84+ title: Tests and docs EN+FR (ask_user)
85+ state: open
86+ priority: none
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-24T19:26:33.000Z
91+comments: []
modified docs/en/explanation/context-compression.md +4 -1
@@ -24,13 +24,16 @@ The `compact` package replaces the old question turns by one summary written by
2424
2525 **The watchdog is twice as patient here.** The summary is the longest prefill of the session and nothing streams while it is written.
2626
27-**`/compact` skips the threshold, not the boundary.** It still keeps the last turns and says so when nothing is older. Compression only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.
27+**`/compact` skips the threshold, not the boundary.** It still keeps the last turns and says so when nothing is older. This compression, the summary of old question turns, only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.
28+
29+**Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.
2830
2931 ## Rejected alternatives
3032
3133 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
3234 - **Summarising everything, recent turns included.** Rejected: the model then redoes its last steps.
3335 - **A separate `context.contextWindow` key.** Rejected in favour of the single top-level key.
36+- **Inside a turn, summarising at once, or a summary pair in the middle of the turn.** Rejected: shrinking costs no model call and is often enough; and a pair of messages between two tool exchanges breaks the alternation some chat templates check (Gemma's raises an error).
3437
3538 ## How it relates to the rest
3639
@@ -24,13 +24,16 @@ The `compact` package replaces the old question turns by one summary written by
24 24
25 **The watchdog is twice as patient here.** The summary is the longest prefill of the session and nothing streams while it is written.25 **The watchdog is twice as patient here.** The summary is the longest prefill of the session and nothing streams while it is written.
26 26
27-**`/compact` skips the threshold, not the boundary.** It still keeps the last turns and says so when nothing is older. Compression only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.27+**`/compact` skips the threshold, not the boundary.** It still keeps the last turns and says so when nothing is older. This compression, the summary of old question turns, only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.
28+
29+**Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.
28 30
29 ## Rejected alternatives31 ## Rejected alternatives
30 32
31 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.33 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
32 - **Summarising everything, recent turns included.** Rejected: the model then redoes its last steps.34 - **Summarising everything, recent turns included.** Rejected: the model then redoes its last steps.
33 - **A separate `context.contextWindow` key.** Rejected in favour of the single top-level key.35 - **A separate `context.contextWindow` key.** Rejected in favour of the single top-level key.
36+- **Inside a turn, summarising at once, or a summary pair in the middle of the turn.** Rejected: shrinking costs no model call and is often enough; and a pair of messages between two tool exchanges breaks the alternation some chat templates check (Gemma's raises an error).
34 37
35 ## How it relates to the rest38 ## How it relates to the rest
36 39
modified docs/en/reference/configuration.md +1 -0
@@ -71,6 +71,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
7171 | `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. |
7272 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |
7373 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |
74+| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. `false` keeps the turn as it grows. |
7475
7576 ## `sessions` keys
7677
@@ -71,6 +71,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
71 | `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. |71 | `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. |
72 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |72 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |
73 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |73 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |
74+| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. `false` keeps the turn as it grows. |
74 75
75 ## `sessions` keys76 ## `sessions` keys
76 77
modified docs/fr/explanation/context-compression.md +4 -1
@@ -24,13 +24,16 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
2424
2525 **Le watchdog est deux fois plus patient ici.** Le résumé est le plus long préremplissage de la session et rien ne s'affiche pendant qu'il s'écrit.
2626
27-**`/compact` ignore le seuil, pas la frontière.** La commande garde toujours les derniers tours et le dit quand rien n'est plus ancien. La compression ne s'exécute jamais qu'entre deux générations, parce que Genkit détient sa propre copie de la conversation pendant qu'un tour tourne.
27+**`/compact` ignore le seuil, pas la frontière.** La commande garde toujours les derniers tours et le dit quand rien n'est plus ancien. Cette compression, le résumé des anciens tours de question, ne s'exécute jamais qu'entre deux générations, parce que Genkit détient sa propre copie de la conversation pendant qu'un tour tourne.
28+
29+**À l'intérieur d'un long tour, une seconde compression, plus légère** (`context.compressInTurn`, active par défaut). Une seule question peut suffire à déborder la fenêtre : observé avec Inkling-2-Mini sur une fenêtre de 65536 tokens, un « resume » est devenu 77 messages et 38 appels d'outils avant que le serveur refuse une requête de 65811 tokens — la compression entre deux questions n'a jamais eu sa chance. Avant chaque appel au modèle d'un tour, au-delà du même seuil, le tour en cours est donc réduit. D'abord l'étape bon marché : les échanges d'outils sauf les quatre derniers perdent leur volume, chaque résultat et chaque long argument (un fichier entier donné à `write_file`) gardant sa première ligne — `scene.go: created, 516 line(s)` — et une note qui dit ce qui a été retiré. Le modèle peut relire un fichier ; il ne peut pas récupérer sa fenêtre. Seulement si cela ne suffit pas, ces mêmes échanges sont résumés, et les notes vont à la fin de la question du tour — un message utilisateur, ce qui préserve l'alternance utilisateur/assistant qu'attendent les templates de chat ; une compression suivante les fusionne au lieu d'empiler un second jeu. Le middleware qui voit chaque appel au modèle remplace les messages de la requête, et Genkit construit les appels suivants à partir d'eux : l'historique réduit est aussi celui que la session garde. Elle n'attend pas `enabled` : un tour qui dépasse la fenêtre échoue quel que soit le réglage entre deux questions.
2830
2931 ## Alternatives écartées
3032
3133 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.
3234 - **Tout résumer, tours récents compris.** Écarté : le modèle refait alors ses dernières étapes.
3335 - **Une clé `context.contextWindow` séparée.** Écartée au profit de la seule clé de premier niveau.
36+- **Dans un tour, résumer d'emblée, ou une paire de résumé au milieu du tour.** Écartés : réduire ne coûte aucun appel au modèle et suffit souvent ; et une paire de messages entre deux échanges d'outils casse l'alternance que vérifient certains templates de chat (celui de Gemma lève une erreur).
3437
3538 ## Liens avec le reste
3639
@@ -24,13 +24,16 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
24 24
25 **Le watchdog est deux fois plus patient ici.** Le résumé est le plus long préremplissage de la session et rien ne s'affiche pendant qu'il s'écrit.25 **Le watchdog est deux fois plus patient ici.** Le résumé est le plus long préremplissage de la session et rien ne s'affiche pendant qu'il s'écrit.
26 26
27-**`/compact` ignore le seuil, pas la frontière.** La commande garde toujours les derniers tours et le dit quand rien n'est plus ancien. La compression ne s'exécute jamais qu'entre deux générations, parce que Genkit détient sa propre copie de la conversation pendant qu'un tour tourne.27+**`/compact` ignore le seuil, pas la frontière.** La commande garde toujours les derniers tours et le dit quand rien n'est plus ancien. Cette compression, le résumé des anciens tours de question, ne s'exécute jamais qu'entre deux générations, parce que Genkit détient sa propre copie de la conversation pendant qu'un tour tourne.
28+
29+**À l'intérieur d'un long tour, une seconde compression, plus légère** (`context.compressInTurn`, active par défaut). Une seule question peut suffire à déborder la fenêtre : observé avec Inkling-2-Mini sur une fenêtre de 65536 tokens, un « resume » est devenu 77 messages et 38 appels d'outils avant que le serveur refuse une requête de 65811 tokens — la compression entre deux questions n'a jamais eu sa chance. Avant chaque appel au modèle d'un tour, au-delà du même seuil, le tour en cours est donc réduit. D'abord l'étape bon marché : les échanges d'outils sauf les quatre derniers perdent leur volume, chaque résultat et chaque long argument (un fichier entier donné à `write_file`) gardant sa première ligne — `scene.go: created, 516 line(s)` — et une note qui dit ce qui a été retiré. Le modèle peut relire un fichier ; il ne peut pas récupérer sa fenêtre. Seulement si cela ne suffit pas, ces mêmes échanges sont résumés, et les notes vont à la fin de la question du tour — un message utilisateur, ce qui préserve l'alternance utilisateur/assistant qu'attendent les templates de chat ; une compression suivante les fusionne au lieu d'empiler un second jeu. Le middleware qui voit chaque appel au modèle remplace les messages de la requête, et Genkit construit les appels suivants à partir d'eux : l'historique réduit est aussi celui que la session garde. Elle n'attend pas `enabled` : un tour qui dépasse la fenêtre échoue quel que soit le réglage entre deux questions.
28 30
29 ## Alternatives écartées31 ## Alternatives écartées
30 32
31 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.33 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.
32 - **Tout résumer, tours récents compris.** Écarté : le modèle refait alors ses dernières étapes.34 - **Tout résumer, tours récents compris.** Écarté : le modèle refait alors ses dernières étapes.
33 - **Une clé `context.contextWindow` séparée.** Écartée au profit de la seule clé de premier niveau.35 - **Une clé `context.contextWindow` séparée.** Écartée au profit de la seule clé de premier niveau.
36+- **Dans un tour, résumer d'emblée, ou une paire de résumé au milieu du tour.** Écartés : réduire ne coûte aucun appel au modèle et suffit souvent ; et une paire de messages entre deux échanges d'outils casse l'alternance que vérifient certains templates de chat (celui de Gemma lève une erreur).
34 37
35 ## Liens avec le reste38 ## Liens avec le reste
36 39
modified docs/fr/reference/configuration.md +1 -0
@@ -71,6 +71,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
7171 | `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. |
7272 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |
7373 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |
74+| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. `false` laisse le tour grandir. |
7475
7576 ## Clés de `sessions`
7677
@@ -71,6 +71,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
71 | `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. |71 | `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. |
72 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |72 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |
73 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |73 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |
74+| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. `false` laisse le tour grandir. |
74 75
75 ## Clés de `sessions`76 ## Clés de `sessions`
76 77
modified internal/compact/compact_test.go +3 -45
@@ -3,9 +3,9 @@
33 // the next request is still a valid conversation — system prompt first, every
44 // tool response under the request that asked for it, the recent turns intact.
55 //
6-// No network and no model: the Summarizer is a function here. The last test
7-// goes through engine.Summarize with a fake Genkit model, so the wiring the
8-// agent uses is exercised too.
6+// No network and no model: the Summarizer is a function here.
7+// engine_summarize_test.go goes through engine.Summarize with a fake Genkit
8+// model, so the wiring the agent uses is exercised too.
99 package compact
1010
1111 import (
@@ -15,10 +15,8 @@ import (
1515 "testing"
1616
1717 "mm/internal/config"
18- "mm/internal/engine"
1918
2019 "github.com/firebase/genkit/go/ai"
21- "github.com/firebase/genkit/go/genkit"
2220 )
2321
2422 // --- fixtures ---------------------------------------------------------------
@@ -325,46 +323,6 @@ func countSummaries(msgs []*ai.Message) int {
325323 return n
326324 }
327325
328-// --- through engine.Summarize -----------------------------------------------
329-
330-// TestCompactThroughEngineSummarize wires the real Summarizer the agent uses
331-// onto a fake Genkit model, the same approach as internal/engine's tests: the
332-// request the model receives must carry no tools, and the text it returns must
333-// land in the summary message. The Engine is built the way testEngine does it
334-// there — the model reference is all Summarize reads from it.
335-func TestCompactThroughEngineSummarize(t *testing.T) {
336- g := genkit.Init(context.Background())
337- var sawTools int
338- genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
339- &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
340- func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
341- sawTools = len(r.Tools)
342- return &ai.ModelResponse{
343- Message: ai.NewModelMessage(ai.NewTextPart("## Goal\nfrom the fake model")),
344- FinishReason: ai.FinishReasonStop,
345- }, nil
346- })
347- e := &engine.Engine{G: g, Model: "dmr/" + config.Cfg.Model}
348-
349- msgs := history(turn("q1", 2, "x"), turn("q2", 1, "y"))
350- c := cfg(1)
351- res, err := Compact(context.Background(), msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) {
352- return e.Summarize(ctx, request, c.SummaryMaxTokens)
353- })
354- if err != nil {
355- t.Fatalf("Compact via engine.Summarize: %v", err)
356- }
357- if sawTools != 0 {
358- t.Errorf("the summary request declared %d tool(s), want none", sawTools)
359- }
360- if !strings.Contains(res.Messages[1].Text(), "from the fake model") {
361- t.Errorf("the model's text is not in the summary: %q", res.Messages[1].Text())
362- }
363- if err := Valid(res.Messages); err != nil {
364- t.Errorf("invalid history: %v", err)
365- }
366-}
367-
368326 // The notes of a summary come back without their wrapper line; both halves
369327 // of the pair are recognised, and nothing else is.
370328 func TestSummaryNotesAndPair(t *testing.T) {
@@ -3,9 +3,9 @@
3 // the next request is still a valid conversation — system prompt first, every3 // the next request is still a valid conversation — system prompt first, every
4 // tool response under the request that asked for it, the recent turns intact.4 // tool response under the request that asked for it, the recent turns intact.
5 //5 //
6-// No network and no model: the Summarizer is a function here. The last test6+// No network and no model: the Summarizer is a function here.
7-// goes through engine.Summarize with a fake Genkit model, so the wiring the7+// engine_summarize_test.go goes through engine.Summarize with a fake Genkit
8-// agent uses is exercised too.8+// model, so the wiring the agent uses is exercised too.
9 package compact9 package compact
10 10
11 import (11 import (
@@ -15,10 +15,8 @@ import (
15 "testing"15 "testing"
16 16
17 "mm/internal/config"17 "mm/internal/config"
18- "mm/internal/engine"
19 18
20 "github.com/firebase/genkit/go/ai"19 "github.com/firebase/genkit/go/ai"
21- "github.com/firebase/genkit/go/genkit"
22 )20 )
23 21
24 // --- fixtures ---------------------------------------------------------------22 // --- fixtures ---------------------------------------------------------------
@@ -325,46 +323,6 @@ func countSummaries(msgs []*ai.Message) int {
325 return n323 return n
326 }324 }
327 325
328-// --- through engine.Summarize -----------------------------------------------
329-
330-// TestCompactThroughEngineSummarize wires the real Summarizer the agent uses
331-// onto a fake Genkit model, the same approach as internal/engine's tests: the
332-// request the model receives must carry no tools, and the text it returns must
333-// land in the summary message. The Engine is built the way testEngine does it
334-// there — the model reference is all Summarize reads from it.
335-func TestCompactThroughEngineSummarize(t *testing.T) {
336- g := genkit.Init(context.Background())
337- var sawTools int
338- genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
339- &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
340- func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
341- sawTools = len(r.Tools)
342- return &ai.ModelResponse{
343- Message: ai.NewModelMessage(ai.NewTextPart("## Goal\nfrom the fake model")),
344- FinishReason: ai.FinishReasonStop,
345- }, nil
346- })
347- e := &engine.Engine{G: g, Model: "dmr/" + config.Cfg.Model}
348-
349- msgs := history(turn("q1", 2, "x"), turn("q2", 1, "y"))
350- c := cfg(1)
351- res, err := Compact(context.Background(), msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) {
352- return e.Summarize(ctx, request, c.SummaryMaxTokens)
353- })
354- if err != nil {
355- t.Fatalf("Compact via engine.Summarize: %v", err)
356- }
357- if sawTools != 0 {
358- t.Errorf("the summary request declared %d tool(s), want none", sawTools)
359- }
360- if !strings.Contains(res.Messages[1].Text(), "from the fake model") {
361- t.Errorf("the model's text is not in the summary: %q", res.Messages[1].Text())
362- }
363- if err := Valid(res.Messages); err != nil {
364- t.Errorf("invalid history: %v", err)
365- }
366-}
367-
368 // The notes of a summary come back without their wrapper line; both halves326 // The notes of a summary come back without their wrapper line; both halves
369 // of the pair are recognised, and nothing else is.327 // of the pair are recognised, and nothing else is.
370 func TestSummaryNotesAndPair(t *testing.T) {328 func TestSummaryNotesAndPair(t *testing.T) {
added internal/compact/engine_summarize_test.go +58 -0
new file mode 100644
@@ -0,0 +1,58 @@
1+// An external test package: engine imports compact (in-turn compression,
2+// ticket 251), so a test that imports engine cannot live inside compact.
3+package compact_test
4+
5+import (
6+ "context"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/compact"
11+ "mm/internal/config"
12+ "mm/internal/engine"
13+
14+ "github.com/firebase/genkit/go/ai"
15+ "github.com/firebase/genkit/go/genkit"
16+)
17+
18+// TestCompactThroughEngineSummarize wires the real Summarizer the agent uses
19+// onto a fake Genkit model, the same approach as internal/engine's tests: the
20+// request the model receives must carry no tools, and the text it returns must
21+// land in the summary message. The Engine is built the way testEngine does it
22+// there — the model reference is all Summarize reads from it.
23+func TestCompactThroughEngineSummarize(t *testing.T) {
24+ g := genkit.Init(context.Background())
25+ var sawTools int
26+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
27+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
28+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
29+ sawTools = len(r.Tools)
30+ return &ai.ModelResponse{
31+ Message: ai.NewModelMessage(ai.NewTextPart("## Goal\nfrom the fake model")),
32+ FinishReason: ai.FinishReasonStop,
33+ }, nil
34+ })
35+ e := &engine.Engine{G: g, Model: "dmr/" + config.Cfg.Model}
36+
37+ msgs := []*ai.Message{
38+ ai.NewSystemTextMessage("system"),
39+ ai.NewUserTextMessage("q1"), ai.NewModelTextMessage("a1"),
40+ ai.NewUserTextMessage("q2"), ai.NewModelTextMessage("a2"),
41+ }
42+ c := config.ContextConfig{Enabled: true, KeepLastTurns: 1, SummaryMaxTokens: 256}
43+ res, err := compact.Compact(context.Background(), msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) {
44+ return e.Summarize(ctx, request, c.SummaryMaxTokens)
45+ })
46+ if err != nil {
47+ t.Fatalf("Compact via engine.Summarize: %v", err)
48+ }
49+ if sawTools != 0 {
50+ t.Errorf("the summary request declared %d tool(s), want none", sawTools)
51+ }
52+ if !strings.Contains(res.Messages[1].Text(), "from the fake model") {
53+ t.Errorf("the model's text is not in the summary: %q", res.Messages[1].Text())
54+ }
55+ if err := compact.Valid(res.Messages); err != nil {
56+ t.Errorf("invalid history: %v", err)
57+ }
58+}
new file mode 100644
@@ -0,0 +1,58 @@
1+// An external test package: engine imports compact (in-turn compression,
2+// ticket 251), so a test that imports engine cannot live inside compact.
3+package compact_test
4+
5+import (
6+ "context"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/compact"
11+ "mm/internal/config"
12+ "mm/internal/engine"
13+
14+ "github.com/firebase/genkit/go/ai"
15+ "github.com/firebase/genkit/go/genkit"
16+)
17+
18+// TestCompactThroughEngineSummarize wires the real Summarizer the agent uses
19+// onto a fake Genkit model, the same approach as internal/engine's tests: the
20+// request the model receives must carry no tools, and the text it returns must
21+// land in the summary message. The Engine is built the way testEngine does it
22+// there — the model reference is all Summarize reads from it.
23+func TestCompactThroughEngineSummarize(t *testing.T) {
24+ g := genkit.Init(context.Background())
25+ var sawTools int
26+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
27+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
28+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
29+ sawTools = len(r.Tools)
30+ return &ai.ModelResponse{
31+ Message: ai.NewModelMessage(ai.NewTextPart("## Goal\nfrom the fake model")),
32+ FinishReason: ai.FinishReasonStop,
33+ }, nil
34+ })
35+ e := &engine.Engine{G: g, Model: "dmr/" + config.Cfg.Model}
36+
37+ msgs := []*ai.Message{
38+ ai.NewSystemTextMessage("system"),
39+ ai.NewUserTextMessage("q1"), ai.NewModelTextMessage("a1"),
40+ ai.NewUserTextMessage("q2"), ai.NewModelTextMessage("a2"),
41+ }
42+ c := config.ContextConfig{Enabled: true, KeepLastTurns: 1, SummaryMaxTokens: 256}
43+ res, err := compact.Compact(context.Background(), msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) {
44+ return e.Summarize(ctx, request, c.SummaryMaxTokens)
45+ })
46+ if err != nil {
47+ t.Fatalf("Compact via engine.Summarize: %v", err)
48+ }
49+ if sawTools != 0 {
50+ t.Errorf("the summary request declared %d tool(s), want none", sawTools)
51+ }
52+ if !strings.Contains(res.Messages[1].Text(), "from the fake model") {
53+ t.Errorf("the model's text is not in the summary: %q", res.Messages[1].Text())
54+ }
55+ if err := compact.Valid(res.Messages); err != nil {
56+ t.Errorf("invalid history: %v", err)
57+ }
58+}
added internal/compact/inturn.go +281 -0
new file mode 100644
@@ -0,0 +1,281 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "time"
8+
9+ "mm/internal/config"
10+
11+ "github.com/firebase/genkit/go/ai"
12+)
13+
14+// Compression INSIDE a turn (ticket 251, config context.compressInTurn).
15+//
16+// Between two questions, Compact summarises the old question turns. A long
17+// autonomous turn never reaches that point: observed with Inkling-2-Mini, one
18+// question → 77 messages, 38 tool calls, three whole Go files written, then
19+// "the request (65811 tokens) is larger than the server's window (65536)".
20+//
21+// So before each model call of a turn, when the history passes
22+// context.threshold of the window, the CURRENT turn is made smaller, in two
23+// steps, the second only when the first is not enough:
24+//
25+// 1. shrink: every tool exchange of the turn but the last KeepToolCalls
26+// loses its bulk — a tool result keeps its first line
27+// (`scene.go: created, 516 line(s)`), a long argument of a call (a whole
28+// file given to write_file) keeps its first line too; a note says what
29+// was dropped. The model can read a file again; it cannot get its window
30+// back.
31+// 2. summarise: the older exchanges of the turn are replaced by notes the
32+// model writes about them, appended to the turn's question — a user
33+// message, so the user/assistant alternation chat templates expect holds.
34+//
35+// The question, the last KeepToolCalls exchanges and everything before the
36+// turn are never touched; a tool call is never split from its result
37+// (Valid). On any failure the history is left as it was.
38+
39+// KeepToolCalls is the number of tool exchanges (a model message with its
40+// calls, then their results) left raw at the end of the turn: the work the
41+// model is doing right now.
42+const KeepToolCalls = 4
43+
44+// shrinkOver is the length past which a tool result or a call argument is
45+// shrunk; shorter ones are not worth a note.
46+const shrinkOver = 400
47+
48+// InTurnDecide says whether the turn must be made smaller before the next
49+// call: the larger of the measure and the estimate passes the threshold of
50+// a known window. It does not read context.enabled: a turn that grows past
51+// the window fails whatever the between-questions setting says.
52+func InTurnDecide(msgs []*ai.Message, measured, window int, cfg config.ContextConfig) bool {
53+ if !cfg.CompressInTurn || window <= 0 || cfg.Threshold <= 0 {
54+ return false
55+ }
56+ return max(Estimate(msgs), measured)*100 >= window*cfg.Threshold
57+}
58+
59+// InTurnResult is what CompactTurn did, for the one-line report.
60+type InTurnResult struct {
61+ Messages []*ai.Message
62+ Shrunk int // tool results and arguments shrunk
63+ Summarised int // messages replaced by the notes (0 = no summary)
64+ Before int // estimated tokens before
65+ After int
66+ Elapsed time.Duration
67+}
68+
69+// Report is the 🗜️ line:
70+//
71+// in-turn: shrank 12 tool call(s) and result(s), summarised 20 message(s) (61.2k → 18.4k tokens, 4.1s)
72+func (r InTurnResult) Report() string {
73+ var parts []string
74+ if r.Shrunk > 0 {
75+ parts = append(parts, fmt.Sprintf("shrank %d tool call(s) and result(s)", r.Shrunk))
76+ }
77+ if r.Summarised > 0 {
78+ parts = append(parts, fmt.Sprintf("summarised %d message(s)", r.Summarised))
79+ }
80+ return fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),
81+ Kilo(r.Before), Kilo(r.After), seconds(r.Elapsed))
82+}
83+
84+// CompactTurn makes the current turn of msgs smaller: shrink first, then,
85+// when the estimate still passes the threshold (window > 0), summarise. It
86+// returns ErrNothingToCompact when the turn has no exchange older than the
87+// kept ones. msgs itself is never modified.
88+func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config.ContextConfig, summarize Summarizer) (InTurnResult, error) {
89+ start := time.Now()
90+ r := InTurnResult{Before: Estimate(msgs)}
91+ q, cut := turnBounds(msgs)
92+ if q < 0 || cut <= q+1 {
93+ return InTurnResult{}, ErrNothingToCompact
94+ }
95+
96+ out := make([]*ai.Message, len(msgs))
97+ copy(out, msgs)
98+ for i := q + 1; i < cut; i++ {
99+ if m, n := shrink(out[i]); n > 0 {
100+ out[i], r.Shrunk = m, r.Shrunk+n
101+ }
102+ }
103+
104+ if window > 0 && Estimate(out)*100 >= window*cfg.Threshold && summarize != nil {
105+ older := out[q+1 : cut]
106+ // The question first: the note-taker knows the task, and the request
107+ // opens with a user message, as chat templates expect.
108+ prompt := turnPrompt
109+ if out[q].Metadata[metaKey] == "in-turn" {
110+ prompt += turnMergeLine
111+ }
112+ notes, err := summarize(ctx, Request(append([]*ai.Message{out[q]}, older...), prompt, false))
113+ if err == nil && strings.TrimSpace(notes) != "" {
114+ question := withNotes(out[q], notes, len(older))
115+ summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[cut:]...)
116+ if Valid(summed) == nil {
117+ out, r.Summarised = summed, len(older)
118+ }
119+ }
120+ }
121+ if r.Shrunk == 0 && r.Summarised == 0 {
122+ return InTurnResult{}, ErrNothingToCompact
123+ }
124+ if err := Valid(out); err != nil {
125+ return InTurnResult{}, fmt.Errorf("in-turn compression broke the history: %w", err)
126+ }
127+ r.Messages, r.After, r.Elapsed = out, Estimate(out), time.Since(start)
128+ return r, nil
129+}
130+
131+// turnBounds finds the current turn's question (the last user message that
132+// is not tool results) and the start of its kept tail: the model message of
133+// the KeepToolCalls-th last exchange. q is -1 when there is no question;
134+// cut <= q+1 when nothing is older than the tail.
135+func turnBounds(msgs []*ai.Message) (q, cut int) {
136+ q = -1
137+ for i := len(msgs) - 1; i >= 0; i-- {
138+ if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) {
139+ q = i
140+ break
141+ }
142+ }
143+ if q < 0 {
144+ return -1, 0
145+ }
146+ cut = len(msgs)
147+ seen := 0
148+ for i := len(msgs) - 1; i > q; i-- {
149+ if msgs[i].Role == ai.RoleModel && hasToolRequest(msgs[i]) {
150+ seen++
151+ cut = i
152+ if seen == KeepToolCalls {
153+ break
154+ }
155+ }
156+ }
157+ if seen < KeepToolCalls {
158+ return q, q + 1 // the whole turn is the tail
159+ }
160+ return q, cut
161+}
162+
163+func hasToolRequest(m *ai.Message) bool {
164+ for _, p := range m.Content {
165+ if p.IsToolRequest() {
166+ return true
167+ }
168+ }
169+ return false
170+}
171+
172+func hasToolResponse(m *ai.Message) bool {
173+ for _, p := range m.Content {
174+ if p.IsToolResponse() {
175+ return true
176+ }
177+ }
178+ return false
179+}
180+
181+// shrink returns a copy of m with its long tool results and call arguments
182+// cut to their first line, and how many it cut; m itself when none.
183+func shrink(m *ai.Message) (*ai.Message, int) {
184+ n := 0
185+ parts := make([]*ai.Part, len(m.Content))
186+ for i, p := range m.Content {
187+ parts[i] = p
188+ switch {
189+ case p.IsToolResponse() && p.ToolResponse != nil:
190+ text := jsonOf(p.ToolResponse.Output)
191+ if len(text) > shrinkOver {
192+ r := *p.ToolResponse
193+ r.Output = headLine(text)
194+ parts[i] = ai.NewToolResponsePart(&r)
195+ n++
196+ }
197+ case p.IsToolRequest() && p.ToolRequest != nil:
198+ in, ok := p.ToolRequest.Input.(map[string]any)
199+ if !ok {
200+ continue
201+ }
202+ var cut map[string]any
203+ for k, v := range in {
204+ s, isText := v.(string)
205+ if !isText || len(s) <= shrinkOver {
206+ continue
207+ }
208+ if cut == nil {
209+ cut = make(map[string]any, len(in))
210+ for k2, v2 := range in {
211+ cut[k2] = v2
212+ }
213+ }
214+ cut[k] = headLine(s)
215+ }
216+ if cut != nil {
217+ r := *p.ToolRequest
218+ r.Input = cut
219+ parts[i] = ai.NewToolRequestPart(&r)
220+ n++
221+ }
222+ }
223+ }
224+ if n == 0 {
225+ return m, 0
226+ }
227+ meta := map[string]any{metaKey: "shrunk"}
228+ for k, v := range m.Metadata {
229+ if k != metaKey {
230+ meta[k] = v
231+ }
232+ }
233+ return ai.NewMessage(m.Role, meta, parts...), n
234+}
235+
236+// headLine is a long text's first line (at most 200 characters) and a note
237+// saying what was dropped.
238+func headLine(s string) string {
239+ first, _, _ := strings.Cut(s, "\n")
240+ if len(first) > 200 {
241+ first = first[:200] + "…"
242+ }
243+ lines := strings.Count(s, "\n") + 1
244+ return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s))
245+}
246+
247+// turnPrompt asks for notes on the turn's older exchanges.
248+const turnPrompt = `Everything above, after the system message, is the first part of the work
249+an agent did on ONE task, through tool calls. Write notes the same agent will
250+use to continue that task without this part, in English, as short bullet
251+points: the files read, created or changed (exact paths, what changed), the
252+commands run and the results that still matter (failing tests, exact errors),
253+the decisions taken, and what remained to do at that point. Do not quote file
254+contents. Do not invent anything. At most 25 lines.`
255+
256+// turnMergeLine is added when the question already carries notes of an
257+// earlier compression of the same turn.
258+const turnMergeLine = "\n\nThe question above already ends with notes on an earlier part of the work: merge them into your notes, do not repeat them as-is."
259+
260+// withNotes is the turn's question with the notes on its older exchanges
261+// appended: still the user's message, so the next message (the model's
262+// kept tool call) keeps the alternation.
263+func withNotes(question *ai.Message, notes string, n int) *ai.Message {
264+ text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. Treat them as notes, not as observations: re-read a file or re-run a command before relying on it.]\n\n%s",
265+ n, strings.TrimSpace(notes))
266+ // The question's own parts (text, an image…) stay as they were; notes
267+ // of an earlier compression — its last part — are replaced, the new
268+ // notes having merged them.
269+ own := question.Content
270+ if question.Metadata[metaKey] == "in-turn" && len(own) > 1 {
271+ own = own[:len(own)-1]
272+ }
273+ parts := append(append([]*ai.Part{}, own...), ai.NewTextPart("\n\n"+text))
274+ meta := map[string]any{metaKey: "in-turn"}
275+ for k, v := range question.Metadata {
276+ if k != metaKey {
277+ meta[k] = v
278+ }
279+ }
280+ return ai.NewMessage(ai.RoleUser, meta, parts...)
281+}
new file mode 100644
@@ -0,0 +1,281 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "time"
8+
9+ "mm/internal/config"
10+
11+ "github.com/firebase/genkit/go/ai"
12+)
13+
14+// Compression INSIDE a turn (ticket 251, config context.compressInTurn).
15+//
16+// Between two questions, Compact summarises the old question turns. A long
17+// autonomous turn never reaches that point: observed with Inkling-2-Mini, one
18+// question → 77 messages, 38 tool calls, three whole Go files written, then
19+// "the request (65811 tokens) is larger than the server's window (65536)".
20+//
21+// So before each model call of a turn, when the history passes
22+// context.threshold of the window, the CURRENT turn is made smaller, in two
23+// steps, the second only when the first is not enough:
24+//
25+// 1. shrink: every tool exchange of the turn but the last KeepToolCalls
26+// loses its bulk — a tool result keeps its first line
27+// (`scene.go: created, 516 line(s)`), a long argument of a call (a whole
28+// file given to write_file) keeps its first line too; a note says what
29+// was dropped. The model can read a file again; it cannot get its window
30+// back.
31+// 2. summarise: the older exchanges of the turn are replaced by notes the
32+// model writes about them, appended to the turn's question — a user
33+// message, so the user/assistant alternation chat templates expect holds.
34+//
35+// The question, the last KeepToolCalls exchanges and everything before the
36+// turn are never touched; a tool call is never split from its result
37+// (Valid). On any failure the history is left as it was.
38+
39+// KeepToolCalls is the number of tool exchanges (a model message with its
40+// calls, then their results) left raw at the end of the turn: the work the
41+// model is doing right now.
42+const KeepToolCalls = 4
43+
44+// shrinkOver is the length past which a tool result or a call argument is
45+// shrunk; shorter ones are not worth a note.
46+const shrinkOver = 400
47+
48+// InTurnDecide says whether the turn must be made smaller before the next
49+// call: the larger of the measure and the estimate passes the threshold of
50+// a known window. It does not read context.enabled: a turn that grows past
51+// the window fails whatever the between-questions setting says.
52+func InTurnDecide(msgs []*ai.Message, measured, window int, cfg config.ContextConfig) bool {
53+ if !cfg.CompressInTurn || window <= 0 || cfg.Threshold <= 0 {
54+ return false
55+ }
56+ return max(Estimate(msgs), measured)*100 >= window*cfg.Threshold
57+}
58+
59+// InTurnResult is what CompactTurn did, for the one-line report.
60+type InTurnResult struct {
61+ Messages []*ai.Message
62+ Shrunk int // tool results and arguments shrunk
63+ Summarised int // messages replaced by the notes (0 = no summary)
64+ Before int // estimated tokens before
65+ After int
66+ Elapsed time.Duration
67+}
68+
69+// Report is the 🗜️ line:
70+//
71+// in-turn: shrank 12 tool call(s) and result(s), summarised 20 message(s) (61.2k → 18.4k tokens, 4.1s)
72+func (r InTurnResult) Report() string {
73+ var parts []string
74+ if r.Shrunk > 0 {
75+ parts = append(parts, fmt.Sprintf("shrank %d tool call(s) and result(s)", r.Shrunk))
76+ }
77+ if r.Summarised > 0 {
78+ parts = append(parts, fmt.Sprintf("summarised %d message(s)", r.Summarised))
79+ }
80+ return fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),
81+ Kilo(r.Before), Kilo(r.After), seconds(r.Elapsed))
82+}
83+
84+// CompactTurn makes the current turn of msgs smaller: shrink first, then,
85+// when the estimate still passes the threshold (window > 0), summarise. It
86+// returns ErrNothingToCompact when the turn has no exchange older than the
87+// kept ones. msgs itself is never modified.
88+func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config.ContextConfig, summarize Summarizer) (InTurnResult, error) {
89+ start := time.Now()
90+ r := InTurnResult{Before: Estimate(msgs)}
91+ q, cut := turnBounds(msgs)
92+ if q < 0 || cut <= q+1 {
93+ return InTurnResult{}, ErrNothingToCompact
94+ }
95+
96+ out := make([]*ai.Message, len(msgs))
97+ copy(out, msgs)
98+ for i := q + 1; i < cut; i++ {
99+ if m, n := shrink(out[i]); n > 0 {
100+ out[i], r.Shrunk = m, r.Shrunk+n
101+ }
102+ }
103+
104+ if window > 0 && Estimate(out)*100 >= window*cfg.Threshold && summarize != nil {
105+ older := out[q+1 : cut]
106+ // The question first: the note-taker knows the task, and the request
107+ // opens with a user message, as chat templates expect.
108+ prompt := turnPrompt
109+ if out[q].Metadata[metaKey] == "in-turn" {
110+ prompt += turnMergeLine
111+ }
112+ notes, err := summarize(ctx, Request(append([]*ai.Message{out[q]}, older...), prompt, false))
113+ if err == nil && strings.TrimSpace(notes) != "" {
114+ question := withNotes(out[q], notes, len(older))
115+ summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[cut:]...)
116+ if Valid(summed) == nil {
117+ out, r.Summarised = summed, len(older)
118+ }
119+ }
120+ }
121+ if r.Shrunk == 0 && r.Summarised == 0 {
122+ return InTurnResult{}, ErrNothingToCompact
123+ }
124+ if err := Valid(out); err != nil {
125+ return InTurnResult{}, fmt.Errorf("in-turn compression broke the history: %w", err)
126+ }
127+ r.Messages, r.After, r.Elapsed = out, Estimate(out), time.Since(start)
128+ return r, nil
129+}
130+
131+// turnBounds finds the current turn's question (the last user message that
132+// is not tool results) and the start of its kept tail: the model message of
133+// the KeepToolCalls-th last exchange. q is -1 when there is no question;
134+// cut <= q+1 when nothing is older than the tail.
135+func turnBounds(msgs []*ai.Message) (q, cut int) {
136+ q = -1
137+ for i := len(msgs) - 1; i >= 0; i-- {
138+ if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) {
139+ q = i
140+ break
141+ }
142+ }
143+ if q < 0 {
144+ return -1, 0
145+ }
146+ cut = len(msgs)
147+ seen := 0
148+ for i := len(msgs) - 1; i > q; i-- {
149+ if msgs[i].Role == ai.RoleModel && hasToolRequest(msgs[i]) {
150+ seen++
151+ cut = i
152+ if seen == KeepToolCalls {
153+ break
154+ }
155+ }
156+ }
157+ if seen < KeepToolCalls {
158+ return q, q + 1 // the whole turn is the tail
159+ }
160+ return q, cut
161+}
162+
163+func hasToolRequest(m *ai.Message) bool {
164+ for _, p := range m.Content {
165+ if p.IsToolRequest() {
166+ return true
167+ }
168+ }
169+ return false
170+}
171+
172+func hasToolResponse(m *ai.Message) bool {
173+ for _, p := range m.Content {
174+ if p.IsToolResponse() {
175+ return true
176+ }
177+ }
178+ return false
179+}
180+
181+// shrink returns a copy of m with its long tool results and call arguments
182+// cut to their first line, and how many it cut; m itself when none.
183+func shrink(m *ai.Message) (*ai.Message, int) {
184+ n := 0
185+ parts := make([]*ai.Part, len(m.Content))
186+ for i, p := range m.Content {
187+ parts[i] = p
188+ switch {
189+ case p.IsToolResponse() && p.ToolResponse != nil:
190+ text := jsonOf(p.ToolResponse.Output)
191+ if len(text) > shrinkOver {
192+ r := *p.ToolResponse
193+ r.Output = headLine(text)
194+ parts[i] = ai.NewToolResponsePart(&r)
195+ n++
196+ }
197+ case p.IsToolRequest() && p.ToolRequest != nil:
198+ in, ok := p.ToolRequest.Input.(map[string]any)
199+ if !ok {
200+ continue
201+ }
202+ var cut map[string]any
203+ for k, v := range in {
204+ s, isText := v.(string)
205+ if !isText || len(s) <= shrinkOver {
206+ continue
207+ }
208+ if cut == nil {
209+ cut = make(map[string]any, len(in))
210+ for k2, v2 := range in {
211+ cut[k2] = v2
212+ }
213+ }
214+ cut[k] = headLine(s)
215+ }
216+ if cut != nil {
217+ r := *p.ToolRequest
218+ r.Input = cut
219+ parts[i] = ai.NewToolRequestPart(&r)
220+ n++
221+ }
222+ }
223+ }
224+ if n == 0 {
225+ return m, 0
226+ }
227+ meta := map[string]any{metaKey: "shrunk"}
228+ for k, v := range m.Metadata {
229+ if k != metaKey {
230+ meta[k] = v
231+ }
232+ }
233+ return ai.NewMessage(m.Role, meta, parts...), n
234+}
235+
236+// headLine is a long text's first line (at most 200 characters) and a note
237+// saying what was dropped.
238+func headLine(s string) string {
239+ first, _, _ := strings.Cut(s, "\n")
240+ if len(first) > 200 {
241+ first = first[:200] + "…"
242+ }
243+ lines := strings.Count(s, "\n") + 1
244+ return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s))
245+}
246+
247+// turnPrompt asks for notes on the turn's older exchanges.
248+const turnPrompt = `Everything above, after the system message, is the first part of the work
249+an agent did on ONE task, through tool calls. Write notes the same agent will
250+use to continue that task without this part, in English, as short bullet
251+points: the files read, created or changed (exact paths, what changed), the
252+commands run and the results that still matter (failing tests, exact errors),
253+the decisions taken, and what remained to do at that point. Do not quote file
254+contents. Do not invent anything. At most 25 lines.`
255+
256+// turnMergeLine is added when the question already carries notes of an
257+// earlier compression of the same turn.
258+const turnMergeLine = "\n\nThe question above already ends with notes on an earlier part of the work: merge them into your notes, do not repeat them as-is."
259+
260+// withNotes is the turn's question with the notes on its older exchanges
261+// appended: still the user's message, so the next message (the model's
262+// kept tool call) keeps the alternation.
263+func withNotes(question *ai.Message, notes string, n int) *ai.Message {
264+ text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. Treat them as notes, not as observations: re-read a file or re-run a command before relying on it.]\n\n%s",
265+ n, strings.TrimSpace(notes))
266+ // The question's own parts (text, an image…) stay as they were; notes
267+ // of an earlier compression — its last part — are replaced, the new
268+ // notes having merged them.
269+ own := question.Content
270+ if question.Metadata[metaKey] == "in-turn" && len(own) > 1 {
271+ own = own[:len(own)-1]
272+ }
273+ parts := append(append([]*ai.Part{}, own...), ai.NewTextPart("\n\n"+text))
274+ meta := map[string]any{metaKey: "in-turn"}
275+ for k, v := range question.Metadata {
276+ if k != metaKey {
277+ meta[k] = v
278+ }
279+ }
280+ return ai.NewMessage(ai.RoleUser, meta, parts...)
281+}
added internal/compact/inturn_test.go +147 -0
new file mode 100644
@@ -0,0 +1,147 @@
1+package compact
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+)
14+
15+// longTurn is a history whose last turn is one question and n tool
16+// exchanges: write_file with a whole file, then bash with a long output.
17+func longTurn(n int) []*ai.Message {
18+ big := strings.Repeat("line of output\n", 200)
19+ msgs := []*ai.Message{
20+ ai.NewSystemTextMessage("system"),
21+ ai.NewUserTextMessage("earlier question"), ai.NewModelTextMessage("earlier answer"),
22+ ai.NewUserTextMessage("build the game"),
23+ }
24+ for i := range n {
25+ ref := fmt.Sprintf("c%d", i)
26+ msgs = append(msgs,
27+ ai.NewMessage(ai.RoleModel, nil, ai.NewToolRequestPart(&ai.ToolRequest{Name: "write_file", Ref: ref,
28+ Input: map[string]any{"path": fmt.Sprintf("f%d.go", i), "content": "package main\n" + big}})),
29+ ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "write_file", Ref: ref,
30+ Output: fmt.Sprintf("f%d.go: created, 201 line(s)\n%s", i, big)})),
31+ )
32+ }
33+ return msgs
34+}
35+
36+func inTurnCfg() config.ContextConfig {
37+ return config.ContextConfig{CompressInTurn: true, Threshold: 75, SummaryMaxTokens: 512}
38+}
39+
40+func TestInTurnDecide(t *testing.T) {
41+ msgs := longTurn(8)
42+ tokens := Estimate(msgs)
43+ c := inTurnCfg()
44+ if !InTurnDecide(msgs, 0, tokens, c) || InTurnDecide(msgs, 0, tokens*2, c) {
45+ t.Error("threshold: want compress at 100 %, not at 50 %")
46+ }
47+ if !InTurnDecide(msgs, tokens*2, tokens*2, c) {
48+ t.Error("the server's measure, larger than the estimate, must count")
49+ }
50+ if InTurnDecide(msgs, 0, 0, c) {
51+ t.Error("unknown window: must not decide")
52+ }
53+ c.CompressInTurn = false
54+ if InTurnDecide(msgs, 0, tokens, c) {
55+ t.Error("compressInTurn false: must not decide")
56+ }
57+}
58+
59+// Shrinking is enough: the older exchanges keep their first lines, the last
60+// KeepToolCalls are untouched, no summary is asked, nothing is orphaned.
61+func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
62+ msgs := longTurn(8)
63+ before := Estimate(msgs)
64+ called := false
65+ r, err := CompactTurn(context.Background(), msgs, before*10, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
66+ called = true
67+ return "notes", nil
68+ })
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ if called || r.Summarised != 0 {
73+ t.Error("a summary was asked although shrinking was enough")
74+ }
75+ if r.Shrunk != 8 { // 4 older exchanges: a call and a result each
76+ t.Errorf("shrunk %d, want 8", r.Shrunk)
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+ // Half the exchanges (the older half) shrunk to almost nothing.
82+ if r.After*10 > before*6 {
83+ t.Errorf("%d → %d tokens: the older half was not shrunk", before, r.After)
84+ }
85+ out := r.Messages[5].Content[0].ToolResponse.Output.(string)
86+ if !strings.HasPrefix(out, "f0.go: created, 201 line(s)\n[mm: the rest") {
87+ t.Errorf("shrunk result: %q", out[:80])
88+ }
89+ if in := r.Messages[4].Content[0].ToolRequest.Input.(map[string]any); in["path"] != "f0.go" || !strings.HasPrefix(in["content"].(string), "package main\n[mm:") {
90+ t.Errorf("shrunk call: %v", in)
91+ }
92+ for i := len(msgs) - 2*KeepToolCalls; i < len(msgs); i++ {
93+ if r.Messages[i] != msgs[i] {
94+ t.Errorf("message %d of the kept tail changed", i)
95+ }
96+ }
97+ if strings.Contains(msgs[5].Content[0].ToolResponse.Output.(string), "[mm:") {
98+ t.Error("the caller's history was modified")
99+ }
100+}
101+
102+// Shrinking is not enough: the older exchanges become notes appended to the
103+// question; the note-taker sees the question first.
104+func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
105+ msgs := longTurn(10)
106+ var asked []*ai.Message
107+ r, err := CompactTurn(context.Background(), msgs, 100, inTurnCfg(), func(_ context.Context, req []*ai.Message) (string, error) {
108+ asked = req
109+ return "- wrote f0.go … f5.go", nil
110+ })
111+ if err != nil {
112+ t.Fatal(err)
113+ }
114+ if r.Summarised != 12 { // 6 older exchanges
115+ t.Errorf("summarised %d messages, want 12", r.Summarised)
116+ }
117+ if asked[1].Text() != "build the game" {
118+ t.Errorf("the summary request starts with %q, want the question", asked[1].Text())
119+ }
120+ if err := Valid(r.Messages); err != nil {
121+ t.Fatal(err)
122+ }
123+ q := r.Messages[3]
124+ if q.Role != ai.RoleUser || !strings.Contains(q.Text(), "build the game") || !strings.Contains(q.Text(), "- wrote f0.go") {
125+ t.Errorf("question: %q", q.Text())
126+ }
127+ if len(r.Messages) != 4+2*KeepToolCalls || r.Messages[4].Role != ai.RoleModel {
128+ t.Errorf("%d messages, want the head, the question and %d exchanges", len(r.Messages), KeepToolCalls)
129+ }
130+ if !strings.Contains(r.Report(), "summarised 12 message(s)") {
131+ t.Errorf("report %q", r.Report())
132+ }
133+}
134+
135+// A failed summary keeps what shrinking did; a short turn has nothing older
136+// than its kept tail.
137+func TestCompactTurnFallbacks(t *testing.T) {
138+ r, err := CompactTurn(context.Background(), longTurn(10), 100, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
139+ return "", errors.New("server down")
140+ })
141+ if err != nil || r.Summarised != 0 || r.Shrunk == 0 || Valid(r.Messages) != nil {
142+ t.Errorf("failed summary: %+v, %v — want the shrunk history", r, err)
143+ }
144+ if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), 100, inTurnCfg(), nil); !errors.Is(err, ErrNothingToCompact) {
145+ t.Errorf("short turn: %v, want ErrNothingToCompact", err)
146+ }
147+}
new file mode 100644
@@ -0,0 +1,147 @@
1+package compact
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+)
14+
15+// longTurn is a history whose last turn is one question and n tool
16+// exchanges: write_file with a whole file, then bash with a long output.
17+func longTurn(n int) []*ai.Message {
18+ big := strings.Repeat("line of output\n", 200)
19+ msgs := []*ai.Message{
20+ ai.NewSystemTextMessage("system"),
21+ ai.NewUserTextMessage("earlier question"), ai.NewModelTextMessage("earlier answer"),
22+ ai.NewUserTextMessage("build the game"),
23+ }
24+ for i := range n {
25+ ref := fmt.Sprintf("c%d", i)
26+ msgs = append(msgs,
27+ ai.NewMessage(ai.RoleModel, nil, ai.NewToolRequestPart(&ai.ToolRequest{Name: "write_file", Ref: ref,
28+ Input: map[string]any{"path": fmt.Sprintf("f%d.go", i), "content": "package main\n" + big}})),
29+ ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "write_file", Ref: ref,
30+ Output: fmt.Sprintf("f%d.go: created, 201 line(s)\n%s", i, big)})),
31+ )
32+ }
33+ return msgs
34+}
35+
36+func inTurnCfg() config.ContextConfig {
37+ return config.ContextConfig{CompressInTurn: true, Threshold: 75, SummaryMaxTokens: 512}
38+}
39+
40+func TestInTurnDecide(t *testing.T) {
41+ msgs := longTurn(8)
42+ tokens := Estimate(msgs)
43+ c := inTurnCfg()
44+ if !InTurnDecide(msgs, 0, tokens, c) || InTurnDecide(msgs, 0, tokens*2, c) {
45+ t.Error("threshold: want compress at 100 %, not at 50 %")
46+ }
47+ if !InTurnDecide(msgs, tokens*2, tokens*2, c) {
48+ t.Error("the server's measure, larger than the estimate, must count")
49+ }
50+ if InTurnDecide(msgs, 0, 0, c) {
51+ t.Error("unknown window: must not decide")
52+ }
53+ c.CompressInTurn = false
54+ if InTurnDecide(msgs, 0, tokens, c) {
55+ t.Error("compressInTurn false: must not decide")
56+ }
57+}
58+
59+// Shrinking is enough: the older exchanges keep their first lines, the last
60+// KeepToolCalls are untouched, no summary is asked, nothing is orphaned.
61+func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
62+ msgs := longTurn(8)
63+ before := Estimate(msgs)
64+ called := false
65+ r, err := CompactTurn(context.Background(), msgs, before*10, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
66+ called = true
67+ return "notes", nil
68+ })
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ if called || r.Summarised != 0 {
73+ t.Error("a summary was asked although shrinking was enough")
74+ }
75+ if r.Shrunk != 8 { // 4 older exchanges: a call and a result each
76+ t.Errorf("shrunk %d, want 8", r.Shrunk)
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+ // Half the exchanges (the older half) shrunk to almost nothing.
82+ if r.After*10 > before*6 {
83+ t.Errorf("%d → %d tokens: the older half was not shrunk", before, r.After)
84+ }
85+ out := r.Messages[5].Content[0].ToolResponse.Output.(string)
86+ if !strings.HasPrefix(out, "f0.go: created, 201 line(s)\n[mm: the rest") {
87+ t.Errorf("shrunk result: %q", out[:80])
88+ }
89+ if in := r.Messages[4].Content[0].ToolRequest.Input.(map[string]any); in["path"] != "f0.go" || !strings.HasPrefix(in["content"].(string), "package main\n[mm:") {
90+ t.Errorf("shrunk call: %v", in)
91+ }
92+ for i := len(msgs) - 2*KeepToolCalls; i < len(msgs); i++ {
93+ if r.Messages[i] != msgs[i] {
94+ t.Errorf("message %d of the kept tail changed", i)
95+ }
96+ }
97+ if strings.Contains(msgs[5].Content[0].ToolResponse.Output.(string), "[mm:") {
98+ t.Error("the caller's history was modified")
99+ }
100+}
101+
102+// Shrinking is not enough: the older exchanges become notes appended to the
103+// question; the note-taker sees the question first.
104+func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
105+ msgs := longTurn(10)
106+ var asked []*ai.Message
107+ r, err := CompactTurn(context.Background(), msgs, 100, inTurnCfg(), func(_ context.Context, req []*ai.Message) (string, error) {
108+ asked = req
109+ return "- wrote f0.go … f5.go", nil
110+ })
111+ if err != nil {
112+ t.Fatal(err)
113+ }
114+ if r.Summarised != 12 { // 6 older exchanges
115+ t.Errorf("summarised %d messages, want 12", r.Summarised)
116+ }
117+ if asked[1].Text() != "build the game" {
118+ t.Errorf("the summary request starts with %q, want the question", asked[1].Text())
119+ }
120+ if err := Valid(r.Messages); err != nil {
121+ t.Fatal(err)
122+ }
123+ q := r.Messages[3]
124+ if q.Role != ai.RoleUser || !strings.Contains(q.Text(), "build the game") || !strings.Contains(q.Text(), "- wrote f0.go") {
125+ t.Errorf("question: %q", q.Text())
126+ }
127+ if len(r.Messages) != 4+2*KeepToolCalls || r.Messages[4].Role != ai.RoleModel {
128+ t.Errorf("%d messages, want the head, the question and %d exchanges", len(r.Messages), KeepToolCalls)
129+ }
130+ if !strings.Contains(r.Report(), "summarised 12 message(s)") {
131+ t.Errorf("report %q", r.Report())
132+ }
133+}
134+
135+// A failed summary keeps what shrinking did; a short turn has nothing older
136+// than its kept tail.
137+func TestCompactTurnFallbacks(t *testing.T) {
138+ r, err := CompactTurn(context.Background(), longTurn(10), 100, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
139+ return "", errors.New("server down")
140+ })
141+ if err != nil || r.Summarised != 0 || r.Shrunk == 0 || Valid(r.Messages) != nil {
142+ t.Errorf("failed summary: %+v, %v — want the shrunk history", r, err)
143+ }
144+ if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), 100, inTurnCfg(), nil); !errors.Is(err, ErrNothingToCompact) {
145+ t.Errorf("short turn: %v, want ErrNothingToCompact", err)
146+ }
147+}
modified internal/config/config.go +10 -1
@@ -807,6 +807,14 @@ type ContextConfig struct {
807807
808808 // ShowStats: print the one-line 🗜️ report after each compression.
809809 ShowStats bool `yaml:"showStats"`
810+
811+ // CompressInTurn (ticket 251): before each model call of a turn, when the
812+ // history passes Threshold of a known window, shrink the turn's older
813+ // tool results (first line kept), then, if that is not enough, summarise
814+ // its older tool exchanges into notes appended to the question. The last
815+ // compact.KeepToolCalls exchanges stay raw. On by default; independent of
816+ // Enabled — a turn that outgrows the window fails either way.
817+ CompressInTurn bool `yaml:"compressInTurn"`
810818 }
811819
812820 // The values of toolFormat.
@@ -922,7 +930,8 @@ which ones you left running.`,
922930 },
923931 Yolo: true,
924932 Context: ContextConfig{
925- Enabled: false,
933+ Enabled: false,
934+ CompressInTurn: true,
926935 // 75 % leaves a quarter of the window for the next question, the tool
927936 // outputs of its turns and the answer: one `bash` output alone can be
928937 // maxOutput characters, about 4-5k tokens.
@@ -807,6 +807,14 @@ type ContextConfig struct {
807 807
808 // ShowStats: print the one-line 🗜️ report after each compression.808 // ShowStats: print the one-line 🗜️ report after each compression.
809 ShowStats bool `yaml:"showStats"`809 ShowStats bool `yaml:"showStats"`
810+
811+ // CompressInTurn (ticket 251): before each model call of a turn, when the
812+ // history passes Threshold of a known window, shrink the turn's older
813+ // tool results (first line kept), then, if that is not enough, summarise
814+ // its older tool exchanges into notes appended to the question. The last
815+ // compact.KeepToolCalls exchanges stay raw. On by default; independent of
816+ // Enabled — a turn that outgrows the window fails either way.
817+ CompressInTurn bool `yaml:"compressInTurn"`
810 }818 }
811 819
812 // The values of toolFormat.820 // The values of toolFormat.
@@ -922,7 +930,8 @@ which ones you left running.`,
922 },930 },
923 Yolo: true,931 Yolo: true,
924 Context: ContextConfig{932 Context: ContextConfig{
925- Enabled: false,933+ Enabled: false,
934+ CompressInTurn: true,
926 // 75 % leaves a quarter of the window for the next question, the tool935 // 75 % leaves a quarter of the window for the next question, the tool
927 // outputs of its turns and the answer: one `bash` output alone can be936 // outputs of its turns and the answer: one `bash` output alone can be
928 // maxOutput characters, about 4-5k tokens.937 // maxOutput characters, about 4-5k tokens.
modified internal/engine/engine.go +11 -0
@@ -51,6 +51,10 @@ type Engine struct {
5151 // the exact figure the compression trigger prefers over its estimate.
5252 lastInput atomic.Int64
5353
54+ // inTurnProbed: the in-turn compression asked the server for its window
55+ // once already (inturn.go) — never again in this process.
56+ inTurnProbed atomic.Bool
57+
5458 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by
5559 // hand, in a test — runs none.
5660 hooks *hooks.Runner
@@ -372,6 +376,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a
372376 // Same tools, same order, on every call: the server's prompt
373377 // cache depends on it (tooldefs.go, ticket 53).
374378 params.Request.Tools = stableTools(params.Request.Tools)
379+ // From the turn's second call on — tools have run — a history
380+ // past the threshold is made smaller first (inturn.go, ticket
381+ // 251). The wait counts as the call's: the summary is no beat.
382+ if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(messages) {
383+ pl.expect()
384+ e.compactInTurn(ctx, params)
385+ }
375386 full = slices.Clone(params.Request.Messages)
376387 // call runs ONE model call under its own context, which the
377388 // loop watch cancels when the stream repeats itself — the
@@ -51,6 +51,10 @@ type Engine struct {
51 // the exact figure the compression trigger prefers over its estimate.51 // the exact figure the compression trigger prefers over its estimate.
52 lastInput atomic.Int6452 lastInput atomic.Int64
53 53
54+ // inTurnProbed: the in-turn compression asked the server for its window
55+ // once already (inturn.go) — never again in this process.
56+ inTurnProbed atomic.Bool
57+
54 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by58 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by
55 // hand, in a test — runs none.59 // hand, in a test — runs none.
56 hooks *hooks.Runner60 hooks *hooks.Runner
@@ -372,6 +376,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a
372 // Same tools, same order, on every call: the server's prompt376 // Same tools, same order, on every call: the server's prompt
373 // cache depends on it (tooldefs.go, ticket 53).377 // cache depends on it (tooldefs.go, ticket 53).
374 params.Request.Tools = stableTools(params.Request.Tools)378 params.Request.Tools = stableTools(params.Request.Tools)
379+ // From the turn's second call on — tools have run — a history
380+ // past the threshold is made smaller first (inturn.go, ticket
381+ // 251). The wait counts as the call's: the summary is no beat.
382+ if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(messages) {
383+ pl.expect()
384+ e.compactInTurn(ctx, params)
385+ }
375 full = slices.Clone(params.Request.Messages)386 full = slices.Clone(params.Request.Messages)
376 // call runs ONE model call under its own context, which the387 // call runs ONE model call under its own context, which the
377 // loop watch cancels when the stream repeats itself — the388 // loop watch cancels when the stream repeats itself — the
added internal/engine/inturn.go +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+package engine
2+
3+import (
4+ "context"
5+ "errors"
6+
7+ "mm/internal/compact"
8+ "mm/internal/config"
9+ "mm/internal/spinner"
10+ "mm/internal/ui"
11+
12+ "github.com/firebase/genkit/go/ai"
13+)
14+
15+// compactInTurn makes the turn smaller before a model call when its history
16+// passed context.threshold (ticket 251, compact.CompactTurn): params'
17+// messages are replaced, so Genkit builds the next calls from the smaller
18+// history too, and the session keeps it. Every front end goes through here —
19+// the line mode, the window, -p, ACP. A failure leaves the history as it was:
20+// the call is sent, and the server says whether it fits.
21+func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
22+ cfg := config.Cfg.Context
23+ msgs := params.Request.Messages
24+ // -p shows no banner, so the start-up probe never ran: ask the server
25+ // now — once per process: a server that does not tell (dmr) must not
26+ // cost a probe before every tool call. No provider: a test engine.
27+ if e.ContextWindow == 0 && e.Provider != nil && !e.inTurnProbed.Swap(true) {
28+ e.EnsureContextWindow(ctx)
29+ }
30+ if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cfg) {
31+ return
32+ }
33+ spinner.Start("Compressing the turn")
34+ // A context of its own: the turn's values (its reasoning display, its
35+ // speed meter) must not see the summary request; the turn's end still
36+ // stops it.
37+ sumCtx, cancel := context.WithCancel(context.Background())
38+ defer cancel()
39+ stop := context.AfterFunc(ctx, cancel)
40+ defer stop()
41+ summarize := func(ctx context.Context, req []*ai.Message) (string, error) {
42+ return e.Summarize(ctx, req, max(cfg.SummaryMaxTokens, 512))
43+ }
44+ r, err := compact.CompactTurn(sumCtx, msgs, e.ContextWindow, cfg, summarize)
45+ switch {
46+ case errors.Is(err, compact.ErrNothingToCompact):
47+ return
48+ case err != nil:
49+ ui.Notice("🗜️ in-turn compression failed: " + err.Error())
50+ return
51+ }
52+ params.Request.Messages = r.Messages
53+ // The server's last count was of the longer history: forgotten, or the
54+ // next decision would compress again on a stale figure.
55+ e.lastInput.Store(0)
56+ spinner.Stop()
57+ if cfg.ShowStats {
58+ ui.Notice("🗜️ " + r.Report())
59+ }
60+}
new file mode 100644
@@ -0,0 +1,60 @@
1+package engine
2+
3+import (
4+ "context"
5+ "errors"
6+
7+ "mm/internal/compact"
8+ "mm/internal/config"
9+ "mm/internal/spinner"
10+ "mm/internal/ui"
11+
12+ "github.com/firebase/genkit/go/ai"
13+)
14+
15+// compactInTurn makes the turn smaller before a model call when its history
16+// passed context.threshold (ticket 251, compact.CompactTurn): params'
17+// messages are replaced, so Genkit builds the next calls from the smaller
18+// history too, and the session keeps it. Every front end goes through here —
19+// the line mode, the window, -p, ACP. A failure leaves the history as it was:
20+// the call is sent, and the server says whether it fits.
21+func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
22+ cfg := config.Cfg.Context
23+ msgs := params.Request.Messages
24+ // -p shows no banner, so the start-up probe never ran: ask the server
25+ // now — once per process: a server that does not tell (dmr) must not
26+ // cost a probe before every tool call. No provider: a test engine.
27+ if e.ContextWindow == 0 && e.Provider != nil && !e.inTurnProbed.Swap(true) {
28+ e.EnsureContextWindow(ctx)
29+ }
30+ if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cfg) {
31+ return
32+ }
33+ spinner.Start("Compressing the turn")
34+ // A context of its own: the turn's values (its reasoning display, its
35+ // speed meter) must not see the summary request; the turn's end still
36+ // stops it.
37+ sumCtx, cancel := context.WithCancel(context.Background())
38+ defer cancel()
39+ stop := context.AfterFunc(ctx, cancel)
40+ defer stop()
41+ summarize := func(ctx context.Context, req []*ai.Message) (string, error) {
42+ return e.Summarize(ctx, req, max(cfg.SummaryMaxTokens, 512))
43+ }
44+ r, err := compact.CompactTurn(sumCtx, msgs, e.ContextWindow, cfg, summarize)
45+ switch {
46+ case errors.Is(err, compact.ErrNothingToCompact):
47+ return
48+ case err != nil:
49+ ui.Notice("🗜️ in-turn compression failed: " + err.Error())
50+ return
51+ }
52+ params.Request.Messages = r.Messages
53+ // The server's last count was of the longer history: forgotten, or the
54+ // next decision would compress again on a stale figure.
55+ e.lastInput.Store(0)
56+ spinner.Stop()
57+ if cfg.ShowStats {
58+ ui.Notice("🗜️ " + r.Report())
59+ }
60+}
added internal/engine/inturn_test.go +98 -0
new file mode 100644
@@ -0,0 +1,98 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+ "github.com/firebase/genkit/go/genkit"
14+)
15+
16+// A long turn on a small window (ticket 251): the model keeps calling a tool
17+// whose output is large. Before each call past the threshold, the turn is
18+// made smaller — the requests the model receives stop growing, the summary
19+// request (no tools) is answered with notes, and the history handed back is
20+// still a valid conversation.
21+func TestGenerateCompressesInsideALongTurn(t *testing.T) {
22+ saved := config.Cfg
23+ t.Cleanup(func() { config.Cfg = saved })
24+ config.Cfg.Context.CompressInTurn = true
25+ config.Cfg.Context.Threshold = 75
26+ config.Cfg.MaxTurns = 20
27+
28+ const toolCalls = 12
29+ big := strings.Repeat("a line of the tool's output\n", 100) // ~800 tokens
30+ g := genkit.Init(context.Background())
31+ var sizes []int
32+ calls, summaries := 0, 0
33+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
34+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
35+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
36+ if len(r.Tools) == 0 { // the in-turn summary
37+ summaries++
38+ return modelTurn(ai.NewTextPart("- read the files f0 … f7")), nil
39+ }
40+ sizes = append(sizes, compact.Estimate(r.Messages))
41+ calls++
42+ if calls > toolCalls {
43+ return modelTurn(ai.NewTextPart("done")), nil
44+ }
45+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
46+ Input: map[string]any{"path": fmt.Sprintf("f%d", calls)}})), nil
47+ })
48+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
49+ Path string `json:"path"`
50+ }) (string, error) {
51+ return in.Path + ": 100 line(s)\n" + big, nil
52+ })
53+ e := testEngine(g)
54+ // Compress past 3000 tokens: the kept tail alone (4 exchanges, ~3.2k)
55+ // passes it, so shrinking is not enough and the notes are written.
56+ e.ContextWindow = 4000
57+
58+ _, full, err := e.Generate(context.Background(),
59+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
60+ []ai.ToolRef{ai.ToolName("cat")})
61+ if err != nil {
62+ t.Fatalf("Generate: %v", err)
63+ }
64+ for i, n := range sizes {
65+ if n > e.ContextWindow {
66+ t.Errorf("request %d: %d tokens, more than the %d-token window: %v", i+1, n, e.ContextWindow, sizes)
67+ }
68+ }
69+ if summaries == 0 {
70+ t.Errorf("no in-turn summary on a turn of %v tokens", sizes)
71+ }
72+ if err := compact.Valid(full); err != nil {
73+ t.Errorf("history: %v", err)
74+ }
75+ if !strings.Contains(full[1].Text(), "- read the files f0") {
76+ t.Errorf("the notes are not in the question: %q", full[1].Text())
77+ }
78+ // Compressed several times, the question holds ONE set of notes: each
79+ // summary merged the previous one.
80+ if summaries < 2 || strings.Count(full[1].Text(), "[mm: progress on this task") != 1 {
81+ t.Errorf("%d summaries, question:\n%s", summaries, full[1].Text())
82+ }
83+ if full[len(full)-1].Text() != "done" {
84+ t.Errorf("the turn did not end with the answer")
85+ }
86+
87+ // Off: the same turn grows past the window.
88+ config.Cfg.Context.CompressInTurn = false
89+ calls, sizes = 0, nil
90+ if _, _, err := e.Generate(context.Background(),
91+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
92+ []ai.ToolRef{ai.ToolName("cat")}); err != nil {
93+ t.Fatalf("Generate (off): %v", err)
94+ }
95+ if sizes[len(sizes)-1] <= e.ContextWindow {
96+ t.Errorf("compressInTurn false: last request %d tokens, expected the turn to outgrow the window", sizes[len(sizes)-1])
97+ }
98+}
new file mode 100644
@@ -0,0 +1,98 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+ "github.com/firebase/genkit/go/genkit"
14+)
15+
16+// A long turn on a small window (ticket 251): the model keeps calling a tool
17+// whose output is large. Before each call past the threshold, the turn is
18+// made smaller — the requests the model receives stop growing, the summary
19+// request (no tools) is answered with notes, and the history handed back is
20+// still a valid conversation.
21+func TestGenerateCompressesInsideALongTurn(t *testing.T) {
22+ saved := config.Cfg
23+ t.Cleanup(func() { config.Cfg = saved })
24+ config.Cfg.Context.CompressInTurn = true
25+ config.Cfg.Context.Threshold = 75
26+ config.Cfg.MaxTurns = 20
27+
28+ const toolCalls = 12
29+ big := strings.Repeat("a line of the tool's output\n", 100) // ~800 tokens
30+ g := genkit.Init(context.Background())
31+ var sizes []int
32+ calls, summaries := 0, 0
33+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
34+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
35+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
36+ if len(r.Tools) == 0 { // the in-turn summary
37+ summaries++
38+ return modelTurn(ai.NewTextPart("- read the files f0 … f7")), nil
39+ }
40+ sizes = append(sizes, compact.Estimate(r.Messages))
41+ calls++
42+ if calls > toolCalls {
43+ return modelTurn(ai.NewTextPart("done")), nil
44+ }
45+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
46+ Input: map[string]any{"path": fmt.Sprintf("f%d", calls)}})), nil
47+ })
48+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
49+ Path string `json:"path"`
50+ }) (string, error) {
51+ return in.Path + ": 100 line(s)\n" + big, nil
52+ })
53+ e := testEngine(g)
54+ // Compress past 3000 tokens: the kept tail alone (4 exchanges, ~3.2k)
55+ // passes it, so shrinking is not enough and the notes are written.
56+ e.ContextWindow = 4000
57+
58+ _, full, err := e.Generate(context.Background(),
59+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
60+ []ai.ToolRef{ai.ToolName("cat")})
61+ if err != nil {
62+ t.Fatalf("Generate: %v", err)
63+ }
64+ for i, n := range sizes {
65+ if n > e.ContextWindow {
66+ t.Errorf("request %d: %d tokens, more than the %d-token window: %v", i+1, n, e.ContextWindow, sizes)
67+ }
68+ }
69+ if summaries == 0 {
70+ t.Errorf("no in-turn summary on a turn of %v tokens", sizes)
71+ }
72+ if err := compact.Valid(full); err != nil {
73+ t.Errorf("history: %v", err)
74+ }
75+ if !strings.Contains(full[1].Text(), "- read the files f0") {
76+ t.Errorf("the notes are not in the question: %q", full[1].Text())
77+ }
78+ // Compressed several times, the question holds ONE set of notes: each
79+ // summary merged the previous one.
80+ if summaries < 2 || strings.Count(full[1].Text(), "[mm: progress on this task") != 1 {
81+ t.Errorf("%d summaries, question:\n%s", summaries, full[1].Text())
82+ }
83+ if full[len(full)-1].Text() != "done" {
84+ t.Errorf("the turn did not end with the answer")
85+ }
86+
87+ // Off: the same turn grows past the window.
88+ config.Cfg.Context.CompressInTurn = false
89+ calls, sizes = 0, nil
90+ if _, _, err := e.Generate(context.Background(),
91+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
92+ []ai.ToolRef{ai.ToolName("cat")}); err != nil {
93+ t.Fatalf("Generate (off): %v", err)
94+ }
95+ if sizes[len(sizes)-1] <= e.ContextWindow {
96+ t.Errorf("compressInTurn false: last request %d tokens, expected the turn to outgrow the window", sizes[len(sizes)-1])
97+ }
98+}