Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(core): a compaction request runs at the Session's thinking level (#700)

Yaowei Zheng742842d1d667
diff --git a/changelog/unreleased/2026-09-11-compaction-thinking-level.md b/changelog/unreleased/2026-09-11-compaction-thinking-level.md
new file mode 100644
index 00000000..a3612d0c
--- /dev/null
+++ b/changelog/unreleased/2026-09-11-compaction-thinking-level.md
@@ -0,0 +1,28 @@
+# A compaction request runs at the Session's thinking level
+
+- **Date:** 2026-09-11
+- **Type:** fix
+- **Scope:** `core`
+- **PR:** [#700](https://github.com/Prism-Shadow/penguin-harness/pull/700)
+
+[中文版](2026-09-11-compaction-thinking-level.zh.md)
+
+## Details
+
+- The thinking level is a per-request parameter, and every LLM request takes the level the
+ Session has pinned — the composer's picker, the CLI's `--thinking` / `/thinking`,
+ `session.thinkingLevel` on the SDK — falling back to the level the context was opened with
+ only when there is none. The compaction request was excepted and always took the fallback, so
+ a Session whose pin differed from its context's base ran its turns at one level and its
+ compaction at another. It now carries the pin like any other request.
+- The exception existed to hold the compaction request's prefix identical to the context it
+ summarises, keeping the provider's cache warm at the moment a miss costs most. It could only
+ ever fire once the user had moved the pin, though — and by then every turn since had gone out
+ at the new level and the cache had been rebuilt against it, leaving the compaction request as
+ the one request that differed.
+- What the split did cost is real: on a provider that reads the level as a thinking mode, it is
+ a mode changing mid-conversation. A turn produced under the quieter level carries no chain of
+ thought, and DeepSeek rejects a request whose current tool-call chain replays such a turn back
+ into thinking mode.
+- `specs/05-ARCHITECTURE.md` § "上下文轮换与运行配置" carried the exception; the design change is
+ [penguin-harness-design #149](https://github.com/Prism-Shadow/penguin-harness-design/pull/149).
diff --git a/changelog/unreleased/2026-09-11-compaction-thinking-level.zh.md b/changelog/unreleased/2026-09-11-compaction-thinking-level.zh.md
new file mode 100644
index 00000000..3fc2287e
--- /dev/null
+++ b/changelog/unreleased/2026-09-11-compaction-thinking-level.zh.md
@@ -0,0 +1,22 @@
+# 压缩请求按会话的思考等级发出
+
+- **Date:** 2026-09-11
+- **Type:** fix
+- **Scope:** `core`
+- **PR:** [#700](https://github.com/Prism-Shadow/penguin-harness/pull/700)
+
+[English](2026-09-11-compaction-thinking-level.md)
+
+## 细节
+
+- 思考等级是每请求参数,每次 LLM 请求都取 Session 钉住的等级——对话工具条的选择器、CLI 的
+ `--thinking` / `/thinking`、SDK 的 `session.thinkingLevel`——未钉住时才回退到上下文开启时读到的
+ 等级。压缩请求此前是个例外、恒取回退值,于是一个「钉住的等级与上下文基准档不同」的会话,普通轮跑在
+ 一个等级上、压缩轮跑在另一个等级上。现在它与其他请求一样携带该等级。
+- 这条例外的用意,是让压缩请求的前缀与它所压缩的那个上下文保持一致,从而在「缓存未命中代价最大」的
+ 时刻保住 provider 的缓存。但它只可能在用户已经改过等级时才触发——而那时其后的每一轮早已按新等级
+ 发出、缓存也已按新等级重建,反倒是按基准档发出的压缩请求成了唯一不一致的那次。
+- 这个分裂真正的代价是:在把等级读作思考模式的 provider 那里,它意味着思考模式在对话中途变动。在安静
+ 档下产出的那一轮不带思考内容,而 DeepSeek 会拒绝「当前工具调用链里回放了这样一轮」的请求。
+- `specs/05-ARCHITECTURE.md`「上下文轮换与运行配置」一节原本写有这条例外,配套设计改动见
+ [penguin-harness-design #149](https://github.com/Prism-Shadow/penguin-harness-design/pull/149)。
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 974b3028..bced2eab 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -481,10 +481,9 @@ export class ContextEngine {
/**
* The Session's current thinking level — the soft-limited runtime parameter as
* engine-owned state: `setThinkingLevel` (fed by the `Session.thinkingLevel` setter) moves it
- * mid-context, and every subsequent turn request carries it as the per-request override.
- * Undefined = no pin: the LLM object's construction default (the context's opening base)
- * applies. Compaction requests ignore it and keep the context's base — their prefix must
- * stay byte-identical at the moment the context is largest.
+ * mid-context, and every subsequent request carries it as the per-request override — a
+ * turn and a compaction alike. Undefined = no pin: the LLM object's construction default
+ * (the context's opening base) applies.
*/
private thinkingLevel?: ThinkingLevelName;
/** Most recent token_usage's request.total, i.e. the current context usage figure. */
@@ -567,7 +566,7 @@ export class ContextEngine {
}
}
- /** Moves the Session's thinking level mid-context (see the `thinkingLevel` field); applies from the next turn request. */
+ /** Moves the Session's thinking level mid-context (see the `thinkingLevel` field); applies from the next request, turn or compaction. */
setThinkingLevel(level: ThinkingLevelName): void {
this.thinkingLevel = level;
}
@@ -1812,9 +1811,19 @@ export class ContextEngine {
// written to the (old) Trace only, not pushed to the stream, keeping the compaction process
// invisible to Human.
await this.write(requestBegin());
+ // The Session's pinned thinking level, read live and carried exactly as a turn carries it
+ // (see the `thinkingLevel` field): the level is the soft-limited per-request parameter, so
+ // one Session never has two levels in flight at once. Were this request left on the level
+ // the context opened at while the turns around it run on the pin, a provider that reads the
+ // level as a thinking mode would see the mode change mid-conversation — and DeepSeek
+ // rejects a request whose current tool-call chain replays a turn that carries no chain of
+ // thought. The strict-tier prefix this request does hold identical to a turn's is its
+ // system prompt and toolset; the level is a request parameter, not part of either.
+ const level = this.thinkingLevel;
const gen = this.llm.streamGenerate({
newMessages: input,
...(signal ? { signal } : {}),
+ ...(level !== undefined ? { thinkingLevel: level } : {}),
});
let text = "";
const toolCalls: OmniMessage<ToolCallPayload>[] = [];
diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.ts
index 835f1fca..baf7c26c 100644
--- a/packages/core/test/compaction.test.ts
+++ b/packages/core/test/compaction.test.ts
@@ -57,6 +57,7 @@ import type {
GenerativeModelParameters,
LLMInterface,
LLMOutcome,
+ ThinkingLevelName,
} from "../src/interfaces/index.js";
import { ContextEngine, SUMMARY_RETRY_GUIDANCE } from "../src/engine/context-engine.js";
import { Session } from "../src/session.js";
@@ -77,6 +78,8 @@ interface ScriptedResponse {
/** Fake LLM that responds according to a script, recording each input it receives. */
class ScriptedLLM implements LLMInterface {
calls: OmniMessage[][] = [];
+ /** The per-request thinking level of each call, in the same order as `calls`. */
+ levels: (ThinkingLevelName | undefined)[] = [];
constructor(
private readonly responses: ScriptedResponse[],
readonly label = "llm",
@@ -86,6 +89,7 @@ class ScriptedLLM implements LLMInterface {
params: GenerativeModelParameters,
): AsyncGenerator<OmniMessage, LLMOutcome> {
this.calls.push(params.newMessages);
+ this.levels.push(params.thinkingLevel);
const next = this.responses.shift();
if (!next) {
return { status: "retryable", errorMessage: `${this.label}: no scripted response` };
@@ -279,6 +283,33 @@ describe("context compaction", () => {
).toBe(true);
});
+ it("carries no thinking level when the Session has no pin, on a turn or a compaction", async () => {
+ // The pinned half of the rule is engine.test.ts's "applies setThinkingLevel to every
+ // request of the Session". This is the other half: with no pin the request says nothing at
+ // all and the LLM object's construction default — the level the context was opened with —
+ // stands. The engine must not start inventing one for either kind of request.
+ const llm1 = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(150, 150)] },
+ { messages: [assistantText("[summary]the distilled summary[/summary]"), usage(160, 310)] },
+ ],
+ "llm1",
+ );
+ const llm2 = new ScriptedLLM([{ messages: [assistantText("answer two"), usage(20, 330)] }]);
+ const engine = new ContextEngine({
+ llm: llm1,
+ environment: fakeEnvironment,
+ trace: new Writer({ tracesDir: traces, sessionId: "sess_compact_nolevel" }),
+ sessionMeta: metaMessage,
+ compaction: settings(),
+ openNextContext: () => ({ llm: llm2 }),
+ });
+
+ await collect(engine.run([userText("task one")], { approve: allowAll }));
+
+ expect(llm1.levels).toEqual([undefined, undefined]);
+ });
+
it("the rotated Trace file opens with the meta the new context was opened with, and a later context without one keeps it", async () => {
// The composition layer re-assembles the system prompt for each context and hands the
// engine the session_meta recording it: that meta — not the Session's first — is what the
diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts
index 5a52c69c..0522b7da 100644
--- a/packages/core/test/engine.test.ts
+++ b/packages/core/test/engine.test.ts
@@ -965,7 +965,7 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {
});
describe("ContextEngine live thinking level (the soft-limited runtime parameter)", () => {
- it("applies setThinkingLevel to every turn request — reconnects included — while compaction requests keep the context default", async () => {
+ it("applies setThinkingLevel to every request of the Session — reconnects and the compaction request included", async () => {
const levels: (string | undefined)[] = [];
let calls = 0;
const llm: LLMInterface = {
@@ -979,8 +979,10 @@ describe("ContextEngine live thinking level (the soft-limited runtime parameter)
}
if (calls === 2) {
// Retry completes with usage above the compaction threshold → a Task-boundary
- // summarize compaction issues one more request (the engine's, not a turn): it
- // must NOT carry the live override — its prefix stays the context's own.
+ // summarize compaction issues one more request (the engine's, not a turn). It
+ // carries the live override like any other: a pin only ever differs from the
+ // context's base once the user has moved it, and by then the turns since have
+ // already gone out at the new level.
yield assistantText("recovered");
yield tokenUsage(emptyTokenCounts(), {
cache_read: 0,
@@ -1023,8 +1025,8 @@ describe("ContextEngine live thinking level (the soft-limited runtime parameter)
engine.setThinkingLevel("high");
await collectRun(engine, [userText("go")], allowAll);
expect(calls).toBe(3);
- // Turn attempt + reconnect retry carry the live level; the compaction request does not.
- expect(levels).toEqual(["high", "high", undefined]);
+ // Turn attempt, reconnect retry and the compaction request all carry the live level.
+ expect(levels).toEqual(["high", "high", "high"]);
// A re-pin between runs is picked up by the next request without any rotation.
engine.setThinkingLevel("low");
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index 73b4d8e6..32a9dc8f 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -198,7 +198,7 @@ An abandoned compaction is **made up later**, never patched over. Mid-Task the r
Compaction triggered **mid-Task** never preempts the tools: `runTurn` returns only once every tool call of the turn has completed, so the results are ready and paired before the checkpoint is even reached. They then ride the compaction request itself, ahead of the compaction Prompt, in their original call order — whatever a tool produced (a normal result, a `[tool error]`, a denial) is what the summary is written from. A tool that waits on approval or runs for minutes simply delays the compaction; no clock is running on it, because the compaction request has not been issued yet. Nothing synthetic is inserted to close the exchange.
-While the compaction request runs, its thinking and the summary it writes ride the output stream as ordinary `partial_thinking` and `partial_text` (or the complete `thinking` / `text`, for LLM implementations that stream nothing), positioned between the paired compaction events — no separate event type, and the compaction request's other raw messages stay Trace-only as before. The request runs at the thinking level its model context already has; nothing turns thinking on for it. The Web App renders the compaction row like a running work group, and expands exactly one of its two layers: the header's title doubles as its status — Compacting (or Clearing) while it runs, Compacted (or Cleared) once done, the work-group header's own Running/Done idiom — and carries the wall time (ticking while it runs, settled once done); **while the compaction runs the row is open and its sections are not** — **Thinking** (present only when the request produced any) and **Result**, each a closed row carrying its own label and its own wall time, so the reader can see that they are there and how long each is taking without the request's raw workings landing in the transcript. Once the compaction settles the row closes itself again, leaving the one-line summary. The chevron is there from the start of a summarize compaction, so the reader can open either section to watch the request work, or read the outcome afterwards. A history rebuild reads the same content back from the compaction span's recorded thinking and output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation, and the CLI prints none of it.
+While the compaction request runs, its thinking and the summary it writes ride the output stream as ordinary `partial_thinking` and `partial_text` (or the complete `thinking` / `text`, for LLM implementations that stream nothing), positioned between the paired compaction events — no separate event type, and the compaction request's other raw messages stay Trace-only as before. The request carries the Session's pinned thinking level, exactly as every other LLM request does; with no pin, the level the model context was opened with applies. The Web App renders the compaction row like a running work group, and expands exactly one of its two layers: the header's title doubles as its status — Compacting (or Clearing) while it runs, Compacted (or Cleared) once done, the work-group header's own Running/Done idiom — and carries the wall time (ticking while it runs, settled once done); **while the compaction runs the row is open and its sections are not** — **Thinking** (present only when the request produced any) and **Result**, each a closed row carrying its own label and its own wall time, so the reader can see that they are there and how long each is taking without the request's raw workings landing in the transcript. Once the compaction settles the row closes itself again, leaving the one-line summary. The chevron is there from the start of a summarize compaction, so the reader can open either section to watch the request work, or read the outcome afterwards. A history rebuild reads the same content back from the compaction span's recorded thinking and output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation, and the CLI prints none of it.
A compaction the user quit out of — the process died mid-request, leaving a `compaction_begin` with no matching end — is simply a **failed compaction**. When the session next loads, resume closes the span with a `failed` `compaction_end` before appending anything else and **discards the half-written summary**: nothing is reconstructed from it, the original context stands, and the standing threshold makes the compaction up at the next trigger. Closing the span is what keeps the conversation that follows visible — every reader treats messages between the paired events as compaction-internal — and the Web App drops the partial draft from the row rather than showing a truncated summary as if it had been adopted.
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index 17df70a0..90274da6 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -191,7 +191,7 @@ interface CompactionSettings {
任务中途触发的压缩绝不抢在工具前面:`runTurn` 要等本轮**全部**工具调用执行完毕才返回,因此到达压缩检查点时结果已经就绪、也已与 `tool_call` 配对。这些结果随后**随压缩请求本身**发出,排在压缩 Prompt 之前、保持原始调用顺序——工具产出什么(正常结果、`[tool error]`、被拒绝的回执),摘要就据此写成。需要审批或耗时数分钟的工具只是让压缩延后:压缩请求尚未发出,也就没有任何计时在跑。全程不插入任何合成消息去闭合该交换。
-压缩请求运行期间,它的思考与它写出的摘要以普通的 `partial_thinking` 与 `partial_text`(不产出流式消息的 LLM 实现则为完整 `thinking` / `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。压缩请求沿用模型上下文本来的思考等级,不会为它单独开启思考。Web App 的压缩行按运行中的工作分组呈现,且两层里只展开一层:组头的标题兼作状态——进行中为「压缩中」/「清空中」、结束后为「压缩完毕」/「清空完毕」,与工作分组组头的「运行中」/「运行完毕」同一写法——并带 wall time(进行中实时计时、结束后定格);**压缩运行期间该行展开、其中两节不展开**——「思考」(请求产出了思考时才有)与「压缩结果」各是一条折叠的行,各自带标签与自己的 wall time,读者能看到它们存在、各花了多久,而压缩请求的原始过程不会落进正文。压缩结束后该行自行收起,只留下一行摘要。summarize 压缩一开始就带上折叠箭头,读者展开任一节即可实时观看或事后阅读。历史重建从压缩区间已记录的思考与输出读回同一段内容,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文,CLI 也不打印其中任何内容。
+压缩请求运行期间,它的思考与它写出的摘要以普通的 `partial_thinking` 与 `partial_text`(不产出流式消息的 LLM 实现则为完整 `thinking` / `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。压缩请求与其他每一次 LLM 请求一样携带 Session 钉住的思考等级;未钉住时取该模型上下文开启时的等级。Web App 的压缩行按运行中的工作分组呈现,且两层里只展开一层:组头的标题兼作状态——进行中为「压缩中」/「清空中」、结束后为「压缩完毕」/「清空完毕」,与工作分组组头的「运行中」/「运行完毕」同一写法——并带 wall time(进行中实时计时、结束后定格);**压缩运行期间该行展开、其中两节不展开**——「思考」(请求产出了思考时才有)与「压缩结果」各是一条折叠的行,各自带标签与自己的 wall time,读者能看到它们存在、各花了多久,而压缩请求的原始过程不会落进正文。压缩结束后该行自行收起,只留下一行摘要。summarize 压缩一开始就带上折叠箭头,读者展开任一节即可实时观看或事后阅读。历史重建从压缩区间已记录的思考与输出读回同一段内容,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文,CLI 也不打印其中任何内容。
用户中途退出程序导致没写完的压缩(留下没有配对 end 的 `compaction_begin`),就是一次**压缩失败**。会话下次加载时,恢复流程在续写任何内容之前先以 `failed` 收束该区间,并**直接丢弃写了一半的摘要**:不做任何重建,原上下文照旧,阈值依然超标、压缩留待下次触发时补做。收束区间正是让其后对话保持可见的关键——所有读取方都把成对事件之间的消息当作压缩内部消息;Web 端同时丢掉那段半成品草稿,不把截断的摘要摆成像是已被采纳的样子。