Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/coding-agent/docs/compaction.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ Non-cancelled failures append a versioned `step-compaction-failure` custom entry

A `length` response remains an incomplete summary and is never saved as a successful checkpoint. Check model output limits and input headroom rather than assuming increasing `reserveTokens` increases the output cap. Transient transport failures use the existing bounded retry policy; deterministic malformed responses and cancellations do not become network retries.

A `length` response is not immediately fatal: reasoning shares the model's output cap with the summary body, so a request that thinks too much can truncate a summary that would otherwise fit. Two recovery steps run in order and are recorded in `degradations`:

1. `thinking-off` — resend the unchanged input with reasoning removed.
2. `tight-target` — resend with a tightened length budget appended to the prompt.

When both are spent the truncated response is reported as a failure with the steps already applied. This is a deterministic failure: an identical request, model and cap cannot succeed on retry, so automatic threshold compaction pauses on the first occurrence instead of after the transient-failure limit.

### Summarization Request Policy

Reasoning and the summary body share one output cap. The session's thinking level is therefore only a ceiling: `compaction.thinkingLevel` (default `low`) caps it, `"inherit"` restores the old behavior of passing the session level through, and the result is clamped to what the model accepts.

`compaction.summaryTargetTokens` (default 16000) gives the prompt an explicit budget, capped at half the model's output limit so reasoning has room. The update prompt consolidates rather than copies the previous summary forward, so the summary converges instead of growing monotonically across compactions.

## Compaction

### When It Triggers
Expand Down Expand Up @@ -440,6 +453,8 @@ Configure compaction in `~/.stepcode/config.toml` or trusted `<project-dir>/.ste
enabled = true
triggerRatio = 0.9
keepRecentTokens = 20000
thinkingLevel = "low"
summaryTargetTokens = 16000

[compaction.modelTriggerRatios]
"my-provider/small-window-model" = 0.8
Expand All @@ -454,6 +469,8 @@ keepRecentTokens = 20000
| `triggerPolicy` | `"v2"` | `"legacy"` restores the previous threshold and checkpoints |
| `reserveTokens` | `16384` | Legacy trigger headroom; when set explicitly, also caps the v2 trigger at `contextWindow - reserveTokens` |
| `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) |
| `thinkingLevel` | `"low"` | Thinking-level ceiling for summarization requests; the session level is an upper bound, `"inherit"` keeps it |
| `summaryTargetTokens` | `16000` | Token target for the summary; capped at half the model's output limit |

Invalid trigger values fall back to their defaults and are reported as settings warnings at startup.

Expand Down
9 changes: 9 additions & 0 deletions packages/coding-agent/docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ anthropicExtraUsage = false
| `compaction.triggerPolicy` | string | `"v2"` | `"legacy"` restores the previous `contextWindow - reserveTokens` trigger and checkpoints |
| `compaction.reserveTokens` | number | `16384` | Legacy trigger headroom; under v2 an explicit value also caps the trigger at `contextWindow - reserveTokens` |
| `compaction.keepRecentTokens` | number | `20000` | Recent tokens to keep (not summarized) |
| `compaction.thinkingLevel` | string | `"low"` | Thinking-level ceiling for summarization requests; the session level is an upper bound, `"inherit"` keeps it |
| `compaction.summaryTargetTokens` | number | `16000` | Token target for the summary; capped at half the model's output limit |
| `compaction.contextProjection` | string | `"off"` | `off` selects native compaction, `lightweight-v1` selects deterministic projection, `clm-v1` opts into CLM |
| `compaction.autoClm.enabled` | boolean | `true` | Attempt bounded CLM maintenance before native compaction |

Expand All @@ -136,11 +138,18 @@ anthropicExtraUsage = false
enabled = true
triggerRatio = 0.9
keepRecentTokens = 20000
thinkingLevel = "low"
summaryTargetTokens = 16000
```

Compaction summaries use the provider's normal model/output and remaining-context
budget. `compaction.reserveTokens` does not set a separate summary output cap.

Reasoning shares that output cap with the summary body, so the session's thinking
level is capped by `compaction.thinkingLevel` rather than passed through. A summary
that still hits the output limit is retried once with reasoning removed and once
with a tightened budget before it fails.

### Branch Summary

| Setting | Type | Default | Description |
Expand Down
42 changes: 42 additions & 0 deletions packages/coding-agent/schema/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,48 @@
],
"description": "Context projection mode: `off` (default, native compaction), `lightweight-v1`, or `clm-v1`."
},
"thinkingLevel": {
"anyOf": [
{
"type": "string",
"const": "inherit"
},
{
"type": "string",
"const": "off"
},
{
"type": "string",
"const": "minimal"
},
{
"type": "string",
"const": "low"
},
{
"type": "string",
"const": "medium"
},
{
"type": "string",
"const": "high"
},
{
"type": "string",
"const": "xhigh"
},
{
"type": "string",
"const": "max"
}
],
"description": "Thinking level ceiling for summarization requests (default `low`). The session level is an upper bound; `inherit` keeps it. Reasoning shares the output cap with the summary, so an uncapped level truncates the summary on adaptive-thinking models."
},
"summaryTargetTokens": {
"type": "integer",
"minimum": 1,
"description": "Token target for the generated summary (default 16000). Capped at half the model's output limit; an invalid value is ignored."
},
"autoClm": {
"type": "object",
"properties": {
Expand Down
106 changes: 87 additions & 19 deletions packages/coding-agent/src/core/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import {
type ProjectionByRuleStats,
prepareCompaction,
projectContextForRequest,
resolveCompactionThinkingLevel,
resolveCompactionThreshold,
shouldCompact,
} from "./compaction/index.ts";
Expand All @@ -99,7 +100,12 @@ import {
type LiveContextStatus,
} from "./compaction/live-context/manager.ts";
import { StableContextNotices } from "./compaction/live-context/stable-notices.ts";
import { formatRetryPolicy, formatSummaryDiagnostics, SummaryFailure } from "./compaction/summary-diagnostics.ts";
import {
formatRetryPolicy,
formatSummaryDiagnostics,
isTruncatedSummaryFailure,
SummaryFailure,
} from "./compaction/summary-diagnostics.ts";
import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.ts";
import { SessionExecutionTrace } from "./execution-trace.ts";
import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.ts";
Expand Down Expand Up @@ -526,8 +532,13 @@ export class AgentSession {
private _autoClmAbortController?: AbortController;
private _manualClm = false;
private _nativeThresholdBoundary?: string;
/** Consecutive failed automatic threshold compactions; v2 pauses automatic compaction at the limit. */
private _thresholdCompactionFailures = 0;
/**
* Consecutive failed automatic threshold compactions, keyed by the identity of the
* attempt that failed. A different summarizer, output cap, context window or
* thinking level is a genuinely new attempt, so its failures start from zero; the
* same key keeps counting until a compaction succeeds.
*/
private _thresholdCompactionFailure: { fingerprint: string; count: number } | undefined;
/**
* What `_runAgentPrompt` measured for the prompt's first request. The before-request hook skips its
* check only when the outgoing request still matches, so input added afterwards is measured again.
Expand Down Expand Up @@ -865,10 +876,11 @@ export class AgentSession {
// While paused, skip measurement too: a persistent estimator fault must stop being retried.
if (this._thresholdCompactionPaused()) return context;
const previousCompaction = getLatestCompactionEntry(this.sessionManager.getBranch())?.id;
// The model the request will use; a maintenance fault is counted against it.
const model = this.model;
try {
const automatic = await this._runAutomaticClm(context, signal);
if (!automatic?.attempted) {
const model = this.model;
if (
model &&
model.contextWindow > 0 &&
Expand All @@ -885,7 +897,7 @@ export class AgentSession {
} catch (error) {
// Maintenance is optional for this request: send it as-is, and let overflow recovery cover a
// request that does not fit. _runAutoCompaction reports its own failures.
if (!signal?.aborted) this._recordMaintenanceFault(error);
if (!signal?.aborted) this._recordMaintenanceFault(error, model);
}
// Only native compaction rebuilds canonical state. Otherwise keep the loop context
// while CLM overlays its existing prefix.
Expand Down Expand Up @@ -937,15 +949,61 @@ export class AgentSession {

/** Automatic threshold maintenance pauses after repeated failures until a compaction succeeds. */
private _thresholdCompactionPaused(): boolean {
return this._usesTriggerPolicyV2() && this._thresholdCompactionFailures >= AUTO_COMPACTION_FAILURE_LIMIT;
if (!this._usesTriggerPolicyV2() || !this.model) return false;
const failure = this._thresholdCompactionFailure;
// Only the attempt that failed is paused. A different summarizer, output cap,
// window or thinking level gets its own chance, so the pause must not follow it.
return (
failure?.fingerprint === this._thresholdCompactionFingerprint(this.model) &&
failure.count >= AUTO_COMPACTION_FAILURE_LIMIT
);
}

/**
* Identity of the next automatic threshold compaction. Everything that decides
* whether the same request can succeed again is part of it: the summarizer, its
* output cap, the context window that sets the trigger, and the thinking level the
* summary request will use. Switching models to another key restarts the count;
* switching back resumes it.
*/
private _thresholdCompactionFingerprint(model: Model<any>): string {
const thinkingLevel = resolveCompactionThinkingLevel(
model,
this.thinkingLevel,
this.settingsManager.getCompactionThinkingLevel(),
);
return [
`${model.provider}/${model.id}`,
`maxTokens=${model.maxTokens}`,
`window=${model.contextWindow}`,
`thinking=${thinkingLevel}`,
].join("|");
}

/** Record a threshold-compaction failure against the attempt's fingerprint. */
private _recordThresholdCompactionFailure(model: Model<any>, deterministic = false): void {
const fingerprint = this._thresholdCompactionFingerprint(model);
const previous =
this._thresholdCompactionFailure?.fingerprint === fingerprint ? this._thresholdCompactionFailure.count : 0;
// A deterministic failure (the recovery ladder is spent) cannot succeed on an
// identical retry, so it saturates the budget instead of spending it one by one.
this._thresholdCompactionFailure = {
fingerprint,
count: deterministic ? AUTO_COMPACTION_FAILURE_LIMIT : previous + 1,
};
}

/** Clear the failure count after a compaction or CLM edit succeeded. */
private _clearThresholdCompactionFailures(): void {
this._thresholdCompactionFailure = undefined;
}

/**
* Record an unexpected throw while measuring or preparing automatic maintenance. It is persisted as a
* compaction failure diagnostic and counts toward the pause, so a persistent fault stops being retried.
*/
private _recordMaintenanceFault(error: unknown): void {
this._thresholdCompactionFailures++;
private _recordMaintenanceFault(error: unknown, model: Model<any> | undefined = this.model): void {
if (model) this._recordThresholdCompactionFailure(model);
try {
this._recordCompactionFailure(error, "threshold");
} catch {
Expand Down Expand Up @@ -1173,7 +1231,7 @@ export class AgentSession {
}
if (!result.attempted) return result;
// An accepted CLM edit is a successful automatic maintenance; it ends a failure streak.
if (result.accepted) this._thresholdCompactionFailures = 0;
if (result.accepted) this._clearThresholdCompactionFailures();
if (result.outcome) this._emit({ type: "live_context", outcome: result.outcome });
this._emit({ type: "auto_clm_end", result });
if (result.fallback && !signal?.aborted && !interrupted()) {
Expand Down Expand Up @@ -1620,7 +1678,7 @@ export class AgentSession {
this.agent.state.messages,
signal ?? this._agentRunAbortController?.signal,
);
if (outcome?.accepted) this._thresholdCompactionFailures = 0;
if (outcome?.accepted) this._clearThresholdCompactionFailures();
if (outcome) this._emit({ type: "live_context", outcome });
}
};
Expand Down Expand Up @@ -3187,8 +3245,6 @@ export class AgentSession {
source: "set" | "cycle" | "restore",
): Promise<void> {
if (modelsAreEqual(previousModel, nextModel)) return;
// A different model has its own window and summarizer behavior; give automatic compaction a fresh start.
this._thresholdCompactionFailures = 0;
await this._extensionRunner.emit({
type: "model_select",
model: nextModel,
Expand Down Expand Up @@ -3455,6 +3511,13 @@ export class AgentSession {
env: Record<string, string> | undefined,
reason: "manual" | "threshold" | "overflow",
): Promise<CompactionResult> {
// Reasoning shares the output cap with the summary body, so the session level
// is capped by `compaction.thinkingLevel` instead of being inherited as-is.
const thinkingLevel = resolveCompactionThinkingLevel(
requestModel,
this.thinkingLevel,
this.settingsManager.getCompactionThinkingLevel(),
);
return this._trace.withSummaryPurpose("compaction", () =>
compact(
preparation,
Expand All @@ -3463,7 +3526,7 @@ export class AgentSession {
headers,
customInstructions,
signal,
this.thinkingLevel,
thinkingLevel,
this.agent.streamFunction,
env,
this.settingsManager.getRetrySettings(),
Expand Down Expand Up @@ -3592,7 +3655,7 @@ export class AgentSession {
usage,
);
this._trace.recordSummary("compaction", compactionEntryId);
this._thresholdCompactionFailures = 0;
this._clearThresholdCompactionFailures();
const newEntries = this.sessionManager.getEntries();
const sessionContext = this.sessionManager.buildSessionContext();
this.agent.state.messages = sessionContext.messages;
Expand Down Expand Up @@ -4027,7 +4090,7 @@ export class AgentSession {
);
this._trace.recordSummary("compaction", compactionEntryId);
committed = true;
this._thresholdCompactionFailures = 0;
this._clearThresholdCompactionFailures();
const newEntries = this.sessionManager.getEntries();
const sessionContext = this.sessionManager.buildSessionContext();
this.agent.state.messages = sessionContext.messages;
Expand Down Expand Up @@ -4089,9 +4152,15 @@ export class AgentSession {
// A throw after the compaction was persisted (for example from a session_compact
// handler) is not a failed compaction, so it does not count toward the pause.
if (!aborted && !committed && reason === "threshold") {
this._thresholdCompactionFailures++;
// A summary the degradation ladder could not rescue is deterministic: the
// same request, model and cap fail again, so pause immediately instead of
// repeating it for the remaining transient-failure budget.
const deterministic = error instanceof SummaryFailure && isTruncatedSummaryFailure(error);
if (this.model) this._recordThresholdCompactionFailure(this.model, deterministic);
if (this._thresholdCompactionPaused()) {
formattedErrorMessage += `\nAutomatic compaction is paused for this session after ${AUTO_COMPACTION_FAILURE_LIMIT} consecutive failures. Run /compact to retry; a successful compaction resumes it.`;
formattedErrorMessage += deterministic
? `\nAutomatic compaction is paused: the summary hit the output limit even after dropping reasoning and tightening the target. Run /compact to retry; a successful compaction resumes it.`
: `\nAutomatic compaction is paused for this session after ${AUTO_COMPACTION_FAILURE_LIMIT} consecutive failures. Run /compact to retry; a successful compaction resumes it.`;
}
}
this._emit({
Expand Down Expand Up @@ -4233,8 +4302,7 @@ export class AgentSession {
}

this.agent.state.model = refreshedModel;
// A changed window moves the trigger, like a model switch; give automatic compaction a fresh start.
if (refreshedModel.contextWindow !== currentModel.contextWindow) this._thresholdCompactionFailures = 0;
// A changed window moves the trigger; the failure fingerprint already covers it.
}

private _bindExtensionCore(runner: ExtensionRunner): void {
Expand Down
Loading