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
66 changes: 63 additions & 3 deletions agent-claude-sdk/src/replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,55 @@
# under 145,000 tokens for everything measured, which leaves the rest of a 200K window for the
# instructions, the tools and the turn's own work.
CHARS_PER_TOKEN = 1.5
# The most real tokens one estimated token was, of everything measured above: 145,000 for 100,000.
WORST_TOKENS_PER_ESTIMATE = 1.45

# WHERE A LONG RUN CLEARS, AS EVERY OPENBOT ENGINE SETS IT (shared/context-window.ts): late, close
# to the window of the model the run is on, as Claude Code compacts (about 167,000 on a 200K window,
# about 367,000 on its 400K `auto` window of a 1M model), and 100,000 where nobody says the window.
UNKNOWN_WINDOW_TRIGGER_TOKENS = 100_000
AUTO_WINDOW_TOKENS = 400_000
WINDOW_RESERVE_TOKENS = 33_000
# How the server says the window of the model it chose for the run, beside `openbotModel`.
CONTEXT_WINDOW_PROP = "openbotContextWindow"
# Below that point, the room this harness keeps for Claude Code's own prompt and tools, the Bot's
# tool schemas, its role and context, and the turn's own work: what the budget left on a 200K window.
REPLAY_HEADROOM_TOKENS = 22_000


def context_window_of(value):
"""A context window in tokens, or None for anything that is not one."""
if isinstance(value, bool):
return None
if isinstance(value, str):
try:
value = float(value)
except ValueError:
return None
if isinstance(value, (int, float)) and math.isfinite(value) and 1_000 <= value <= 100_000_000:
return int(value)
return None


def clear_trigger_for(window):
"""Past how many input tokens a run on a model with this window makes room."""
tokens = context_window_of(window)
if tokens is None:
return UNKNOWN_WINDOW_TRIGGER_TOKENS
filled = min(tokens, AUTO_WINDOW_TOKENS)
return max(filled - WINDOW_RESERVE_TOKENS, filled // 2)


def replay_budget(window):
"""How much of the thread a query replays, in estimated tokens, on a model with this window.

The most the replay may really be, at the worst ratio measured, is what is left below the point
every engine makes room at once the headroom is kept: 100,000 on a 200K window, as before, and
on a 1M window about 238,000, which is never past where Claude Code itself would compact. Never
less than `REPLAY_BUDGET_TOKENS`, which every window this harness runs at holds.
"""
room = (clear_trigger_for(window) - REPLAY_HEADROOM_TOKENS) / WORST_TOKENS_PER_ESTIMATE
return max(REPLAY_BUDGET_TOKENS, int(room))
# The most visual tokens one image costs on any current model: a 2,576 px long edge on Claude 4.7
# and later (https://platform.claude.com/docs/en/build-with-claude/vision).
IMAGE_TOKENS = 4_784
Expand Down Expand Up @@ -203,7 +252,9 @@ def as_sent_to_model(input_data):
)


def conversation_content(messages, model_only=True, fit_results=False, recall=False):
def conversation_content(
messages, model_only=True, fit_results=False, recall=False, budget=REPLAY_BUDGET_TOKENS
):
"""Replay completed history as labelled data; keep attached images as images.

ClaudeSDKClient.query accepts user input, not an arbitrary assistant history.
Expand Down Expand Up @@ -231,6 +282,8 @@ def conversation_content(messages, model_only=True, fit_results=False, recall=Fa
it was smaller than the budget assumes.

`recall` says the run offers `recall_earlier_results`, which a cleared result then names.

`budget` is the run's (`replay_budget`): larger on a model the server says has a larger window.
"""
kept = [
message
Expand All @@ -242,6 +295,7 @@ def conversation_content(messages, model_only=True, fit_results=False, recall=Fa
entries = fit_to_budget(
kept,
[_entry_blocks(_cut_result(message, RESULT_CHARS), strict=model_only) for message in kept],
budget=budget,
cut_all=fit_results,
recall=recall,
)
Expand All @@ -253,13 +307,13 @@ def conversation_content(messages, model_only=True, fit_results=False, recall=Fa
]
first = _first_request(kept)
costs = [estimated_tokens(blocks) for blocks in entries]
start, skipped = replay_plan(kept, costs, pinned=first)
start, skipped = replay_plan(kept, costs, budget=budget, pinned=first)
if start or skipped:
# Over the budget even with results cleared: room is kept for what is condensed, and for
# the lines that open and may close the replay.
frame = estimated_tokens([*content, {"type": "text", "text": HISTORY_ENDS}])
start, skipped = replay_plan(
kept, costs, budget=REPLAY_BUDGET_TOKENS - DIGEST_TOKENS - frame, pinned=first
kept, costs, budget=budget - DIGEST_TOKENS - frame, pinned=first
)
pinned = first is not None and first < start
earlier = [index for index in range(start) if not (pinned and index == first)]
Expand Down Expand Up @@ -816,6 +870,12 @@ async def prompt():
model_only=model_only,
fit_results=fit_results,
recall=any(tool.name == RECALL for tool in input_data.tools or []),
# Larger on a model the server says has a larger window (`replay_budget`).
budget=replay_budget(
(input_data.forwarded_props or {}).get(CONTEXT_WINDOW_PROP)
if isinstance(input_data.forwarded_props, dict)
else None
),
),
},
"parent_tool_use_id": None,
Expand Down
60 changes: 60 additions & 0 deletions agent-claude-sdk/tests/test_long_turn_replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,26 @@
Real replay functions on real AG-UI messages, with results the size of an app's listing.
"""

import asyncio
import json
import sys
from pathlib import Path

import pytest
from ag_ui.core import RunAgentInput

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.replay import REPLAY_BUDGET_TOKENS, conversation_content, estimated_tokens


@pytest.fixture
def sdk_client(sdk):
"""The controlled SDK client of test_thread_history: it records each query's prompt."""
return sdk


from test_thread_history import sdk # noqa: E402,F401 The fixture, shared.

# The newest results a replay keeps whole, as OpenBot's other engines do.
KEEP_WHOLE_RESULTS = 10
STEPS = 100
Expand Down Expand Up @@ -201,6 +212,55 @@ def test_a_plan_written_early_in_a_long_turn_survives_a_replay_past_the_budget()
)


def test_a_model_with_a_1m_window_replays_far_more_whole(sdk_client):
"""The replay's budget follows the window of the model the run is on, where the server says it.

100,000 tokens is sized for the smallest window Claude Code runs at, 200K. On a model with a 1M
window Claude Code keeps everything until about 367,000, so a thread of about 180,000 tokens as
the replay estimates it replays whole there: every result, the oldest included. With no window
said, as before.
"""
from src.adapter import OpenBotClaudeAgentAdapter
from src.replay import replay_budget

assert replay_budget(None) == replay_budget(200_000) == REPLAY_BUDGET_TOKENS
steps = 15
messages = [message.model_dump(by_alias=True, exclude_none=True) for message in long_turn(6_000)]
# The first 15 steps of the long turn: 45 results of 6,000 characters.
cut_at = next(index for index, message in enumerate(messages) if message["id"] == f"step-{steps}")
thread = messages[:cut_at]

def request(window):
return RunAgentInput.model_validate(
{
"threadId": "thread-a",
"runId": f"run-{window}",
"state": {},
"messages": thread,
"tools": [],
"context": [],
"forwardedProps": {} if window is None else {"openbotContextWindow": window},
}
)

async def replayed_prompt(window):
adapter = OpenBotClaudeAgentAdapter(name="test")
try:
async with asyncio.timeout(5):
[event async for event in adapter.run(request(window))]
return sdk_client[-1].prompts[-1]
finally:
await adapter.shutdown()

unknown = asyncio.run(replayed_prompt(None))
assert "RESULT_000_TAIL" not in unknown, "on an unknown window the oldest results are cut"

large = asyncio.run(replayed_prompt(1_000_000))
for number in range(steps * BATCH):
assert f"RESULT_{number:03d}_TAIL" in large, f"result {number} whole on a 1M window"
assert "cut to make room" not in large and "were left out" not in large


def test_a_long_turn_of_large_results_fits_on_the_too_long_retry():
"""Ten results of 20 KB are over the budget on their own, so the first replay keeps them whole
and over it; the retry after the model refuses it as too long cuts them, and fits."""
Expand Down
2 changes: 1 addition & 1 deletion agent-langgraph-ts/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ WORKDIR /app
COPY agent-langgraph-ts/package.json agent-langgraph-ts/package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force

COPY shared/listen-port.ts shared/model-providers.ts shared/model-providers.json shared/recall-earlier-results.ts shared/tool-search.ts /shared/
COPY shared/context-window.ts shared/listen-port.ts shared/model-providers.ts shared/model-providers.json shared/recall-earlier-results.ts shared/tool-search.ts /shared/
COPY agent-langgraph-ts/src ./src

ENV NODE_ENV=production PORT=4215
Expand Down
99 changes: 72 additions & 27 deletions agent-langgraph-ts/src/context-room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
* 1. On Claude, Anthropic clears old tool results on its side. Every request carries the edit and
* its beta, and the whole history. A proxy in front of Claude that refuses the field is
* remembered for the life of the process and gets rule 2 instead.
* 2. On every other provider the rule runs here, before each model call: past 100,000 input
* tokens, the oldest tool results become a short note naming their call until what is sent is
* down to 60,000, never the last 10, and only if that frees at least 20,000 tokens. Then the
* 2. On every other provider the rule runs here, before each model call: past the trigger, the
* oldest tool results become a short note naming their call until what is sent is down to
* 60% of it, never the last 10, and only if that frees at least 20,000 tokens. The trigger is
* late, close to the window of the model the server chose for the run where it says it
* (`openbotContextWindow`, about 367,000 on a 1M window, as Claude Code compacts), and 100,000
* where nobody says (shared/context-window.ts). Anthropic is told the same trigger. Then the
* boundary holds until what is sent passes 100,000 again, so the provider's prompt cache is
* broken once per clearing rather than on every step (`heldClearing`). `search_tools` results
* are never cleared, because they say which tools the Bot may call. Each call keeps a result, so
Expand Down Expand Up @@ -39,17 +42,28 @@ import {
HumanMessage,
ToolMessage,
} from "@langchain/core/messages";
import {
CONTEXT_WINDOW_PROP,
contextWindowOf,
UNKNOWN_WINDOW_TRIGGER_TOKENS,
} from "../../shared/context-window.ts";
import { RECALL_EARLIER_RESULTS } from "../../shared/recall-earlier-results.ts";
import { SEARCH_TOOLS } from "../../shared/tool-search.ts";
import { links, providerWords, statusOf } from "./errors.ts";

/** Past this many input tokens, old tool results are cleared. */
export const CLEAR_TRIGGER_TOKENS = 100_000;
/**
* Down to this many, and then the boundary is held until the trigger is passed again, so the prefix
* a provider caches changes once in a long stretch of steps instead of on every one.
* Past this many input tokens, old tool results are cleared, on a model whose window nobody said.
* Where the server says the window of the model it chose (`openbotContextWindow`), the run clears
* late, close to it, as Claude Code does (`clearTriggerFor`, shared/context-window.ts).
*/
export const CLEAR_TRIGGER_TOKENS = UNKNOWN_WINDOW_TRIGGER_TOKENS;
/**
* Down to this share of the trigger, and then the boundary is held until the trigger is passed
* again, so the prefix a provider caches changes once in a long stretch of steps instead of on
* every one: 60,000 on the 100,000 trigger.
*/
export const LOW_WATERMARK_TOKENS = 60_000;
export const LOW_WATERMARK_SHARE = 0.6;
export const LOW_WATERMARK_TOKENS = CLEAR_TRIGGER_TOKENS * LOW_WATERMARK_SHARE;
/**
* The tool results that stay whole. Ten rather than Anthropic's default of three: a Bot is told to
* batch about five reads at once, and a step must see the whole of its latest batch.
Expand All @@ -69,21 +83,32 @@ export const CHARS_PER_TOKEN = 2.3;
export const IMAGE_TOKENS = 1_600;

export const CONTEXT_EDITING_BETA = "context-management-2025-06-27";
/** Anthropic's context editing, with the same numbers as the local rule. */
export const CONTEXT_EDITING = {
edits: [
{
type: "clear_tool_uses_20250919" as const,
trigger: { type: "input_tokens" as const, value: CLEAR_TRIGGER_TOKENS },
keep: { type: "tool_uses" as const, value: KEEP_RESULTS },
clear_at_least: {
type: "input_tokens" as const,
value: CLEAR_AT_LEAST_TOKENS,
/** Anthropic's context editing, with the same numbers as the local rule, past `trigger`. */
export function contextEditingFor(trigger: number) {
return {
edits: [
{
type: "clear_tool_uses_20250919" as const,
trigger: { type: "input_tokens" as const, value: trigger },
keep: { type: "tool_uses" as const, value: KEEP_RESULTS },
clear_at_least: {
type: "input_tokens" as const,
value: CLEAR_AT_LEAST_TOKENS,
},
exclude_tools: NEVER_CLEARED,
},
exclude_tools: NEVER_CLEARED,
},
],
};
],
};
}
/** Anthropic's context editing on a model whose window nobody said. */
export const CONTEXT_EDITING = contextEditingFor(CLEAR_TRIGGER_TOKENS);

/** The window the server says the run's model has, or undefined: `openbotContextWindow`. */
export function runContextWindow(
props: Record<string, unknown>,
): number | undefined {
return contextWindowOf(props[CONTEXT_WINDOW_PROP]);
}

export const RECALL = RECALL_EARLIER_RESULTS;

Expand Down Expand Up @@ -401,10 +426,24 @@ export function cutEarlier(
*/
export function roomFor(
messages: readonly BaseMessage[],
options: { stage: number; clearsOnServer: boolean; extraChars?: number },
options: {
stage: number;
clearsOnServer: boolean;
extraChars?: number;
/** Stage 0's trigger: the run's model's (`clearTriggerFor`), else `CLEAR_TRIGGER_TOKENS`. */
trigger?: number;
},
): BaseMessage[] {
if (options.stage === 0 && options.clearsOnServer) return [...messages];
const stage: Stage = STAGES[Math.min(options.stage, LAST_STAGE)];
const chosen: Stage = STAGES[Math.min(options.stage, LAST_STAGE)];
const stage =
options.stage === 0 && options.trigger
? {
...chosen,
trigger: options.trigger,
low: options.trigger * LOW_WATERMARK_SHARE,
}
: chosen;
const cleared = clearOldResults(messages, stage, options.extraChars ?? 0);
return [...(stage.cut ? cutEarlier(cleared) : cleared)];
}
Expand All @@ -418,10 +457,16 @@ function addressOf(model: ChatAnthropic): string {
return model.apiUrl?.trim() || "https://api.anthropic.com";
}

/** A Claude model with Anthropic's context editing on, unless its address has refused it. */
export function withContextEditing(model: ChatAnthropic): ChatAnthropic {
/**
* A Claude model with Anthropic's context editing on, past `trigger`, unless its address has
* refused it.
*/
export function withContextEditing(
model: ChatAnthropic,
trigger: number = CLEAR_TRIGGER_TOKENS,
): ChatAnthropic {
if (editingRefused.has(addressOf(model))) return model;
model.contextManagement = CONTEXT_EDITING;
model.contextManagement = contextEditingFor(trigger);
model.betas = [...(model.betas ?? []), CONTEXT_EDITING_BETA];
return model;
}
Expand Down
8 changes: 8 additions & 0 deletions agent-langgraph-ts/src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { ChatAnthropic } from "@langchain/anthropic";
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatGoogle } from "@langchain/google";
import { ChatOpenAI } from "@langchain/openai";
import { clearTriggerFor } from "../../shared/context-window.ts";
// The one rule every Bot in the box decides by, imported rather than copied, so a model OpenAI
// moves to the Responses API moves here in the same change. Node loads it through the JSON hook in
// json-modules.ts (see there for why and how).
Expand Down Expand Up @@ -80,6 +81,11 @@ export type RunModel = {
organization?: string;
/** The run's own stop, which cancels a Claude plan's query. */
signal?: AbortSignal;
/**
* The context window of the model the server chose, when it says (`openbotContextWindow`): where
* the run clears its old tool results (context-room.ts).
*/
contextWindow?: number;
};

export const ROUTES = new Set([
Expand Down Expand Up @@ -307,6 +313,8 @@ function anthropicModel(model: string, run: RunModel, env: Env): BaseChatModel {
...(thinksByDefault(model) ? { thinking: { type: "adaptive" } } : {}),
}),
),
// Late on a large window, as Claude Code compacts (shared/context-window.ts).
clearTriggerFor(run.contextWindow),
),
);
}
Expand Down
Loading
Loading