Skip to content
Merged
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
6 changes: 5 additions & 1 deletion packages/core/src/session/context-reduction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ export const reduce = (input: Input): Reduction => {
const usableWindow = (model: Model) => {
const context = model.route.defaults.limits?.context
if (context === undefined || context <= 0) return undefined
return Math.max(context - (model.route.defaults.limits?.output ?? 0), 1)
// A declared output reserve at or above the context limit must not collapse the window to one
// token (every request would then be reduced to exhaustion): keep a quarter of the context.
return Math.max(context - (model.route.defaults.limits?.output ?? 0), Math.ceil(context / 4))
}

/** Serialized length of one value as the request carries it. */
Expand Down Expand Up @@ -428,6 +430,8 @@ const staleOutputs = (messages: readonly SessionMessage.Message[], protection: P
rewrite(messages, (tool, index) => {
if (index >= protection.recentFrom || tool.state.status !== "completed") return undefined
if (protection.calls.has(tool.id)) return undefined
// Truncation rebuilds the result as plain text; a result carrying files or other non-text parts would lose them.
if (tool.state.content.some((item) => item.type !== "text")) return undefined
const text = tool.state.content.map((item) => (item.type === "text" ? item.text : "")).join("\n")
if (text.length <= TRUNCATE_KEEP * 2) return undefined
return {
Expand Down
7 changes: 7 additions & 0 deletions packages/core/test/context-reduction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ describe("SessionContextReduction", () => {
expect(result.report.reclaimedTokens).toBe(0)
})

test("keeps a quarter of the context when the output reserve meets or exceeds it", () => {
const messages = [user("hello"), assistant([text("hi")])]
const result = reduce({ messages, model: windowModel(8_000, 8_000) })
expect(result.report.limit).toBe(2_000)
expect(result.report.outcome).toBe("untouched")
})

test("reports as sent when the model declares no usable window", () => {
const messages = [user(big("question")), assistant([text(big("answer"))])]
const result = reduce({ messages, model: Model.make({ id: "unknown", provider: "test", route: OpenAIChat.route }) })
Expand Down
Loading