Skip to content

feat(agent): 15-step history compaction and 100k input token cap - #808

Open
Razor573 wants to merge 4 commits into
wangzan101:mainfrom
Razor573:pr/compaction-15-100k
Open

Razor573 wants to merge 4 commits into
wangzan101:mainfrom
Razor573:pr/compaction-15-100k

Conversation

@Razor573

Copy link
Copy Markdown
Contributor

Summary

Ports 15-step periodic history compaction (keeping the last 3 full observations and screenshots) and a hard 100,000-token input cap per model call onto upstream main.

What this PR includes

  • ContextLimits: Adds MAX_INPUT_TOKENS = 100_000 and caps usable and minTrigger floor accordingly so large context windows (e.g., 128k / 1M) never exceed 100k input tokens per call.
  • ContextCompressor:
    • Adds periodic compaction every 15 tool-call steps (COMPACT_EVERY_STEPS = 15), preserving the last 3 full observations (KEEP_FULL_OBSERVATIONS = 3) while folding earlier completed steps into a deterministic summary.
    • Enforces MAX_INPUT_TOKENS_CAP = 100_000 during compaction and invokes HistoryPruner.enforceCap as a hard cap fallback.
  • HistoryPruner:
    • Adds pruneOlderObservations (keeps the last keepFull UI observations and attached screenshots intact while shrinking older screen payloads and images).
    • Adds enforceCap (progressively prunes older observations, shrinks oversized results, strips non-user images, drops oldest non-pinned rounds while keeping tool call/result pairs intact, and clips oversized parts if still over cap).
  • ModelCaller:
    • Enforces the 100k cap before every model call (re-compacting aggressively and applying HistoryPruner.enforceCap if needed) so neither non-streaming nor streaming calls exceed 100,000 estimated input tokens.
  • Tests: Adds CompactionAndCapTest and updates ContextLimitsTest, ContextCompressorTest, HistoryPrunerTest, StructuredCompactionTest, PrefixStabilityTest, PrefixStabilityAdaptersTest, and AgentLoopTest.

Adaptations for upstream main

  • Based cleanly on upstream main (9c7aabd8) with all fork-only changes excluded (no Mika 2 branding, no full UI tree serialization changes, no Vertex/Gemini live refresh).
  • Preserved upstream's ModelPool (attemptMember), RateLimitGovernor, ConversationMeter, and firstActionCall() in ModelCaller and ContextCompressor.
  • Kept ContextCompressor's foldEvery: Int? = null parameter backwards-compatible for existing upstream tests (ContextCompressorTest), while switching ModelCaller to use the new 15-step periodic compaction + keep-last-3-observations policy by default (superseding the temporary 16-round TEMP_COMPACTION_EVERY_ROUNDS setting in ProviderStore, which can be removed in a follow-up cleanup if desired).
  • Removed the fork-only UiTreeJson full-tree assertion from CompactionAndCapTest so tests align with upstream's UiTreeJson output format.

Verification

  • ./gradlew :core:test --tests "*ContextLimitsTest*" --tests "*ContextCompressorTest*" --tests "*HistoryPrunerTest*" --tests "*CompactionAndCapTest*" --tests "*PrefixStabilityTest*" --tests "*PrefixStabilityAdaptersTest*" --tests "*StructuredCompactionTest*" --tests "*AgentLoopTest*" — passed (BUILD SUCCESSFUL).

Copilot AI balanced review requested due to automatic review settings November 22, 2026 15:41

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T15:45:05.038244Z 89b0131 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 89b01311b2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +320 to +321
val call = work[idx].parts.filterIsInstance<Part.ToolCall>().firstOrNull()
tools.verb(call?.name) !in PINNED_VERBS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve pinned actions when pruning a round

Under cap pressure, if an assistant round contains task_progress before hand_to_user, ask_user, or request_confirmation, this firstOrNull() sees only the non-pinned bookkeeping call, so dropOldestRounds deletes the entire assistant message and all its results. ContextCompressor.fold already handles this ordering; apply the same action-call classification here so a handoff or confirmation is not silently removed from the remaining history.

Useful? React with 👍 / 👎.

val sent = if (restored === raw.messages) raw else raw.copy(messages = restored, estimate = TokenEstimate.of(restored))
var restored = ContextRecovery.ensure(history, raw.messages)
var sent = if (restored === raw.messages) raw else raw.copy(messages = restored, estimate = TokenEstimate.of(restored))
fun exceedsCap(est: Int) = UsageMeter.estimate(est + overhead, compressor.scale) > cap || (est + overhead) > ContextLimits.MAX_INPUT_TOKENS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count the transformed prompt toward the input cap

The overhead used by this check is computed from the original systemPrompt, but invokeModel() applies promptTransform before dispatch. If an enabled prompt-rewrite plugin expands the prompt, exceedsCap understates the request size and can send more than 100,000 tokens despite passing this guard; enforce the cap against the transformed prompt.

Useful? React with 👍 / 👎.

if (fits(work)) return work
clipCandidateList(ranked { m, p -> isSummaryMessage(m) && p is Part.Text })
if (fits(work)) return work
clipCandidateList(ranked { m, p -> m.author == Author.User && (p is Part.Text || p is Part.Thinking || p is Part.ToolResult) })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject image-heavy requests that cannot fit the cap

If user-supplied images keep fits false, this final candidate list cannot clip them, and the earlier image-stripping step skips user messages. enforceCap can therefore return an over-cap request, which ModelCaller.attemptMember sends without a final fit check; downscale the images or fail before dispatch when the cap still cannot be met.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants