From b83739c14aa5026bdecb283940c6c86283c160af Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 12:29:53 -0800 Subject: [PATCH] Clear a long run's old results late, close to the model's own window Every engine cleared old tool results past 100,000 input tokens, whatever the model. On a model with a 1M window that cleared what a Bot had read long before it had to: Claude Code on the same model keeps everything until about 367,000. shared/context-window.ts holds one rule: clear close to the window of the model the run is on, as Claude Code compacts. 1M and 400K windows clear at 367,000 (Claude Code's 400K auto window, kept as a cost guard), a 200K window at 167,000, a 128K window at 95,000, a small one at half its window, and an unknown window at 100,000 as before. The server says the window of the model it chose in forwardedProps.openbotContextWindow; a stock AG-UI agent ignores it. The LangGraph engine clears from that trigger on every provider, holds its boundary at 60% of it, and tells Anthropic's context editing the same trigger. The Claude Agent SDK engine replays more of the thread on a larger window: 100,000 estimated tokens on a 200K or unknown window as before, about 238,000 on a 1M window, never past where Claude Code itself would compact. A connected Bot can declare its model's window in its AG-UI capabilities, custom["openbot.contextWindow"] = { "tokens": N }, and is cleared at the same point. --- agent-claude-sdk/src/replay.py | 66 ++++++++++++- .../tests/test_long_turn_replay.py | 60 +++++++++++ agent-langgraph-ts/Dockerfile | 2 +- agent-langgraph-ts/src/context-room.ts | 99 ++++++++++++++----- agent-langgraph-ts/src/models.ts | 8 ++ agent-langgraph-ts/src/run.ts | 17 +++- agent-langgraph-ts/test/context-room.test.ts | 46 +++++++++ docs/agent-frameworks.md | 8 ++ shared/context-window.ts | 77 +++++++++++++++ shared/tests/context-window.test.ts | 41 ++++++++ 10 files changed, 391 insertions(+), 33 deletions(-) create mode 100644 shared/context-window.ts create mode 100644 shared/tests/context-window.test.ts diff --git a/agent-claude-sdk/src/replay.py b/agent-claude-sdk/src/replay.py index ba8f3d803d..c8000a522c 100644 --- a/agent-claude-sdk/src/replay.py +++ b/agent-claude-sdk/src/replay.py @@ -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 @@ -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. @@ -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 @@ -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, ) @@ -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)] @@ -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, diff --git a/agent-claude-sdk/tests/test_long_turn_replay.py b/agent-claude-sdk/tests/test_long_turn_replay.py index 7525e8fda3..97aaa5cc51 100644 --- a/agent-claude-sdk/tests/test_long_turn_replay.py +++ b/agent-claude-sdk/tests/test_long_turn_replay.py @@ -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 @@ -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.""" diff --git a/agent-langgraph-ts/Dockerfile b/agent-langgraph-ts/Dockerfile index 98caf61b43..a771a03ce6 100644 --- a/agent-langgraph-ts/Dockerfile +++ b/agent-langgraph-ts/Dockerfile @@ -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 diff --git a/agent-langgraph-ts/src/context-room.ts b/agent-langgraph-ts/src/context-room.ts index c0868be236..17390ebdee 100644 --- a/agent-langgraph-ts/src/context-room.ts +++ b/agent-langgraph-ts/src/context-room.ts @@ -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 @@ -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. @@ -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, +): number | undefined { + return contextWindowOf(props[CONTEXT_WINDOW_PROP]); +} export const RECALL = RECALL_EARLIER_RESULTS; @@ -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)]; } @@ -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; } diff --git a/agent-langgraph-ts/src/models.ts b/agent-langgraph-ts/src/models.ts index f8881dd361..437e6caca4 100644 --- a/agent-langgraph-ts/src/models.ts +++ b/agent-langgraph-ts/src/models.ts @@ -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). @@ -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([ @@ -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), ), ); } diff --git a/agent-langgraph-ts/src/run.ts b/agent-langgraph-ts/src/run.ts index 34c17506c2..f8a57d7b35 100644 --- a/agent-langgraph-ts/src/run.ts +++ b/agent-langgraph-ts/src/run.ts @@ -69,6 +69,7 @@ import { START, StateGraph, } from "@langchain/langgraph"; +import { clearTriggerFor } from "../../shared/context-window.ts"; import { clearsOnServer, LAST_STAGE, @@ -76,6 +77,7 @@ import { recall, refusesContextEditing, roomFor, + runContextWindow, stopContextEditing, tooLong, withRecall, @@ -169,7 +171,11 @@ export type RunContext = { * How hard this run clears what it sends (`STAGES` in context-room.ts). A stage that got a * too-long request through is where every later step starts, so it is not refused again first. */ - room: { stage: number }; + room: { + stage: number; + /** Where stage 0 clears: late on the run's model's window, where the server said it. */ + trigger: number; + }; /** * The run asked Claude for its progress updates, so a thinking block with text is a line for the * person (progress-updates.ts). Otherwise thinking is never shown. @@ -615,6 +621,7 @@ async function answer(state: StateType, config: RunnableConfig) { stage: run.room.stage, clearsOnServer: clearsOnServer(run.model), extraChars: toolChars, + trigger: run.room.trigger, }); const sent = run.reminder ? withReminders(room, places, run.reminder) @@ -918,6 +925,9 @@ export async function runAgent( botId: botIdOf(input.messages ?? []), route: runRoute(props), threadId: input.threadId, + ...(runContextWindow(props) + ? { contextWindow: runContextWindow(props) } + : {}), ...(typeof props.openbotOrganization === "string" && props.openbotOrganization ? { organization: props.openbotOrganization } @@ -944,7 +954,10 @@ export async function runAgent( brokeMidCall: false, log, answersRecall: !offered.some((tool) => tool.name === RECALL), - room: { stage: startingStage(input) }, + room: { + stage: startingStage(input), + trigger: clearTriggerFor(choice.contextWindow), + }, progressUpdates: showsProgressUpdates(model), reminder: reminderForm(model), }; diff --git a/agent-langgraph-ts/test/context-room.test.ts b/agent-langgraph-ts/test/context-room.test.ts index c957887040..ae1bde5a6e 100644 --- a/agent-langgraph-ts/test/context-room.test.ts +++ b/agent-langgraph-ts/test/context-room.test.ts @@ -410,6 +410,52 @@ test("Claude: every request carries context editing and its beta, with the whole } }); +/* + * CLEARED LATE ON A LARGE WINDOW. The same thread, about 210,000 tokens as the engine estimates it, + * on a model OpenBot says has a 1M window (`openbotContextWindow`): Claude Code keeps everything on + * such a model until about 367,000 tokens, so nothing here is cleared, and Anthropic is told the + * same trigger. With no window said, 100,000 as before (the tests above). + */ +test("A model with a 1M window: nothing is cleared until about 367,000 tokens, on any provider", async () => { + const provider = await fakeProvider( + behindWindow(1_000_000, OPENAI_TOO_LONG, lookupOnce), + ); + try { + const input = longThread(); + input.forwardedProps = { + openbotModel: OPENAI_MODEL, + openbotContextWindow: 1_000_000, + }; + await stepAndContinue(openAIEnv(provider.base), input, resultBody(RESULTS)); + for (const request of provider.requests) { + const { whole, notes } = shape(request.body); + assert.equal(notes.length, 0, "nothing cleared"); + assert.ok(whole.length >= RESULTS, "every result whole"); + } + } finally { + await provider.close(); + } + const claude = await fakeProvider( + behindWindow(1_000_000, ANTHROPIC_TOO_LONG, lookupOnce), + ); + try { + const input = longThread(); + input.forwardedProps = { + openbotModel: CLAUDE_MODEL, + openbotContextWindow: 1_000_000, + }; + await stepAndContinue(anthropicEnv(claude.base), input, "a short result"); + for (const request of claude.requests) + assert.deepEqual( + (request.body.context_management as typeof CONTEXT_EDITING).edits[0] + ?.trigger, + { type: "input_tokens", value: 367_000 }, + ); + } finally { + await claude.close(); + } +}); + test("Claude behind a proxy that refuses context editing: cleared here instead, and remembered for the process", async () => { const provider = await fakeProvider( behindWindow( diff --git a/docs/agent-frameworks.md b/docs/agent-frameworks.md index 24c56a27a7..766abb4167 100644 --- a/docs/agent-frameworks.md +++ b/docs/agent-frameworks.md @@ -33,6 +33,14 @@ that declares nothing gets the system messages above, as it always has. A Mastra as **Mastra** serves its declaration at `GET
//capabilities`, which OpenBot reads through `@ag-ui/mastra` with the Bot's key. +On a long job, OpenBot keeps what it sends your endpoint inside the model's context window by +clearing old tool results to a short note your model can read back with `recall_earlier_results`. +It doesn't know which model your endpoint runs, so it starts clearing at 100,000 input tokens. To +have it clear later, as it does for its own Bots, declare your model's window in the same +capabilities, in tokens: `custom["openbot.contextWindow"] = { "tokens": 1000000 }`. OpenBot then +clears close to the window: at about 167,000 tokens on a 200,000-token window, and at about +367,000 on anything larger. + Every snippet below hands your model the system messages its caller sends, as instructions. Keep your endpoint for OpenBot alone: set an authorization header on the Bot's **Setup** and have your server check it. diff --git a/shared/context-window.ts b/shared/context-window.ts new file mode 100644 index 0000000000..2a8fbf80f8 --- /dev/null +++ b/shared/context-window.ts @@ -0,0 +1,77 @@ +/** + * WHEN A LONG RUN CLEARS ITS OLD TOOL RESULTS: LATE, CLOSE TO THE MODEL'S OWN CONTEXT WINDOW. + * + * Every engine keeps a long task inside the model's window the same way: past a number of input + * tokens, old tool results are cleared to a note naming their call, and read back on demand + * (`recall_earlier_results`). That number was 100,000 for every model, Anthropic's API default for + * context editing. On a model with a 1M window it cleared what a Bot had read long before it had to: + * Claude Code on the same model keeps everything until about 367,000. + * + * So the number follows the window of the model the run is on, wherever it is known, the way Claude + * Code sets its own (code.claude.com, Model configuration, "Default auto-compact thresholds"): + * - it acts near the window, leaving room for the turn's answer: a 200K window at about 167K, as + * Claude Code compacts at the model's limit; + * - on a larger window it stops at Claude Code's `auto` window, 400K, at about 367K. Anthropic + * tunes that "for the best cost and performance": every step sends the whole conversation, so a + * step at 900K costs more than twice one at 400K, and the cleared results are still a recall + * away. It stays as a cost guard; + * - a window too small for that room clears at half of it. + * + * Where the window is not known (a model no listing or catalogue names, a connected Bot that does + * not declare one), it is 100,000, as before: early enough for any current model, and a request a + * provider still refuses as too long is cleared harder and asked again on every engine. + * + * One rule, read by every engine that clears: the built-in agent, the server's room for every Bot + * over AG-UI, and the LangGraph engine. The Claude Agent SDK engine keeps the same numbers in + * Python (`agent-claude-sdk/src/replay.py`). + */ + +/** Past this many input tokens old tool results are cleared, when the model's window is unknown. */ +export const UNKNOWN_WINDOW_TRIGGER_TOKENS = 100_000; + +/** + * The most of a window a run fills before clearing, however large the window: Claude Code's `auto` + * window on a model with a 1M window. + */ +export const AUTO_WINDOW_TOKENS = 400_000; + +/** + * Kept free below the window when clearing starts: the turn's answer and its next steps. Claude + * Code's numbers leave the same, about 367K on its 400K window and about 967K on a full 1M. + */ +export const WINDOW_RESERVE_TOKENS = 33_000; + +/** The largest window believed: anything past it is a mistake in a listing, not a model. */ +const LARGEST_WINDOW_TOKENS = 100_000_000; + +/** A context window in tokens, or undefined for anything that is not one. */ +export function contextWindowOf(value: unknown): number | undefined { + const tokens = typeof value === "string" ? Number(value) : value; + return typeof tokens === "number" && + Number.isFinite(tokens) && + tokens >= 1_000 && + tokens <= LARGEST_WINDOW_TOKENS + ? Math.floor(tokens) + : undefined; +} + +/** Past how many input tokens a run on a model with this window clears its old tool results. */ +export function clearTriggerFor(window: unknown): number { + const tokens = contextWindowOf(window); + if (tokens === undefined) return UNKNOWN_WINDOW_TRIGGER_TOKENS; + const filled = Math.min(tokens, AUTO_WINDOW_TOKENS); + return Math.max(filled - WINDOW_RESERVE_TOKENS, Math.floor(filled / 2)); +} + +/** + * How OpenBot tells an engine it runs the window of the model it chose for the run, beside + * `openbotModel` in `forwardedProps`. A stock AG-UI agent ignores it. + */ +export const CONTEXT_WINDOW_PROP = "openbotContextWindow"; + +/** + * How a Bot's endpoint declares its model's window in its AG-UI capabilities, under the extension + * point AG-UI keeps for applications: `{"custom": {"openbot.contextWindow": {"tokens": 1000000}}}`. + * OpenBot then clears what it sends that Bot at the same point as for its own engines. + */ +export const CONTEXT_WINDOW_CAPABILITY = "openbot.contextWindow"; diff --git a/shared/tests/context-window.test.ts b/shared/tests/context-window.test.ts new file mode 100644 index 0000000000..df1fd7a916 --- /dev/null +++ b/shared/tests/context-window.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import { + clearTriggerFor, + contextWindowOf, + UNKNOWN_WINDOW_TRIGGER_TOKENS, +} from "../context-window"; + +/** + * Where a long run starts clearing old tool results, on the windows models really have, against + * Claude Code's own numbers (code.claude.com, Model configuration): it compacts at the model's + * limit, and on a 1M model at about 367,000 tokens of its 400K `auto` window. + */ +describe("where a long run clears its old tool results", () => { + test("late, close to the window, as Claude Code compacts", () => { + // Opus 5.5, Sonnet 5.5, Gemini: 1M. Claude Code's `auto` window, then 33K for the turn. + expect(clearTriggerFor(1_000_000)).toBe(367_000); + // GPT on a 400K window: the same point. + expect(clearTriggerFor(400_000)).toBe(367_000); + // A 200K window: near its limit, as Claude Code compacts a 200K model. + expect(clearTriggerFor(200_000)).toBe(167_000); + // A 128K model behind an OpenAI-compatible endpoint. + expect(clearTriggerFor(128_000)).toBe(95_000); + // A small local model: never past half its window. + expect(clearTriggerFor(32_768)).toBe(16_384); + }); + + test("100,000, as before, where nobody says the window", () => { + for (const unknown of [undefined, null, 0, -1, Number.NaN, "", "a lot", {}]) + expect(clearTriggerFor(unknown)).toBe(UNKNOWN_WINDOW_TRIGGER_TOKENS); + expect(UNKNOWN_WINDOW_TRIGGER_TOKENS).toBe(100_000); + }); + + test("a window is read as a listing gives it, and nothing that is not one is believed", () => { + expect(contextWindowOf(1_000_000)).toBe(1_000_000); + expect(contextWindowOf("200000")).toBe(200_000); + expect(contextWindowOf(131_072.5)).toBe(131_072); + expect(contextWindowOf(512)).toBeUndefined(); + expect(contextWindowOf(1e12)).toBeUndefined(); + expect(contextWindowOf(Number.POSITIVE_INFINITY)).toBeUndefined(); + }); +});