Skip to content

feat(anthropic): opt-in server-side compaction (compact-2026-01-12) - #123402

Merged
steipete merged 9 commits into
mainfrom
steipete/anthropic-server-compaction
Aug 14, 2026
Merged

steipete merged 9 commits into
mainfrom
steipete/anthropic-server-compaction

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

OpenClaw sends no Anthropic context-management features. Long Anthropic sessions rely entirely on OpenClaw's client-side compaction, which rewrites the prompt prefix (burning warm prompt caches) and has historically produced invalid message sequences under heavy tool use. Anthropic shipped server-side compaction (beta compact-2026-01-12): the API summarizes earlier context into a compaction block and drops prior history on later requests, keeping tool_use/tool_result pairing and message sequencing valid by construction.

Closes #10213 (design of record: #10213 (comment)). Related: #54041 (broader context-management passthrough, still open), #65287 (cache-preservation motivation).

Why This Change Was Made

Opt-in, mirroring the shipped OpenAI Responses server-compaction feature end to end:

  • Config: anthropicServerCompaction: true + optional anthropicCompactThreshold model/provider params (no schema change; same source-chain resolution as responsesServerCompaction). Never auto-on while the API is beta. Applies only to direct Anthropic API endpoints with API-key auth; OAuth/subscription, proxies, Bedrock/Vertex/Foundry are excluded.
  • Request: compact-2026-01-12 beta header + context_management.edits with an input_tokens trigger. Default threshold max(50000, floor(contextWindow * 0.7)); configured values clamp to Anthropic's 50K minimum. pause_after_compaction and custom instructions are v1 non-goals.
  • Capture/replay: the streamed compaction block is stored as route-fenced providerReplay state (anthropic-compaction) on the owning assistant message — not a new content-union member, so historical-transcript replay and non-Anthropic providers are untouched. The next request re-emits the summary as the first assistant block and slices pre-checkpoint history client-side; the full transcript stays local. Rejection writes a suppression tombstone and the next turn falls back to full history (the Anthropic client has no full-request rebuild retry seam; dispatch sites are single-shot).
  • Correctness fixes that ride along: mapAnthropicStopReason no longer throws on "compaction"; billed usage sums usage.iterations when a compaction iteration is present (top-level counters exclude it); transcript redaction, rewrite-invalidation, and empty-final-retry paths recognize the new checkpoint type via a shared stripCompactionReplayCheckpoint helper that also replaces the OpenAI-only one.
  • Harness interlock: resolveServerCompactionThreshold (generalized from the OpenAI-only resolver) raises the client-side preflight compaction floor to at least the server threshold, so Anthropic compacts first and OpenClaw's local compaction stays the fallback.

User Impact

Off by default; no behavior change unless a model opts in. Opted-in Anthropic sessions get provider-native summarization with valid message sequencing and warm-cache-friendly prefix handling. Docs: docs/providers/anthropic.md (new "Server-side compaction" accordion) and docs/gateway/config-agents.md.

Evidence

  • Live round-trip against api.anthropic.com (pnpm test:live src/agents/anthropic-compaction.live.test.ts, sonnet-4-6, 50K threshold): beta header sent, context_management injected, compaction checkpoint captured on dense turn 2, summary replayed as first block with sliced history on the following request, and a durable marker from pre-compaction context recalled correctly. 1 passed.
  • Direct API probe: minimal request with the exact injected payload → HTTP 200; 58K-token request → compaction content block + usage.iterations [{type:"compaction",in:58456,out:128},{type:"message",in:229,out:6}], confirming both the wire shape and that top-level usage excludes the compaction iteration (hence the billing fix).
  • Focused tests: 677 tests across the 14 changed non-live test files, 0 failures (wrapper gating/threshold/header, payload policy, capture/replay/suppression/fence-mismatch, stop-reason, iteration billing, transcript redaction, rewrite invalidation, terminal resolution, memory-flush resolver incl. OpenAI compatibility).
  • Six relevant tsgo projects green; docs MDX 773 files + link audit clean; git diff --check clean.
  • Fresh Codex autoreview (gpt-5.6-sol, high): clean, no actionable findings (0.98), plus a clean pass on the live-test hardening commit.
  • Production LOC +631/−76 (net +555, new capability); tests +1228/−21; docs +64/−1.
  • Known gap: node scripts/check-changed.mjs fails on a pre-existing doctor-closure violation from extensions/llama-cpp/src/llama-server-install.ts that reproduces on current origin/main; unrelated to this branch.

@steipete
steipete marked this pull request as ready for review August 14, 2026 01:02
@clawsweeper

clawsweeper Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: anthropic size: XL maintainer Maintainer-authored PR labels Aug 14, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 14, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 14, 2026, 12:18 AM ET / 04:18 UTC.

ClawSweeper review

What this changes

Adds opt-in Anthropic server-side compaction with request controls, stored compaction-summary replay, usage accounting, documentation, and focused/live tests.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

Keep open for explicit maintainer review. This is a protected, maintainer-authored feature PR that introduces opt-in provider configuration and persisted session replay behavior; the supplied evidence is promising but local repository inspection could not run.

Priority: P2
Reviewed head: 64625794165f3753b0351d8d2ffc4299c12c976e
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The supplied live evidence is useful, while exact-head source and upgrade-contract review remain unavailable in this environment.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body reports an after-fix live Anthropic API run and direct API probe that exercise request injection, compaction capture, replay, and durable-context recall.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body reports an after-fix live Anthropic API run and direct API probe that exercise request injection, compaction capture, replay, and durable-context recall.
Evidence reviewed 3 items Submitted implementation surface: The supplied PR diff adds Anthropic compaction request policy, replay capture, transcript sanitization, and shared checkpoint invalidation.
Real behavior evidence: The PR body reports an after-fix live api.anthropic.com round trip and a direct API probe covering injected controls, compaction capture, replay, and iteration usage.
Inspection limitation: Read-only repository commands failed before returning repository output with bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted; current-main source, scoped policy, history, and exact-head diff could not be independently inspected.
Findings None None.
Security None None.

How this fits together

Anthropic model requests pass through the bundled Anthropic plugin and shared AI transport, which also stores assistant transcript state for later turns. Compaction summaries become route-fenced replay metadata that changes the next matching Anthropic request while retaining the local transcript.

flowchart LR
  A[Agent session] --> B[Anthropic plugin]
  B --> C[Shared AI transport]
  C --> D[Anthropic API]
  D --> E[Compaction summary]
  E --> F[Assistant transcript]
  F --> G[Next request replay]
Loading

Decision needed

Question Recommendation
Should OpenClaw adopt this opt-in beta Anthropic compaction API and its persisted assistant-message replay contract? Approve the opt-in contract: Accept the beta-only direct-API configuration and route-fenced replay state after exact-head validation completes.

Why: Automated evidence cannot determine whether this new provider configuration and durable session-state behavior is the intended permanent product boundary.

Before merge

  • Resolve merge risk (P1) - The new provider replay state is persisted on assistant messages and affects subsequent requests, so maintainers should explicitly accept its upgrade and transcript-rewrite contract.
  • Resolve merge risk (P1) - Local read-only inspection was unavailable, so this review cannot independently confirm the exact-head implementation, scoped guidance, or current-main ownership history.
  • Complete next step (P2) - This protected, maintainer-authored feature needs human acceptance of its beta API, configuration, and persisted replay boundary rather than an automated repair.
Agent review details

Security

None.

PR surface

Source +685, Tests +1144, Docs +63. Total +1892 across 36 files.

View PR surface stats
Area Files Added Removed Net
Source 19 804 119 +685
Tests 15 1164 20 +1144
Docs 2 64 1 +63
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 36 2032 140 +1892

Review metrics

Metric Value Why it matters
Production versus test delta production +631/-76; tests +1228/-21; docs +64/-1 The supplied PR body identifies substantial capability growth, making owner review of the persistent replay boundary important.
Provider configuration surface 2 added model parameters anthropicServerCompaction and anthropicCompactThreshold create an opt-in behavior and upgrade-sensitive configuration path.

Stored data model

Persistent data-model change detected: persistent cache schema: packages/ai/src/providers/anthropic.test.ts, persistent cache schema: packages/ai/src/transports/anthropic-transport-stream.test.ts, serialized state: src/agents/transcript-redact.test.ts, unknown-data-model-change: packages/agent-core/src/harness/session/session-context.test.ts, vector/embedding metadata: src/auto-reply/reply/memory-flush.test.ts, vector/embedding metadata: src/auto-reply/reply/memory-flush.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm replay compatibility (recommended)
    Review exact-head fresh-session and upgraded-transcript behavior before merging the new persisted provider replay format.
  2. Pause the replay portion
    Defer the feature if maintainers do not want a durable Anthropic checkpoint contract while the API remains beta.

Technical review

Best possible solution:

Accept one canonical, route-fenced Anthropic checkpoint format only after the transcript and provider owners confirm its replay, redaction, rewrite, and upgrade behavior on the exact head.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a bug reproduction: this is a new opt-in capability. The PR supplies live-provider evidence, but local review could not independently execute or inspect the exact test path.

Is this the best way to solve the issue?

Unclear: provider-native compaction is a plausible design, but the persisted replay contract needs exact-head owner review before it can be judged the best durable solution.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 92eed63f584d.

Labels

Label justifications:

  • P2: This opt-in provider capability has bounded but meaningful effects on long-running Anthropic sessions.
  • merge-risk: 🚨 compatibility: New model parameters and beta-only behavior can affect existing provider configuration and upgrades.
  • merge-risk: 🚨 session-state: The implementation stores compaction replay metadata on assistant transcript entries for later requests.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body reports an after-fix live Anthropic API run and direct API probe that exercise request injection, compaction capture, replay, and durable-context recall.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports an after-fix live Anthropic API run and direct API probe that exercise request injection, compaction capture, replay, and durable-context recall.

Evidence

What I checked:

  • Submitted implementation surface: The supplied PR diff adds Anthropic compaction request policy, replay capture, transcript sanitization, and shared checkpoint invalidation. (packages/ai/src/transports/anthropic-compaction-replay.ts, 64625794165f)
  • Real behavior evidence: The PR body reports an after-fix live api.anthropic.com round trip and a direct API probe covering injected controls, compaction capture, replay, and iteration usage. (extensions/anthropic/server-compaction.live.test.ts, 64625794165f)
  • Inspection limitation: Read-only repository commands failed before returning repository output with bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted; current-main source, scoped policy, history, and exact-head diff could not be independently inspected.

Likely related people:

  • steipete: The supplied PR history attributes all nine commits across Anthropic compaction, transcript, and shared transport surfaces to this account. (role: feature author and recent area contributor; confidence: medium; commits: 5c9fbbf97620, ad540b39e79b, 64625794165f; files: extensions/anthropic/stream-wrappers.ts, packages/ai/src/transports/anthropic-compaction-replay.ts, src/agents/transcript-redact.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm fresh and upgraded transcript replay behavior on the exact head.
  • Have the provider and transcript owners explicitly accept the durable replay contract.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-08-14T01:24:40.515Z sha 68cfc2227a62d0879db2af6ecc60928b30c56db3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T02:21:42.876Z sha 20b03835a03170160819483b94664991c36afae3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T03:31:23.183Z sha 8f78d14 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T04:08:19.861Z sha 466d1f0 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Aug 14, 2026
@steipete
steipete force-pushed the steipete/anthropic-server-compaction branch from 3eb68a4 to 8f78d14 Compare August 14, 2026 02:59
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 14, 2026
@steipete
steipete force-pushed the steipete/anthropic-server-compaction branch from 83a31d3 to 466d1f0 Compare August 14, 2026 04:05
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 14, 2026
Keeps captureAnthropicCompaction module-local; knip flags exports whose
only consumers are tests.
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 14, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready proof for exact head 64625794165f3753b0351d8d2ffc4299c12c976e:

The latest exact-head ClawSweeper review reports no findings. The owner has accepted the opt-in beta API and durable replay boundary.

@steipete
steipete merged commit 25d4807 into main Aug 14, 2026
159 checks passed
@steipete
steipete deleted the steipete/anthropic-server-compaction branch August 14, 2026 04:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 14, 2026
…penclaw#123402)

* feat(anthropic): add server-side compaction replay

* docs(anthropic): document server compaction

* test(anthropic): harden compaction live probe

Fix the live fixture baseUrl (the SDK appends /v1 itself), fail fast on
errored turns instead of silently looping, assert request-side injection
before capture, and log per-turn stream outcomes for live debugging.

* test(anthropic): keep live settings type module-local

* refactor(agents): split transcript replay sanitizers

* test(anthropic): move compaction live probe into plugin tree

* refactor(anthropic): consolidate compaction replay duplication

* test(anthropic): align compaction threshold host coverage

* test(anthropic): fabricate checkpoints via capture tracker

Keeps captureAnthropicCompaction module-local; knip flags exports whose
only consumers are tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: anthropic gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Add Anthropic server-side compaction API support

1 participant