Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(agent-core): E2E findings in context management (#2362)

Call White29d04c95568d
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index 013fce97a..f5652d01e 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -88,12 +88,15 @@ from core.agent_core.harness.context import (
clear_edit,
clearable_results,
compaction_payload,
+ fit_batch,
+ fit_edit,
fit_result,
half_cut,
last_anchor,
message_tokens,
messages_tokens,
normal_cut,
+ notes_tokens,
output_tokens,
request_facts,
request_tokens,
@@ -142,10 +145,14 @@ class UnsupportedModelRoute(ValueError):
class _Exhausted(Exception):
- """C-9 section 8 (d): the run stops ``context_exhausted``, saying what fills the context."""
+ """C-9 section 8 (d): the run stops ``context_exhausted``, saying what fills the context.
- def __init__(self, limit: int, parts: tuple[ContextPart, ...]) -> None:
- self.limit, self.parts = limit, parts
+ ``kind`` is the error's (``_cause``): the part that is too large when measurement shows it (``input_too_large``,
+ ``tool_output_too_large``, ``step_too_large``), else ``context_exhausted``, the conversation's length.
+ """
+
+ def __init__(self, limit: int, parts: tuple[ContextPart, ...], kind: str = "context_exhausted") -> None:
+ self.limit, self.parts, self.kind = limit, parts, kind
sizes = ", ".join(f"{part.name} ~{part.tokens}" for part in parts)
super().__init__(f"The context does not fit the model's input limit of {limit} tokens: {sizes}.")
@@ -260,6 +267,9 @@ class Agent:
self._committed_state_json = "{}"
# C-9's per-run bound (section 10): unproductive checkpoint attempts this run, in memory only.
self._unproductive = 0
+ # The ``context_seq`` of each input this run consumed, its first and every steer: a checkpoint inside the Turn
+ # keeps them as they were (C-9 section 5).
+ self._turn_inputs: set[int] = set()
# The run's attempt ledger (C-9): every model attempt, in order.
self._attempts: list[_Attempt] = []
self._last_model_at: Optional[float] = None
@@ -415,6 +425,7 @@ class Agent:
interruptible=False,
)
self._rows.append(row)
+ self._turn_inputs.add(row.context_seq)
def _validate_response(self, message: AssistantMessage, *, after: Sequence[Message] = ()) -> None:
"""A response is valid after the committed rows and then ``after`` (a checkpoint turn's own messages)."""
@@ -466,6 +477,7 @@ class Agent:
self._committed_state_json = state_representation(self._ctx.state)
self._committed_state = deepcopy(self._ctx.state)
self._unproductive = 0
+ self._turn_inputs = set()
self._attempts = []
loaded = True
system = self.system
@@ -487,7 +499,7 @@ class Agent:
except _Exhausted as error:
decided = self._outcome.primary("context_exhausted")
await emit(ContextExhausted, limit=error.limit, parts=error.parts)
- await self._error(emit, "context_exhausted", str(error), "local", cause=decided)
+ await self._error(emit, error.kind, str(error), "local", cause=decided)
except _Aborted:
self._outcome.primary("aborted")
except asyncio.CancelledError:
@@ -758,7 +770,9 @@ class Agent:
plan = budget(
request, route.capabilities, transcript=view.messages, anchor=last_anchor(self._rows, view)
)
- raise self._exhausted(request, view, plan)
+ movable = half_cut(view.units, turn_inputs=self._turn_inputs, pinned=view.pinned) is not None
+ kind = "context_exhausted" if movable else self._cause(view, None)
+ raise self._exhausted(request, view, plan, kind=kind)
retries, started, retry_error = 0, time.monotonic(), None
continue
retry_error = terminal
@@ -1135,12 +1149,19 @@ class Agent:
attempt in this pass can use it up.
"""
# The bound first: once the run has stopped compacting, nothing is built for a compaction either.
- if not plan.can_fit and (
- self._stopped or not (await self._minimal(system, selected, request, view, plan, carry=False))[1].can_fit
- ):
- # (d): stopped, or not even the request the drop would leave (its row and the last unit, without the
- # previous checkpoint's text) can fit. The provider never sees it.
- raise self._exhausted(request, view, plan)
+ if not plan.can_fit:
+ if self._stopped:
+ raise self._exhausted(request, view, plan) # (d); the provider never sees it
+ _, minimal = await self._minimal(system, selected, request, view, plan, carry=False)
+ if not minimal.can_fit:
+ # Not even the request the drop would leave (its row and the last unit, without the previous
+ # checkpoint's text) can fit: moving the conversation out cannot help. The newest tool batch is cut
+ # to fit (section 3); anything else is (d), and the provider never sees it.
+ rest = minimal.est - self._batch_tokens(view)
+ room = minimal.input_limit - minimal.output - rest
+ if await self._fit_batch(view, (room - minimal.margin, room)):
+ return True
+ raise self._exhausted(request, view, plan, kind=self._cause(view, minimal))
refused, ladder.refused = ladder.refused, False
shrink = refused
if not shrink:
@@ -1152,7 +1173,7 @@ class Agent:
await self._commit_context([("context_edit", clear_edit(target)) for target in targets])
return True
if plan.est >= plan.threshold and not ladder.compacted and not self._stopped:
- cut = normal_cut(view.units, plan.keep)
+ cut = normal_cut(view.units, plan.keep, turn_inputs=self._turn_inputs, pinned=view.pinned)
if cut is not None:
ladder.compacted = True
if not self._fork_fits(system, selected, view, "normal", cut):
@@ -1296,7 +1317,7 @@ class Agent:
return False
if not ladder.summary_failed and not ladder.compacted:
ladder.compacted = True
- cut = normal_cut(units, plan.keep)
+ cut = normal_cut(units, plan.keep, turn_inputs=self._turn_inputs, pinned=view.pinned)
if cut is not None and self._fork_fits(system, selected, view, "normal", cut):
outcome = await self._checkpoint(
system, selected, request, view, plan, cut, mode="normal", reason="overflow", emit=emit
@@ -1306,7 +1327,12 @@ class Agent:
ladder.summary_failed = not outcome.overflow
continue
if not ladder.summary_failed and ladder.rolls < MAX_ROLLS:
- cut = rolling_cut(units, lambda cut: self._fork_fits(system, selected, view, "rolling", cut))
+ cut = rolling_cut(
+ units,
+ lambda cut: self._fork_fits(system, selected, view, "rolling", cut),
+ turn_inputs=self._turn_inputs,
+ pinned=view.pinned,
+ )
if cut is None:
ladder.rolls = MAX_ROLLS
continue
@@ -1318,17 +1344,93 @@ class Agent:
return True
ladder.summary_failed = True
continue
- cut = half_cut(units)
+ cut = half_cut(units, turn_inputs=self._turn_inputs, pinned=view.pinned)
if cut is not None:
carry = await self._carries(system, selected, request, view, plan)
await self._drop(request, view, plan, cut, emit, carry=carry)
return True
+ # Nothing more can move out. A refused request's newest tool batch is cut to half of what the model read
+ # (the provider counts more than the estimate), down to its notes; the refusals bound the halvings.
+ if ladder.overflows and await self._fit_batch(view, (self._batch_tokens(view) // 2,), floor=True):
+ return True
if ladder.overflows or not plan.can_fit:
- raise self._exhausted(request, view, plan)
+ kind = self._cause(view, None if ladder.overflows else plan)
+ raise self._exhausted(request, view, plan, kind=kind)
return False
- def _exhausted(self, request: ModelRequest, view: ContextView, plan: Budget) -> _Exhausted:
- """Section 8 (d): what fills the request, for the user's stop message."""
+ @staticmethod
+ def _newest_batch(view: ContextView) -> list[tuple[ContextEntry, Message]]:
+ """The committed results of the newest unit when it is a tool batch, as the model reads them."""
+ last = view.units[-1] if view.units else None
+ if last is None or last.lead.kind != "response":
+ return []
+ return [(entry, message) for entry, message in last.entries[1:] if entry is not None]
+
+ def _batch_tokens(self, view: ContextView) -> int:
+ return sum(message_tokens(message) for _, message in self._newest_batch(view))
+
+ async def _fit_batch(self, view: ContextView, rooms: Sequence[int], *, floor: bool = False) -> bool:
+ """Section 3: cut the newest tool batch, which nothing can move out, to the first of ``rooms`` (tokens) it can
+ fit, or with ``floor`` to its notes when none can; True when it committed the cuts as ``fit_tool_result``
+ edits.
+
+ Water-filling over the batch's whole outputs (the rows keep them): the largest results are cut to one cap,
+ each saying so. A batch that cannot fit any room is left as it is, for the stop.
+ """
+ results = self._newest_batch(view)
+ if not results:
+ return False
+ originals = [entry.message for entry, _ in results]
+ if floor:
+ rooms = (*rooms, notes_tokens(originals))
+ for room in rooms:
+ texts = fit_batch(originals, room)
+ if texts is not None:
+ break
+ else:
+ return False
+ # Only what changes what the model reads: a stage that cut nothing new leaves the stop to decide.
+ edits = [
+ ("context_edit", fit_edit(entry, cut))
+ for (entry, message), cut in zip(results, texts)
+ if cut is not None and message.content != (text(cut),)
+ ]
+ if not edits:
+ return False
+ await self._commit_context(edits)
+ return True
+
+ def _cause(self, view: ContextView, measured: Optional[Budget]) -> str:
+ """What a stop names as too large when nothing more can move out (section 8 d), decided by measurement.
+
+ ``measured`` is the request the stop judged (the minimal request, or the request itself), whose estimate is
+ over its limit: a part of the newest unit is named only when the request without it fits. A request the
+ provider refused (None) fit our estimate, so its excess is unknown: the results are named while the cuts left
+ them above their notes, the step once they are at their notes.
+ """
+ last = view.units[-1] if view.units else None
+ if last is None:
+ return "context_exhausted"
+ if last.lead.kind == "input":
+ if measured is None:
+ return "context_exhausted"
+ without = measured.est - message_tokens(last.lead.message) + measured.output
+ return "input_too_large" if without <= measured.input_limit else "context_exhausted"
+ results = self._batch_tokens(view)
+ at_notes = results <= notes_tokens([entry.message for entry, _ in self._newest_batch(view)])
+ if measured is None:
+ return "step_too_large" if at_notes else "tool_output_too_large"
+ rest = measured.est - results + measured.output
+ if rest <= measured.input_limit:
+ return "tool_output_too_large" # the results, even at their notes, are the excess
+ if rest - message_tokens(last.lead.message) <= measured.input_limit:
+ return "step_too_large" # the step itself: its tool-call arguments or text
+ return "context_exhausted"
+
+ def _exhausted(
+ self, request: ModelRequest, view: ContextView, plan: Budget, *, kind: str = "context_exhausted"
+ ) -> _Exhausted:
+ """Section 8 (d): what fills the request, for the user's stop message, and the error's ``kind`` (``_cause``)."""
last = view.units[-1] if view.units else None
last_tokens = unit_tokens(last) if last is not None else 0
parts = [
@@ -1340,7 +1442,7 @@ class Agent:
name = "current_request" if last.lead.kind == "input" else "latest_tool_batch"
parts.append(ContextPart(name, last_tokens))
parts.append(ContextPart("output", plan.output + plan.margin))
- return _Exhausted(plan.input_limit, tuple(parts))
+ return _Exhausted(plan.input_limit, tuple(parts), kind)
async def _checkpoint(
self,
@@ -1607,6 +1709,7 @@ class Agent:
summarizer=summarizer,
usage=usage,
checkpoint_omitted=checkpoint_omitted,
+ turn_inputs=self._turn_inputs,
)
seq = max((row.context_seq for row in self._rows), default=0) + 1
candidate = ContextEntry(self.session_id, seq, "compaction", "uncommitted-compaction", payload=payload)
diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.py
index 62d7fe809..558eb8af5 100644
--- a/core/agent_core/harness/context.py
+++ b/core/agent_core/harness/context.py
@@ -18,7 +18,7 @@ import time
import unicodedata
from itertools import accumulate
from dataclasses import dataclass, field
-from typing import Any, Callable, Mapping, Optional, Protocol, Sequence
+from typing import Any, Callable, Collection, Mapping, Optional, Protocol, Sequence
from core.agent_core.ai._common import endpoint_origin
from core.agent_core.ai.provider import ModelCapabilities, ModelRequest
@@ -85,6 +85,10 @@ CHECKPOINT_TRUNCATED = (
"[Output truncated to fit this checkpoint turn: showing about {shown} of {total} tokens. "
"Read a smaller range if you need more.]"
)
+#: What a tool result cut to fit a conversation request says (section 3).
+TOOL_TRUNCATED = (
+ "[Output truncated to fit the context window; re-run with offset/limit or a narrower command to see more.]"
+)
MAX_ROLLS = 2
MAX_OVERFLOWS = 4
#: Unproductive checkpoint attempts (failed, or normal with a result still at least ``INEFFECTIVE_RATIO * T``) a run
@@ -333,12 +337,16 @@ def _estimate(request: ModelRequest, transcript: Sequence[Message], anchor: Opti
return whole
-def fit_result(content: Sequence[UserContent], limit: int) -> tuple[UserContent, ...]:
- """A checkpoint turn's tool result cut to ``limit`` tokens, head kept, saying what was cut (section 6)."""
+def fit_result(
+ content: Sequence[UserContent], limit: int, *, note: str = CHECKPOINT_TRUNCATED, cut: bool = False
+) -> tuple[UserContent, ...]:
+ """A tool result cut to ``limit`` tokens, head kept, ending with ``note`` to say so: a checkpoint turn's (section
+ 6), and through ``fit_batch`` a conversation's (section 3). ``cut``: the caller already dropped part of it (an
+ image a text replacement cannot carry), so it says so even when what is left fits."""
total = message_tokens(ToolResultMessage("fit", "fit", tuple(content)))
- if total <= limit:
+ if total <= limit and not cut:
return tuple(content)
- note = CHECKPOINT_TRUNCATED.format(shown=max(0, limit), total=total)
+ note = note.format(shown=max(0, limit), total=total)
room = max(0, limit - text_tokens(note) - 1) * 4
kept: list[UserContent] = []
for block in content:
@@ -413,7 +421,7 @@ def clearable_results(view: ContextView) -> tuple[ContextEntry, ...]:
entry is not None
and isinstance(message, ToolResultMessage)
and message.tool_name in CLEARABLE_TOOLS
- and entry.row_id not in view.edited
+ and entry.row_id not in view.cleared
):
eligible.append((index, entry, message))
candidates = [item for item in eligible[: max(0, len(eligible) - CLEAR_KEEP_RESULTS)] if item[0] < protected_from]
@@ -423,12 +431,53 @@ def clearable_results(view: ContextView) -> tuple[ContextEntry, ...]:
def clear_edit(entry: ContextEntry) -> dict[str, Any]:
- return {
- "version": 1,
- "target_event_id": entry.row_id,
- "replacement": {"text": CLEARED_PLACEHOLDER},
- "reason": "clear_old_tool_result",
- }
+ return _edit(entry, CLEARED_PLACEHOLDER, "clear_old_tool_result")
+
+
+def fit_edit(entry: ContextEntry, text: str) -> dict[str, Any]:
+ """The edit that shows a tool result cut to fit (``fit_batch``, section 3); the row keeps the whole output."""
+ return _edit(entry, text, "fit_tool_result")
+
+
+def _edit(entry: ContextEntry, text: str, reason: str) -> dict[str, Any]:
+ return {"version": 1, "target_event_id": entry.row_id, "replacement": {"text": text}, "reason": reason}
+
+
+def notes_tokens(results: Sequence[ToolResultMessage]) -> int:
+ """The tokens of a tool batch with every result cut to its note, the least ``fit_batch`` can make of it."""
+ floor = message_tokens(ToolResultMessage("fit", "fit", (text(TOOL_TRUNCATED),)))
+ return sum(min(message_tokens(result), floor) for result in results)
+
+
+def fit_batch(results: Sequence[ToolResultMessage], room: int) -> Optional[list[Optional[str]]]:
+ """A tool batch cut to ``room`` tokens (section 3): the largest results cut to one common cap, water-filling, each
+ ending with ``TOOL_TRUNCATED``; the others whole. Each result's cut text, or None where it stays whole; None for the
+ batch when even every result cut to its note cannot fit (``notes_tokens``)."""
+ sizes = [message_tokens(result) for result in results]
+ if sum(sizes) <= room:
+ return [None] * len(results)
+ floor = message_tokens(ToolResultMessage("fit", "fit", (text(TOOL_TRUNCATED),)))
+
+ def total(cap: int) -> int:
+ return sum(min(size, cap) for size in sizes)
+
+ if notes_tokens(results) > room:
+ return None
+ low, high = floor, max(sizes) # total(low) <= room < total(high)
+ while high - low > 1:
+ middle = (low + high) // 2
+ low, high = (middle, high) if total(middle) <= room else (low, middle)
+ cut: list[Optional[str]] = []
+ for result, size in zip(results, sizes):
+ if size <= low:
+ cut.append(None)
+ continue
+ # The replacement is one text: join the result's blocks first, so the cut measures what the model reads, and
+ # it always says it was cut, an image dropped included.
+ body = "\n".join(block.text or "" for block in result.content if isinstance(block, TextBlock))
+ kept = fit_result((text(body),), low, note=TOOL_TRUNCATED, cut=True)
+ cut.append("\n".join(block.text or "" for block in kept if isinstance(block, TextBlock)))
+ return cut
# --- cut points (context.md section 5) ----------------------------------------------
@@ -438,67 +487,68 @@ def unit_tokens(unit: Unit) -> int:
return messages_tokens(unit.messages)
-def _pins(units: Sequence[Unit]) -> list[Optional[int]]:
- """For each cut before ``units[cut]``, the index of the input it keeps: a cut inside a turn keeps the turn's input
- as it was (section 5), and a cut at an input keeps none."""
- pins: list[Optional[int]] = []
- last: Optional[int] = None
- for index, unit in enumerate(units):
- is_input = unit.lead.kind == "input"
- pins.append(None if is_input else last)
- last = index if is_input else last
- return pins
+def _turn(units: Sequence[Unit], turn_inputs: Collection[int]) -> tuple[list[int], list[int]]:
+ """How many of the in-flight Turn's inputs ``units[:cut]`` holds, and their tokens, for each ``cut``: a cut inside
+ the Turn keeps each of them as it was (section 5)."""
+ counts, sizes = [0], [0]
+ for unit in units:
+ kept = unit.lead.kind == "input" and unit.seq in turn_inputs
+ counts.append(counts[-1] + kept)
+ sizes.append(sizes[-1] + (unit_tokens(unit) if kept else 0))
+ return counts, sizes
-def _moves(pins: Sequence[Optional[int]], cut: int) -> bool:
- """Whether a cut before ``units[cut]`` moves out more than the input it keeps."""
- return cut > 1 or (cut == 1 and pins[1] != 0)
+def _moves(counts: Sequence[int], cut: int, pinned: int) -> bool:
+ """Whether a cut before ``units[cut]`` moves out more than the Turn's inputs it keeps, and falls after the inputs
+ the latest checkpoint kept (``pinned`` of them, first in ``units``): one between them would bring back what that
+ checkpoint summarized."""
+ return cut >= pinned and cut > counts[cut]
-def normal_cut(units: Sequence[Unit], keep: int) -> Optional[int]:
- """Index of the first kept unit: the longest tail of whole units within ``keep``, at least the last, with the input
- a cut inside a turn keeps counted at its own size (section 5).
+def normal_cut(
+ units: Sequence[Unit], keep: int, *, turn_inputs: Collection[int] = (), pinned: int = 0
+) -> Optional[int]:
+ """Index of the first kept unit: the longest tail of whole units within ``keep``, at least the last, with the
+ in-flight Turn's inputs a cut keeps counted once at their own size (section 5), never inside the ``pinned``
+ inputs the latest checkpoint kept.
- None when nothing but that input would move out.
+ None when nothing but the Turn's inputs would move out.
"""
if not units:
return None
sizes = [unit_tokens(unit) for unit in units]
tails = list(accumulate(reversed(sizes)))[::-1] # tails[cut]: the tokens of units[cut:]
- pins = _pins(units)
-
- def kept(cut: int) -> int:
- pin = pins[cut]
- return tails[cut] + (sizes[pin] if pin is not None else 0)
-
+ counts, kept = _turn(units, turn_inputs)
cut = len(units) - 1
- while cut > 0 and kept(cut - 1) <= keep:
+ while cut > max(0, pinned) and tails[cut - 1] + kept[cut - 1] <= keep:
cut -= 1
- return cut if _moves(pins, cut) else None
+ return cut if _moves(counts, cut, pinned) else None
-def half_cut(units: Sequence[Unit]) -> Optional[int]:
- """The cut nearest to half the tokens, never past the last unit; None when nothing but a kept input could move
- out."""
+def half_cut(units: Sequence[Unit], *, turn_inputs: Collection[int] = (), pinned: int = 0) -> Optional[int]:
+ """The cut nearest to half the tokens, never past the last unit nor inside the ``pinned`` kept inputs; None when
+ nothing but the Turn's kept inputs could move out."""
sizes = [unit_tokens(unit) for unit in units]
- pins = _pins(units)
+ counts, _ = _turn(units, turn_inputs)
half = sum(sizes) / 2
best: Optional[int] = None
best_distance = 0.0
before = 0
for cut in range(1, len(units)):
before += sizes[cut - 1]
- if _moves(pins, cut) and (best is None or abs(before - half) < best_distance):
+ if _moves(counts, cut, pinned) and (best is None or abs(before - half) < best_distance):
best, best_distance = cut, abs(before - half)
return best
-def rolling_cut(units: Sequence[Unit], fits: Callable[[int], bool]) -> Optional[int]:
+def rolling_cut(
+ units: Sequence[Unit], fits: Callable[[int], bool], *, turn_inputs: Collection[int] = (), pinned: int = 0
+) -> Optional[int]:
"""The largest cut at or before ``half_cut`` whose forked request over the head fits."""
- pins = _pins(units)
- cut = half_cut(units)
+ counts, _ = _turn(units, turn_inputs)
+ cut = half_cut(units, turn_inputs=turn_inputs, pinned=pinned)
while cut is not None and cut > 0:
- if _moves(pins, cut) and fits(cut):
+ if _moves(counts, cut, pinned) and fits(cut):
return cut
cut -= 1
return None
@@ -719,14 +769,19 @@ def compaction_payload(
summarizer: Optional[Mapping[str, Any]],
usage: Optional[Usage],
checkpoint_omitted: bool = False,
+ turn_inputs: Collection[int] = (),
) -> dict[str, Any]:
"""The ``Compaction`` row for a cut before ``view.units[cut]``; ``tokens_after_estimate`` is the caller's.
``window`` is that of the route the conversation's next request goes to, which reads the summary.
``checkpoint_omitted``: a drop left out the previous checkpoint's text, too large for that route (section 8 c).
+ ``turn_inputs``: the ``context_seq`` of each input the in-flight Turn consumed, its first and every steer; those
+ in the head stay as they were (``kept_inputs``, section 5).
"""
previous_row = view.compaction
previous = previous_row.payload if previous_row is not None else {}
+ if cut < view.pinned:
+ raise ValueError(f"a cut at {cut} falls inside the {view.pinned} inputs the latest checkpoint kept")
head = view.units[:cut]
files = _files(previous, head)
skills, skills_omitted = carried_skills(view, cut)
@@ -751,6 +806,7 @@ def compaction_payload(
"first_kept_seq": view.units[cut].seq,
"summarized_to_seq": summarized_to_seq(view, cut),
"previous_compaction_id": previous_row.row_id if previous_row is not None else None,
+ "kept_inputs": [unit.seq for unit in head if unit.lead.kind == "input" and unit.seq in turn_inputs],
"files_read": files.read,
"files_read_omitted": files.read_omitted,
"files_modified": files.modified,
diff --git a/core/agent_core/harness/projection.py b/core/agent_core/harness/projection.py
index be6f82b1f..5a2d83ad1 100644
--- a/core/agent_core/harness/projection.py
+++ b/core/agent_core/harness/projection.py
@@ -75,24 +75,21 @@ class ContextView:
compaction: Optional[ContextEntry]
checkpoint: Optional[UserMessage]
units: tuple[Unit, ...]
- #: Row ids of tool results a ``context_edit`` replaced.
- edited: frozenset[str]
+ #: Row ids of tool results whose latest ``context_edit`` cleared them (a result cut to fit can still be cleared).
+ cleared: frozenset[str]
context_seq: int
state: Mapping[str, Any]
-
- @property
- def pinned(self) -> bool:
- """Whether ``units[0]`` is a split turn's input the latest checkpoint keeps (C-9 context.md section 5)."""
- return bool(self.compaction and self.units and self.units[0].seq < self.compaction.payload["first_kept_seq"])
+ #: How many of ``units``, first, are inputs the latest checkpoint keeps (``kept_inputs``, C-9 context.md §5).
+ pinned: int = 0
@property
def messages(self) -> tuple[Message, ...]:
return self.prefix(len(self.units))
def prefix(self, cut: int) -> tuple[Message, ...]:
- """The projected messages before ``units[cut]``: a kept split turn's input first, then the checkpoint, whose
- state is the latest environment the model reads, then the units."""
- pinned = self.units[:1] if self.pinned and cut > 0 else ()
+ """The projected messages before ``units[cut]``: the kept inputs of the in-flight Turn first, in order, then the
+ checkpoint, whose state is the latest environment the model reads, then the units."""
+ pinned = self.units[: min(self.pinned, cut)]
head = (self.checkpoint,) if self.checkpoint is not None else ()
return (
*(message for unit in pinned for message in unit.messages),
@@ -225,6 +222,8 @@ _PAYLOAD_SHAPES: dict[str, Check] = {
},
{
"previous_compaction_id": _nullable(_string),
+ # Optional: a row without it keeps no inputs, as rows written before the field existed behave.
+ "kept_inputs": _list(lambda value: _integer(value) and value > 0),
"summarizer": _nullable(
_object({"origin": _reads(origin_from_dict), "prompt_version": _string, "rounds": _count})
),
@@ -236,7 +235,7 @@ _PAYLOAD_SHAPES: dict[str, Check] = {
"version": _one_of(1),
"target_event_id": _string,
"replacement": _object({"text": _string}),
- "reason": _one_of("clear_old_tool_result"),
+ "reason": _one_of("clear_old_tool_result", "fit_tool_result"),
}
),
"agent_state": _object({"version": _one_of(1), "state": lambda value: isinstance(value, dict)}),
@@ -279,8 +278,8 @@ def open_tool_calls(entries: Sequence[ContextEntry]) -> tuple[tuple[ContextEntry
def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] = None) -> ContextView:
- """The context in units: the split turn's input when the latest checkpoint's cut fell inside a turn, that
- checkpoint's message, then the rows from its ``first_kept_seq`` (``ContextView.prefix``).
+ """The context in units: the in-flight Turn's inputs the latest checkpoint keeps, that checkpoint's message, then
+ the rows from its ``first_kept_seq`` (``ContextView.prefix``).
Results (including late recovery rows) follow their response in call
order; a missing result is INTERRUPTED; a result whose call was summarized
@@ -292,6 +291,7 @@ def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] =
state: Mapping[str, Any] = {}
compaction: Optional[ContextEntry] = None
edits: dict[str, str] = {}
+ reasons: dict[str, str] = {}
for row in rows:
if row.kind == "agent_state":
state = row.payload["state"]
@@ -302,9 +302,10 @@ def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] =
if target is None or target.kind != "tool_result" or target.context_seq >= row.context_seq:
raise ProjectionError(f"context_edit row {row.row_id} targets no earlier tool result")
edits[target.row_id] = row.payload["replacement"]["text"]
+ reasons[target.row_id] = row.payload["reason"]
first_kept = compaction.payload["first_kept_seq"] if compaction is not None else 0
units: list[Unit] = []
- inputs = [row for row in rows if row.kind == "input" and row.context_seq < first_kept]
+ inputs = {row.context_seq: row for row in rows if row.kind == "input" and row.context_seq < first_kept}
for row in rows:
if row.kind not in {"input", "response"} or row.context_seq < first_kept:
continue
@@ -321,10 +322,14 @@ def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] =
projected = replace(projected, content=(text(edits[result.row_id]),))
entries_of_unit.append((result, projected))
units.append(Unit(row.context_seq, tuple(entries_of_unit)))
- if inputs and units and units[0].lead.kind != "input":
- # The checkpoint's cut fell inside a turn: the turn's input stays as it was, before the checkpoint and the
- # kept rows (C-9 context.md section 5), so the rest of the turn keeps every block of its request.
- units.insert(0, Unit(inputs[-1].context_seq, ((inputs[-1], inputs[-1].message),)))
+ kept: list[int] = []
+ if compaction is not None:
+ # The checkpoint's cut fell inside the in-flight Turn: each of its inputs, the first and every steer, stays as
+ # it was, in order, before the checkpoint and the kept rows (C-9 context.md section 5).
+ kept = kept_inputs(compaction, inputs, first_is_input=bool(units) and units[0].lead.kind == "input")
+ if any(seq not in inputs for seq in kept) or kept != sorted(set(kept)):
+ raise ProjectionError(f"compaction row {compaction.row_id} keeps inputs it cannot place: {kept}")
+ units[:0] = [Unit(seq, ((inputs[seq], inputs[seq].message),)) for seq in kept]
checkpoint = None
if compaction is not None:
checkpoint = UserMessage(
@@ -334,12 +339,22 @@ def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] =
compaction=compaction,
checkpoint=checkpoint,
units=tuple(deepcopy(units)),
- edited=frozenset(edits),
+ cleared=frozenset(row_id for row_id, reason in reasons.items() if reason == "clear_old_tool_result"),
context_seq=rows[-1].context_seq if rows else 0,
state=deepcopy(state),
+ pinned=len(kept),
)
+def kept_inputs(compaction: ContextEntry, inputs: Mapping[int, ContextEntry], *, first_is_input: bool) -> list[int]:
+ """The inputs a checkpoint row keeps: its ``kept_inputs``; a row written before that field kept the latest input
+ before its ``first_kept_seq`` when its cut fell inside a turn (the first kept unit is not an input), and the same
+ rule reads it now. ``inputs``: the input rows before ``first_kept_seq``, by ``context_seq``."""
+ if "kept_inputs" in compaction.payload:
+ return list(compaction.payload["kept_inputs"])
+ return [max(inputs)] if inputs and not first_is_input else []
+
+
def project(
entries: Sequence[ContextEntry],
*,
diff --git a/docs/plans/agent-core-contracts/context.md b/docs/plans/agent-core-contracts/context.md
index 85cb3a8a1..d989ce17c 100644
--- a/docs/plans/agent-core-contracts/context.md
+++ b/docs/plans/agent-core-contracts/context.md
@@ -76,11 +76,19 @@ So does anything after `R`, an edit there included.
Every conversation request takes the request pipeline (§10, invariant 1). Its C-9 stage, inside the tool loop and
before a retry alike:
-1. **Stop** (§8 d) when the request cannot fit and neither can its minimal request: the request the drop (§8 c)
- would leave with everything but the last unit moved out (the drop's own row with its `state`, and, when the cut
- splits a turn, the turn's input, which stays, §5), budgeted without the anchor (its history would be gone). With
- fewer than two units nothing can move out, and the minimal request is the request itself. The provider never
- sees the request.
+1. **Fit the newest tool batch, or stop** (§8 d) when the request cannot fit and neither can its minimal request:
+ the request the drop (§8 c) would leave with everything but the last unit moved out (the drop's own row with its
+ `state`, without the previous checkpoint's text, and the in-flight Turn's kept inputs, §5), budgeted without the
+ anchor (its history would be gone). With fewer than two units nothing can move out, and the minimal request is
+ the request itself. Moving the conversation out cannot help then, so when the last unit is a tool batch it is cut
+ to fit: the minimal request with the margin `M` when it can, else without; the largest results are cut to one
+ common cap (water-filling), each keeping its head (its text blocks joined; an image the text replacement cannot
+ carry is dropped) and always ending with `[Output truncated to fit the context window; re-run with offset/limit
+ or a narrower command to see more.]`, as one `context_edit` row per cut result
+ (`"reason": "fit_tool_result"`; the rows keep the whole output, §4). This is the bound a checkpoint turn applies
+ to its own tool results (§6), one helper for both. The run continues and compacts as usual. A batch that does not
+ fit even with every result cut to its note, or a last unit that is an input, stops the run: the provider never
+ sees the request. A batch that fits once the conversation moves out is never cut; the ladder makes room for it.
2. **Clear** (§4) when the provider cache is cold (no model request for longer than the cache TTL, 300 s by
default; after a restart, measured from the latest response row's `created_at`) or `est >= 0.8 * T`.
3. **Checkpoint** when `est >= T`, the run has not stopped compacting (§10), and there is something to summarize,
@@ -104,7 +112,8 @@ each is sent only when it can fit.
- Eligible: results of `read` and `bash` in the projected context (terminal screen snapshots join when they exist).
- Protected: results after the second-latest input (the last 2 user turns; with fewer than 2 inputs since the latest
- checkpoint, all of them), the newest 5 eligible results, and results already cleared. A skill load clears like any
+ checkpoint, all of them), the newest 5 eligible results, and results already cleared (a result cut to fit, §3, can
+ still be cleared). A skill load clears like any
other result: the model loads the skill again by name when it needs it, as after a checkpoint (§7). Results before the latest checkpoint are not in the context.
- Applied only when the candidates free at least 20,000 tokens, all at once, one `context_edit` row per result:
`{"target_event_id": <tool_result row id>, "replacement": {"text": PLACEHOLDER}, "reason": "clear_old_tool_result"}`.
@@ -119,22 +128,27 @@ results of its tool calls. A cut falls only before a unit: before a user message
whose tool batch follows it; never at a tool result, so no call is separated from its result.
- **Normal** (threshold, and the first overflow step): the tail is the longest run of whole units at the end
- whose tokens total at most `keep`, and at least the last unit; a split turn's input, which stays (below), counts
- toward `keep` once, at its own size. Everything before it is the head. A head with nothing to summarize but that
- input means there is nothing to summarize.
+ whose tokens total at most `keep`, and at least the last unit; the in-flight Turn's inputs a cut keeps (below)
+ count toward `keep` once, at their own size. Everything before it is the head. A head with nothing to summarize
+ but those inputs means there is nothing to summarize.
- **Rolling** (§8 b): the cut nearest to half the tokens, moved earlier until the forked request over the head can fit
(§1); never past the last unit.
- **Dropped** (§8 c): the cut nearest to half the tokens; never past the last unit.
-Neither moves out nothing but a split turn's input.
-
-`first_kept_seq` is the `context_seq` of the first kept unit. If that unit is not an input, the cut split a turn, and
-the turn's input stays: projection keeps the latest input before `first_kept_seq` as it was, images, attachments, and
-environment block included, right before the checkpoint message and the kept rows (§7), so the checkpoint's
-`state`, the current environment, comes after any environment block the input carries and the latest wins by
-position. The checkpoint summarizes everything else in the head. Nothing is copied and no row field names it: the input is found from the rows,
-and stays through later checkpoints while their cuts fall inside the same turn. If the input alone cannot fit, nothing
-can move it out, and §8 (d) applies.
+Neither moves out nothing but the in-flight Turn's kept inputs.
+
+`first_kept_seq` is the `context_seq` of the first kept unit. A cut inside the in-flight Turn keeps every input that
+Turn consumed before it, its first and each accepted steer, verbatim and in order: the loop knows them (it consumed
+them in this run; the rows carry no Turn identity, and a Turn's start cannot be told from their shape), and the row
+records them (`kept_inputs`, their `context_seq`). Projection places them as they were, images, attachments, and
+environment blocks included, right before the checkpoint message and the kept rows (§7), so the checkpoint's
+`state`, the current environment, comes after any environment block they carry and the latest wins by position.
+The checkpoint summarizes everything else in the head, and a later checkpoint inside the same Turn keeps them again.
+In a later run they are ordinary history, yet no cut falls between them: one there would make an old input's seq the
+new `first_kept_seq` and bring back what that checkpoint summarized, so cuts start at the first unit after them.
+`kept_inputs` is optional: a row written before it kept the latest input before its `first_kept_seq` when its cut
+fell inside a turn (the first kept unit is not an input), and projection reads such a row by the same rule. An earlier Turn a cut splits is summarized like any head. If the kept inputs alone cannot fit, nothing can move them
+out, and §8 (d) applies.
## 6. Checkpoint turn
@@ -251,9 +265,9 @@ is written, so projection stays a pure function of the rows:
the cwd escaped and never cut, every other field cut to 160 UTF-8 bytes (`display`), so the block is the cwd, which
the OS bounds, plus at most about 4 x 40 tokens; a checkpoint always happens inside
a run, and a Turn's own input carries only the fields that changed). Nothing else is rehydrated in v1: skills are
- listed by name in `<skills-loaded>`, pending work is the checkpoint's own "Waiting on", and a split turn's input
- stays as it was (§5).
-- Projection (C-5 §3): the system prompt, hook-rehydrated messages, a split turn's input (§5), one user message
+ listed by name in `<skills-loaded>`, pending work is the checkpoint's own "Waiting on", and the in-flight Turn's
+ inputs stay as they were (§5).
+- Projection (C-5 §3): the system prompt, hook-rehydrated messages, the kept inputs (§5), one user message
holding `summary` and then each `state` text as its own text block, then the rows from `first_kept_seq` on, with
edits applied. A tool result whose
call was summarized is left out with it. No synthetic "continue" message follows.
@@ -275,8 +289,8 @@ once the request fits:
at most 2 rolls per request.
- (c) **Dropped**: when no checkpoint request can help (one failed for this request other than by overflow, a rolling
one failed, no rolling prefix can fit, or the rolls are used up), no model is called:
- the earliest part (§5) moves out of the context. Built like any checkpoint row (§7: fresh `state`, and a split
- turn's input stays), the row keeps the previous checkpoint's text and the
+ the earliest part (§5) moves out of the context. Built like any checkpoint row (§7: fresh `state`, and the
+ in-flight Turn's inputs stay), the row keeps the previous checkpoint's text and the
`<earlier-record>` pointer; `checkpoint` is empty when there was none, and the message then has no framing text.
The previous checkpoint's text is kept only if the minimal request (§3) carrying it can fit: a checkpoint written
on a larger route may not fit a smaller fallback. Otherwise the row has no model text, and its message says, in
@@ -288,7 +302,13 @@ once the request fits:
before provider admission), when nothing more can move out of a request that cannot fit or that the provider
refused, after 4 provider overflows of one request, or once the run has stopped compacting (§10), the run ends
`context_exhausted` and the `context_exhausted` event says what fills the context. No model is called for a
- context that cannot fit.
+ context that cannot fit. The error's kind names what is too large, decided by measurement when moving the
+ conversation out cannot help: a part of the newest unit is named only when the request the stop judged (the
+ minimal request, or the request itself) would fit without it. `tool_output_too_large` when that part is the tool
+ batch's results (even cut to their notes, §3), `step_too_large` when it is the step itself (its tool-call arguments
+ or text), `input_too_large` when it is an input; otherwise `context_exhausted`, the conversation's length. A
+ request the provider refused fit the estimate, so its excess is unknown: the results are named while the cuts left
+ them above their notes, the step once they are at their notes.
An attempt the provider refused, or that is retried, is never context (§10, invariant 4).
@@ -307,11 +327,13 @@ ends the run `context_exhausted`, as in P1. The adapter supplies the following;
which is `O`.
- `scratch_dir`: this Session's scratch directory, `<state>/agent_core/scratch/<session_id>/`; without it, the
policy denies every write.
-- `ContextHost.earlier_record(session_id, through_seq)`: a short factual hint, not a command: the earlier
- conversation is stored in Avibe and can be searched with `vibe data query` against table `messages`, `session_id =
- '<id>'`, `context_seq <= <through_seq>`, the model-facing text being in `content_json.model.message`; for a fork, one
- more line names the Session it was forked from and at which `context_seq`. The model writes its own query (the
- system prompt teaches `vibe data query`); `messages` is readable by every caller.
+- `ContextHost.earlier_record(session_id, through_seq)`: a short factual hint: the earlier messages (inputs and
+ replies, through `through_seq`) are in Avibe's `messages` table under `session_id`, and tool outputs are not, so
+ the model re-runs a tool for its output (`messages` is readable by every caller; tool results are not). Then one
+ runnable example, a fixed query with no CTE and no decoding: `vibe data query --sql "SELECT context_seq, type,
+ substr(content_text,1,500) FROM messages WHERE session_id='<id>' AND context_seq <= <N> ORDER BY context_seq DESC
+ LIMIT 20"`, emitted only when the id is a plain token (letters, digits, `_`, `-`), so the line always runs as
+ written. For a fork, one more line names the Session it was forked from and at which `context_seq`.
- `ContextHost.render_state(StateRequest)`: the `state` texts (§7): the environment's core fields.
- Skill loads marked in their results: `vibe skill load` writes one `<skill_content name="...">` block per skill it
loads, and every top-level block in a successful `bash` result is recorded in the result's `details.skills`
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index 8d6f80472..726bb5ec7 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -104,7 +104,7 @@ sent with that request gets the error result `Tool <name> is not available.`
| `tool_finished` | the committed `tool_result` row; a handed-over job names its Watch |
| `steer_applied` | the steer delivery is accepted into the running Turn |
| `compaction_started`, `compaction_finished`, `compaction_failed` | none: compaction is invisible (C-9 `context.md` §10); a finished one lowers the session's token snapshot |
-| `context_exhausted` | the run's stop message: the conversation has grown too long to continue reliably; start a new session with `/new` (C-9 `context.md` §9); the parts are diagnostic |
+| `context_exhausted` | the run's stop message, from the error's kind (C-9 `context.md` §8 d): `context_exhausted`, the conversation has grown too long to continue reliably, start a new session with `/new`; `tool_output_too_large`, the latest tool output does not fit even shortened, ask for a smaller part or use a larger model; `input_too_large`, the message does not fit, send a shorter one or use a larger model; `step_too_large`, the latest step (its tool-call arguments or text) is too large, ask for smaller steps or use a larger model. The parts are diagnostic |
| `run_ended` | `MessageOutput` settles the Turn; `cause` is the error that decided the outcome, from which the adapter takes the failure's kind, text, and Model Hub attribution (a diagnostic is never the cause) |
| `error` | `notify` / `error` row; the text shown is the adapter's localized copy for the event's `kind` (`vibe/i18n`), and `message` is diagnostic detail, never display copy; `origin` (`source` or `local`, set where the loop raises the error) decides whether Model Hub records the failure against the route (C-9 `context.md` §9) |
diff --git a/docs/plans/agent-core-contracts/transcript-rows.schema.json b/docs/plans/agent-core-contracts/transcript-rows.schema.json
index 98ed53de8..767ebc6d4 100644
--- a/docs/plans/agent-core-contracts/transcript-rows.schema.json
+++ b/docs/plans/agent-core-contracts/transcript-rows.schema.json
@@ -162,7 +162,7 @@
},
"summary": {
"type": "string",
- "description": "The rendered `<context-checkpoint>` message: framing, checkpoint, `<artifacts>`, `<skills-loaded>`, and `<earlier-record>`. Model-facing. When `first_kept_seq` is not an input, the split turn's input row stays in the projected context as it was, right before this message (context.md section 5); no field names it."
+ "description": "The rendered `<context-checkpoint>` message: framing, checkpoint, `<artifacts>`, `<skills-loaded>`, and `<earlier-record>`. Model-facing. The in-flight Turn's inputs before the cut (`kept_inputs`) stay in the projected context as they were, right before this message (context.md section 5)."
},
"checkpoint": {
"type": "string",
@@ -180,6 +180,14 @@
"minimum": 1,
"description": "`context_seq` of the first unit kept verbatim."
},
+ "kept_inputs": {
+ "type": "array",
+ "items": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "description": "`context_seq` of each input of the in-flight Turn (its first and every accepted steer) before `first_kept_seq`, ascending: projection keeps them verbatim, in order, right before this row's message (context.md section 5). Empty when the cut did not fall inside that Turn; optional: a row without it, written before the field, keeps the latest input before `first_kept_seq` when the first kept unit is not an input, as it was written."
+ },
"summarized_to_seq": {
"type": "integer",
"minimum": 0,
@@ -312,8 +320,10 @@
},
"reason": {
"enum": [
- "clear_old_tool_result"
- ]
+ "clear_old_tool_result",
+ "fit_tool_result"
+ ],
+ "description": "`clear_old_tool_result` replaces an old result with the cleared placeholder (context.md section 4); `fit_tool_result` shows the newest batch's result cut to fit, ending with its note (section 3). The row keeps the whole output either way."
}
}
},
@@ -428,6 +438,7 @@
"<loaded-skills>\n...\n</loaded-skills>"
],
"first_kept_seq": 412,
+ "kept_inputs": [],
"summarized_to_seq": 411,
"previous_compaction_id": null,
"files_read": [
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index f5dcc85c8..bcfe9da01 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -186,13 +186,15 @@ and `bash` results with `context_edit` rows, on by default; and a checkpoint wri
transcript up to the response is unchanged; otherwise UTF-8 bytes / 4 of the whole request. Compact when
`est >= T`.
- **Cut** before a user message or before an assistant message whose tool batch follows it, keeping
- `min(20K, 0.25 T)` verbatim; a split turn's input stays in the context as it was, images included.
+ `min(20K, 0.25 T)` verbatim; a cut inside the in-flight Turn keeps its inputs (the first and each steer) as they
+ were, images included. A tool batch that cannot fit even with the conversation moved out is cut to fit, each
+ result saying so.
- **Checkpoint delivery is a fork**: the same model, system prompt, tools, tool choice, and reasoning settings, the
conversation prefix byte-identical, and the owner-approved three-layer prompt appended (`checkpoint-v2`). The
checkpoint turn runs through the same loop under a "dreaming" tool policy: `read` allowed, writes only inside the
Session's scratch directory, everything else denied; at most 5 tool rounds, each tool bounded by the room left in
the window. Its messages are audit rows, never context.
-- **After a checkpoint** the request is the rebuilt system prompt, a split turn's input as it was, the
+- **After a checkpoint** the request is the rebuilt system prompt, the in-flight Turn's kept inputs as they were, the
`<context-checkpoint>` message (framing, checkpoint, cumulative `<artifacts>`, an `<earlier-record>` hint), state
rendered from its own stores when the checkpoint was written (the environment's core fields; the skills it loaded
are listed by name in the checkpoint, for the model to load again), and the verbatim tail. No synthetic "continue" message.
diff --git a/modules/agents/avibe/context.py b/modules/agents/avibe/context.py
index 03f7c64cf..854f6127c 100644
--- a/modules/agents/avibe/context.py
+++ b/modules/agents/avibe/context.py
@@ -3,8 +3,9 @@
``AvibeContextHost`` is the loop's ``ContextHost``:
* ``earlier_record`` is the short hint a checkpoint carries in ``<earlier-record>``:
- where the earlier conversation is stored and how far it goes, and the Session's
- fork source when it is a fork. The model writes its own ``vibe data query``;
+ where the earlier messages are stored and how far they go, one runnable example
+ query, and the Session's fork source when it is a fork. Tool outputs are not
+ there: the model runs a tool again for them;
* ``render_state`` renders the state a checkpoint carries: the environment's core
fields (a checkpoint always happens inside a run), bounded by construction.
@@ -29,6 +30,8 @@ from modules.agents.avibe.prompt import EnvironmentValue, render_environment
#: The tags of the block ``vibe skill load`` writes for each skill it loads (``render_skill_content``).
_SKILL_TAG = re.compile(r'<skill_content name="([^"]*)"[^>]*>|</skill_content>')
+#: An id the example query can quote as it is, in SQL and in the shell.
+_PLAIN_ID = re.compile(r"[A-Za-z0-9_-]+")
def output_budget(capabilities: Any) -> int:
@@ -63,20 +66,23 @@ class AvibeContextHost:
self._environment = environment
def earlier_record(self, session_id: str, through_seq: int) -> Optional[str]:
- """Where the earlier conversation is stored, for the model to search with its own ``vibe data query``.
+ """Where the earlier messages are stored, with one runnable example (``example_query``).
- Not a command: the system prompt already teaches ``vibe data query``, and the rows it names are in
- ``messages``, which every caller may read.
+ ``messages`` holds them and every caller may read it; tool outputs are not there, so the model runs a tool
+ again for its output.
"""
from storage.agent_transcript import fork_link
with self._engine.connect() as conn:
link = fork_link(conn, session_id)
hint = (
- "The full earlier conversation is stored in Avibe. Search it with `vibe data query` against table messages,"
- f" session_id = '{display(session_id)}', context_seq <= {int(through_seq)}; the model-facing text is in"
- " content_json.model.message."
+ "The earlier messages of this conversation (your inputs and replies, through context_seq"
+ f" {int(through_seq)}) are stored in Avibe's messages table, session_id = '{display(session_id)}'."
+ " Tool outputs are not stored there; re-run a tool if you need its output again."
)
+ example = example_query(session_id, through_seq)
+ if example is not None:
+ hint += f" For example:\n{example}"
if link is not None:
hint += f"\nThis Session was forked from {display(link[0])} at context_seq {int(link[1])}."
return hint
@@ -85,6 +91,18 @@ class AvibeContextHost:
return [_environment(self._environment(request.session_id))]
+def example_query(session_id: str, through_seq: int) -> Optional[str]:
+ """One runnable ``vibe data query`` line over the Session's earlier messages, newest first; None for an id it
+ could not quote as it is."""
+ if _PLAIN_ID.fullmatch(session_id) is None:
+ return None
+ sql = (
+ "SELECT context_seq, type, substr(content_text,1,500) FROM messages"
+ f" WHERE session_id='{session_id}' AND context_seq <= {int(through_seq)} ORDER BY context_seq DESC LIMIT 20"
+ )
+ return f'vibe data query --sql "{sql}"'
+
+
def _environment(fields: Mapping[str, EnvironmentValue]) -> str:
"""The environment's core fields, bounded by construction (section 7): no Watches, and each field displayed as
every input's block displays it (``render_environment``)."""
diff --git a/modules/agents/avibe/errors.py b/modules/agents/avibe/errors.py
index 3b6f81c19..13f631b23 100644
--- a/modules/agents/avibe/errors.py
+++ b/modules/agents/avibe/errors.py
@@ -20,6 +20,10 @@ _KIND_KEYS: dict[str, str] = {
"aborted": "interrupted",
"overflow": "contextExhausted",
"context_exhausted": "contextExhausted",
+ # The newest unit alone cannot fit (C-9 section 8 d): starting over would not help, so the copy says what to do.
+ "tool_output_too_large": "toolOutputTooLarge",
+ "input_too_large": "inputTooLarge",
+ "step_too_large": "stepTooLarge",
"rate_limit": "rateLimit",
"overloaded": "overloaded",
"network": "network",
diff --git a/tests/agent_core/agent/test_compaction.py b/tests/agent_core/agent/test_compaction.py
index c69797e54..e6576c423 100644
--- a/tests/agent_core/agent/test_compaction.py
+++ b/tests/agent_core/agent/test_compaction.py
@@ -42,6 +42,7 @@ from core.agent_core.agent.models import ModelSelection
from core.agent_core.cancel import CancelToken
from core.agent_core.harness.context import (
CHECKPOINT_REQUEST,
+ TOOL_TRUNCATED,
ContextConfig,
StateRequest,
compaction_payload,
@@ -814,6 +815,29 @@ async def test_the_ladder_rolls_when_no_fork_can_take_the_whole_context():
assert events[-1].reason == "completed"
+async def test_a_turn_keeps_its_input_and_every_steer_verbatim_across_a_mid_turn_checkpoint():
+ # The Turn's input and a steer it accepted mid-Turn both stay as they were, in order, ahead of the checkpoint: a
+ # checkpoint that rewrote either ("read f10 to f18" as "continue with f19") would drift what the Turn answers.
+ holder, steered = {}, []
+
+ async def execute(arguments, ctx):
+ if not steered:
+ steered.append(await holder["agent"].steer(input_row("steer", "STEER: also report each size")))
+ return ToolResult((text(tokens(6_000)),))
+
+ model = Model(growing(4), [[Done(assistant(CHECKPOINT))]])
+ holder["agent"] = agent = make_agent(model, tools=[FakeTool("read", execute=execute)])
+ events = await run(agent, "read f0 to f3")
+ assert steered == [True] and events[-1].reason == "completed" and len(model.checkpoint_requests) == 1
+ first, steer, checkpoint, *tail = model.conversation_requests[-1].messages
+ assert [first.content[0].text, steer.content[0].text] == ["read f0 to f3", "STEER: also report each size"]
+ assert checkpoint.content[0].text.startswith("<context-checkpoint>") and tail
+ rows = await agent.store.load("session")
+ (compaction,) = [row for row in rows if row.kind == "compaction"]
+ inputs = [row.context_seq for row in rows if row.kind == "input"]
+ assert compaction.payload["kept_inputs"] == inputs
+
+
async def test_a_small_fallback_drops_a_previous_checkpoint_too_large_for_it_and_continues():
# A 15,000-token checkpoint written on a large route cannot fit an 8,000-token fallback: no fork can take it, and a
# drop that kept it would still not fit. The drop leaves its model text out, says so, and the Turn continues.
@@ -868,19 +892,112 @@ async def test_the_ladder_drops_mechanically_once_a_checkpoint_request_fails():
assert events[-1].reason == "completed"
-async def test_the_ladder_stops_with_what_fills_the_context_when_nothing_more_can_move():
- # One result of 30,000 tokens: only the current request and that tool batch are left, and they do not fit.
- model = Model([call("read", "huge", path="f")])
- agent = make_agent(model, tools=[reader(tokens(30_000))])
+#: A 16,000-token route answering at most 4,000 tokens (the Avibe Agent's budget, a quarter of the window).
+SMALL = ModelSelection(
+ ENDPOINT, replace(SELECTION.capabilities, context_window=16_000, input_limit=None, max_output_tokens=4_000)
+)
+
+
+async def test_three_parallel_reads_larger_than_a_16k_window_are_cut_to_fit_and_the_turn_completes():
+ # The E2E repro: a fresh session on a 16K route with a 4,000-token system prompt reads three 15.6 KB files in one
+ # step. Nothing can move out, yet the run continues: the largest results are cut to one cap, each saying so.
+ calls = [ToolCallBlock(f"r{index}", "read", {"path": f"ctx/part0{index}.txt"}) for index in range(3)]
+ model = Model([[Done(assistant(calls=calls))], [Done(assistant("done"))]])
+ agent = make_agent(model, tools=[reader("x" * 15_600)], selection=SMALL, system="s" * 16_000)
+ events = await run(agent)
+ assert events[-1].reason == "completed" and not [e for e in events if isinstance(e, ContextExhausted)]
+ final = model.conversation_requests[-1]
+ results = [message for message in final.messages if isinstance(message, ToolResultMessage)]
+ assert len(results) == 3 and all(result.content[0].text.endswith(TOOL_TRUNCATED) for result in results)
+ assert len({message_tokens(result) for result in results}) == 1 # one cap for equal results
+ # The request fits with the margin, so it is sent as it is.
+ assert request_tokens(final.system, final.tools, final.messages) + 4_000 + 2_000 <= 16_000
+ rows = await agent.store.load("session")
+ # The rows keep every output whole; three edits cut what the model reads.
+ assert [len(row.message.content[0].text) for row in rows if row.kind == "tool_result"] == [15_600] * 3
+ assert [row.payload["reason"] for row in rows if row.kind == "context_edit"] == ["fit_tool_result"] * 3
+
+
+async def test_a_tool_batch_the_ladder_can_make_room_for_is_never_cut():
+ # The batch does not fit beside the history, but it fits once the history moves out: the ladder compacts, and
+ # the result reaches the model whole.
+ store = InMemoryTranscriptStore()
+ await _history_on_a_large_window(store, [5_000, 5_000, 5_000, 2_000])
+ model = Model([call("read", "big", path="f"), [Done(assistant("done"))]], [[Done(assistant(CHECKPOINT))]] * 3)
+ agent = make_agent(model, store=store, tools=[reader(tokens(12_000))])
+ events = await run(agent)
+ assert events[-1].reason == "completed" and [e for e in events if isinstance(e, CompactionFinished)]
+ rows = await store.load("session")
+ assert not [row for row in rows if row.kind == "context_edit" and row.payload["reason"] == "fit_tool_result"]
+ final = model.conversation_requests[-1]
+ (result,) = [m for m in final.messages if isinstance(m, ToolResultMessage) and m.tool_call_id == "big"]
+ assert result.content[0].text == tokens(12_000)
+
+
+async def test_a_refused_batch_nothing_can_move_out_of_is_halved_until_the_provider_takes_it():
+ # The provider counts more than the estimate: it refuses a request that fits here, and nothing older can move
+ # out. The batch is the newest unit, so it is cut to half of what the model read, and the request is sent again.
+ calls = [ToolCallBlock(f"r{index}", "read", {"path": f"f{index}"}) for index in range(3)]
+ model = Model([[Done(assistant(calls=calls))], [OVERFLOW], [Done(assistant("done"))]])
+ agent = make_agent(model, tools=[reader(tokens(2_000))], selection=SMALL)
+ events = await run(agent)
+ assert events[-1].reason == "completed" and not model.checkpoint_requests
+ results = [m for m in model.conversation_requests[-1].messages if isinstance(m, ToolResultMessage)]
+ assert all(result.content[0].text.endswith(TOOL_TRUNCATED) for result in results)
+ assert sum(message_tokens(result) for result in results) <= 3 * 2_001 // 2
+
+
+async def test_a_batch_the_provider_keeps_refusing_is_reported_only_after_it_was_shortened():
+ # Refused on every request: the batch is halved after each refusal, and only then does the run say the tool
+ # output does not fit even shortened, which is now true.
+ calls = [ToolCallBlock(f"r{index}", "read", {"path": f"f{index}"}) for index in range(3)]
+ model = Model([[Done(assistant(calls=calls))], *[[OVERFLOW]] * 4])
+ agent = make_agent(model, tools=[reader(tokens(2_000))], selection=SMALL)
+ events = await run(agent)
+ assert events[-1].reason == "context_exhausted"
+ assert [e.kind for e in events if isinstance(e, AgentError)] == ["tool_output_too_large"]
+ sizes = [
+ sum(message_tokens(m) for m in request.messages if isinstance(m, ToolResultMessage))
+ for request in model.conversation_requests[1:]
+ ]
+ assert len(sizes) == 4 and all(later <= earlier // 2 + 3 for earlier, later in zip(sizes, sizes[1:]))
+
+
+async def test_the_stop_names_the_step_when_its_own_arguments_are_what_does_not_fit():
+ # A write whose arguments nearly fill the window and whose result is two words: the results are not the excess,
+ # the step is, and the error says so instead of blaming the tool output.
+ write = ToolCallBlock("w", "write", {"path": "big.txt", "content": tokens(13_000)})
+ model = Model([[Done(assistant(calls=[write]))]])
+ agent = make_agent(model, tools=[FakeTool("write", result=ToolResult((text("ok"),)))], selection=SMALL)
events = await run(agent)
- exhausted = next(event for event in events if isinstance(event, ContextExhausted))
- assert exhausted.limit == 32_000
- parts = {part.name: part.tokens for part in exhausted.parts}
- assert set(parts) == {"system", "tools", "history", "latest_tool_batch", "output"}
- assert parts["latest_tool_batch"] > 30_000 and parts["output"] == 4_096 + 8_000
- assert [(e.kind) for e in events if isinstance(e, AgentError)] == ["context_exhausted"]
assert events[-1].reason == "context_exhausted"
- assert not model.checkpoint_requests # nothing to summarize, so no model call
+ assert [(e.kind, e.origin) for e in events if isinstance(e, AgentError)] == [("step_too_large", "local")]
+
+
+async def test_a_refused_step_whose_results_are_already_at_their_notes_is_named_as_the_step():
+ # The provider refuses, and the batch cannot be shortened (its result is smaller than a note): what is too large
+ # is the step, not its output.
+ model = Model([call("read", "r", path="f"), [OVERFLOW]])
+ agent = make_agent(model, tools=[reader("tiny")], selection=SMALL)
+ events = await run(agent)
+ assert [e.kind for e in events if isinstance(e, AgentError)] == ["step_too_large"]
+
+
+async def test_the_stop_names_the_tool_output_when_even_its_notes_cannot_fit():
+ # 300 results on an 8,000-token route: cut to their notes, they still do not fit beside the step that asked for
+ # them. The newest tool output is the cause, not the conversation's length, and the error says so.
+ tiny = ModelSelection(
+ ENDPOINT, replace(SELECTION.capabilities, context_window=8_000, input_limit=None, max_output_tokens=2_000)
+ )
+ calls = [ToolCallBlock(f"r{index}", "read", {"path": f"f{index}"}) for index in range(300)]
+ model = Model([[Done(assistant(calls=calls))]])
+ agent = make_agent(model, tools=[reader(tokens(100))], selection=tiny)
+ events = await run(agent)
+ assert events[-1].reason == "context_exhausted"
+ assert [(e.kind, e.origin) for e in events if isinstance(e, AgentError)] == [("tool_output_too_large", "local")]
+ exhausted = next(event for event in events if isinstance(event, ContextExhausted))
+ assert {part.name for part in exhausted.parts} >= {"latest_tool_batch", "output"}
+ assert not [row for row in await agent.store.load("session") if row.kind == "context_edit"]
assert len(model.requests) == 1 # the oversized request never reached the provider
@@ -916,16 +1033,17 @@ async def test_the_stage_judges_the_fork_it_would_send_exactly_as_the_turn_compo
assert all(request.messages[0] == state for request in model.requests)
-async def test_the_stop_check_counts_the_split_turn_input_the_drop_would_keep():
- # The last unit is a tool batch after a large input: moving everything else out still keeps that input, pinned
- # as the split turn's, so nothing can make the request fit (section 8 d). It stops before any checkpoint call or
- # row.
- model = Model([call("read", "big", path="f")], [[Done(assistant(CHECKPOINT))]])
+async def test_the_turn_input_a_drop_would_keep_leaves_the_batch_only_the_room_after_it():
+ # The last unit is a tool batch after a large input: moving everything else out still keeps that input, the
+ # Turn's, so the batch gets only the room left beside it. It is cut to that, with no checkpoint call or row.
+ model = Model([call("read", "big", path="f"), [Done(assistant("done"))]], [[Done(assistant(CHECKPOINT))]])
agent = make_agent(model, tools=[reader(tokens(12_000))])
events = await run(agent, tokens(18_000))
- assert events[-1].reason == "context_exhausted"
- assert [event for event in events if isinstance(event, ContextExhausted)]
- assert not model.checkpoint_requests
+ assert events[-1].reason == "completed" and not model.checkpoint_requests
+ final = model.conversation_requests[-1]
+ (result,) = [message for message in final.messages if isinstance(message, ToolResultMessage)]
+ assert result.content[0].text.endswith(TOOL_TRUNCATED) and message_tokens(result) < 2_000
+ assert request_tokens(final.system, final.tools, final.messages) + 4_096 + 8_000 <= 32_000
assert not [row for row in await agent.store.load("session") if row.kind == "compaction"]
diff --git a/tests/agent_core/agent/test_context.py b/tests/agent_core/agent/test_context.py
index 5f6979dd3..a3e3a9c3a 100644
--- a/tests/agent_core/agent/test_context.py
+++ b/tests/agent_core/agent/test_context.py
@@ -24,8 +24,11 @@ from core.agent_core.harness.context import (
carried_skills,
checkpoint_request,
clearable_results,
+ TOOL_TRUNCATED,
compaction_payload,
display,
+ fit_batch,
+ fit_edit,
fit_result,
half_cut,
checkpoint_max_tokens,
@@ -225,8 +228,7 @@ def test_an_edit_or_checkpoint_before_the_anchor_or_another_route_invalidates_it
earlier_record=None, tokens_before=0, threshold=0, window=200_000, summarizer=None, usage=None,
)
rows.add("compaction", payload=payload)
- # The cut split the anchored response's turn, so the turn's input stays first (section 5).
- assert [unit.seq for unit in context_view(rows.rows).units[:2]] == [view.units[0].seq, anchored.context_seq]
+ assert context_view(rows.rows).units[0].seq == anchored.context_seq
assert _est(rows) == whole(rows)
# A failed or aborted response, or one without usage or request facts, never anchors.
for message, facts in [
@@ -284,10 +286,13 @@ def test_a_cut_never_separates_a_tool_call_from_its_result(seed):
rows = _random_rows(seed)
view = context_view(rows)
rng = random.Random(seed)
+ # The in-flight Turn's inputs: the last input and, by chance, the one before it (a steer).
+ inputs = [unit.seq for unit in view.units if unit.lead.kind == "input"]
+ turn = set(inputs[-2:] if rng.random() < 0.5 else inputs[-1:])
cuts = {
- normal_cut(view.units, rng.choice([0, 50, 500, 5_000])),
- half_cut(view.units),
- rolling_cut(view.units, lambda cut: rng.random() < 0.5),
+ normal_cut(view.units, rng.choice([0, 50, 500, 5_000]), turn_inputs=turn),
+ half_cut(view.units, turn_inputs=turn),
+ rolling_cut(view.units, lambda cut: rng.random() < 0.5, turn_inputs=turn),
}
for cut in cuts - {None}:
assert 0 < cut < len(view.units)
@@ -305,13 +310,15 @@ def test_a_cut_never_separates_a_tool_call_from_its_result(seed):
window=200_000,
summarizer=None,
usage=None,
+ turn_inputs=turn,
)
checkpoint["summary"] = "SUMMARY"
compacted = [*rows, ContextEntry("session", len(rows) + 1, "compaction", "checkpoint", payload=checkpoint)]
messages = project(compacted).messages
- # A cut inside a turn keeps the turn's input whole, right before the checkpoint (section 5).
- inputs = [unit for unit in view.units[:cut] if unit.lead.kind == "input"]
- pinned = tuple(inputs[-1].messages) if inputs and view.units[cut].lead.kind != "input" else ()
+ # A cut inside the Turn keeps each of its inputs whole, in order, right before the checkpoint (section 5).
+ kept = [unit for unit in view.units[:cut] if unit.seq in turn]
+ assert checkpoint["kept_inputs"] == [unit.seq for unit in kept]
+ pinned = tuple(message for unit in kept for message in unit.messages)
assert messages[: len(pinned)] == pinned
assert messages[len(pinned)].content[0].text == "SUMMARY"
_assert_paired(messages[len(pinned) + 1 :])
@@ -347,20 +354,118 @@ def test_the_half_cut_is_nearest_to_half_and_the_rolling_cut_moves_earlier_until
assert half_cut(units[:1]) is None
-def test_a_cut_that_splits_a_turn_counts_the_input_it_pins():
- # A cut inside a turn keeps the turn's input (section 5): it counts toward the kept tail once, at its own size,
- # and a cut that would summarize nothing but that input is no cut.
+def test_a_cut_inside_the_turn_counts_every_input_it_keeps():
+ # A cut inside the in-flight Turn keeps all of its inputs, the first one and each steer (section 5): they count
+ # toward the kept tail once, at their own size, and a cut that would summarize nothing but them is no cut.
rows = Rows()
- rows.input("x" * 8_000)
- for _ in range(4):
+ rows.input("an older turn")
+ rows.response(value="its answer")
+ first = rows.input("x" * 8_000)
+ rows.response(value="y" * 4_000)
+ steer = rows.input("z" * 2_000)
+ for _ in range(3):
rows.response(value="y" * 4_000)
units = context_view(rows.rows).units
+ turn = {first.context_seq, steer.context_seq}
size = [unit_tokens(unit) for unit in units]
- # The input and the last two responses fill the tail's budget: the first two responses are summarized.
- assert normal_cut(units, size[0] + size[3] + size[4]) == 3
- # An input and one response: moving the response's predecessors out would summarize only the pinned input.
- assert normal_cut(units[:2], 10**6) is None and half_cut(units[:2]) is None
- assert half_cut(units) == 2
+ # Both inputs and the last two responses fill the tail's budget; the older turn and two responses move out.
+ assert normal_cut(units, size[2] + size[4] + size[6] + size[7], turn_inputs=turn) == 6
+ # Without the Turn's inputs nothing is kept: the same budget keeps a longer tail.
+ assert normal_cut(units, size[2] + size[4] + size[6] + size[7]) < 6
+ # The Turn's inputs and one response: a cut there would summarize only kept inputs.
+ only = units[2:4]
+ assert normal_cut(only, 10**6, turn_inputs=turn) is None and half_cut(only, turn_inputs=turn) is None
+
+
+def test_a_tool_batch_is_cut_by_water_filling_the_largest_results_first():
+ big = ToolResultMessage("a", "read", (text("a" * 16_000),)) # 4,000 tokens
+ small = [ToolResultMessage(name, "read", (text("b" * 1_600),)) for name in ("b", "c")] # 400 each
+ texts = fit_batch([big, *small], 2_000)
+ assert texts is not None and texts[1:] == [None, None] # the small ones stay whole
+ assert texts[0].endswith(TOOL_TRUNCATED) and texts[0].startswith("a" * 100)
+ assert message_tokens(ToolResultMessage("a", "read", (text(texts[0]),))) <= 2_000 - 800
+ # Equal results share one cap.
+ equal = [ToolResultMessage(name, "read", (text("c" * 8_000),)) for name in "xyz"]
+ cut = fit_batch(equal, 3_000)
+ assert cut is not None and len({len(item) for item in cut}) == 1
+ # Everything fits: nothing is cut; even the notes cannot fit: None.
+ assert fit_batch(small, 10_000) == [None, None] and fit_batch(equal, 10) is None
+
+
+def test_a_result_of_many_blocks_cut_to_fit_stays_within_its_room():
+ # 200 blocks of 50 bytes: the replacement is one text, so the blocks are joined before the cut is measured, and
+ # the batch stays within its room however many blocks the result had.
+ many = ToolResultMessage("m", "bash", tuple(text("b" * 50) for _ in range(200)))
+ other = ToolResultMessage("o", "bash", (text("c" * 400),))
+ for room in (300, 1_000, 2_000):
+ texts = fit_batch([many, other], room)
+ assert texts is not None and texts[0] is not None and texts[0].endswith(TOOL_TRUNCATED)
+ shown = [
+ message if cut is None else ToolResultMessage(message.tool_call_id, message.tool_name, (text(cut),))
+ for message, cut in zip([many, other], texts)
+ ]
+ assert sum(message_tokens(message) for message in shown) <= room, room
+
+
+def test_a_cut_image_result_still_says_it_was_cut():
+ # The replacement is text: an image result's header fits, but its image is gone, so the note must still say so.
+ image = ToolResultMessage("i", "read", (text("Read image file [image/png]"), ImageBlock("image/png", "media-1")))
+ other = ToolResultMessage("o", "read", (text("c" * 4_000),))
+ texts = fit_batch([image, other], 600)
+ assert texts is not None and texts[0] is not None
+ assert texts[0].startswith("Read image file") and texts[0].endswith(TOOL_TRUNCATED)
+
+
+def test_a_later_cut_never_lands_inside_the_inputs_an_earlier_checkpoint_kept():
+ # A checkpoint kept the Turn's input and a steer; a later run has another Turn, so they are ordinary history now.
+ # A cut between them would make the steer's old seq the new first_kept_seq and bring back what that checkpoint
+ # summarized: cuts start at the first unit after the kept inputs.
+ rows = Rows()
+ first = rows.input("x" * 8_000)
+ rows.response(value="summarized once")
+ steer = rows.input("also this")
+ rows.response(value="summarized too")
+ kept = rows.response(value="kept")
+ view = context_view(rows.rows)
+ payload = compaction_payload(
+ view, len(view.units) - 1, mode="dropped", reason="overflow", checkpoint="", state=(), earlier_record=None,
+ tokens_before=1, threshold=2, window=200_000, summarizer=None, usage=None,
+ turn_inputs={first.context_seq, steer.context_seq},
+ )
+ rows.add("compaction", payload=payload)
+ rows.input("a new turn")
+ rows.response(value="answer")
+ units = context_view(rows.rows).units
+ assert [unit.seq for unit in units[:3]] == [first.context_seq, steer.context_seq, kept.context_seq]
+ size = [unit_tokens(unit) for unit in units]
+ assert normal_cut(units, sum(size) - size[0], pinned=2) == 2 # not 1, between the kept inputs
+ assert half_cut(units, pinned=2) == 2 and rolling_cut(units, lambda cut: True, pinned=2) == 2
+ later = compaction_payload(
+ context_view(rows.rows), 2, mode="dropped", reason="overflow", checkpoint="", state=(), earlier_record=None,
+ tokens_before=1, threshold=2, window=200_000, summarizer=None, usage=None,
+ )
+ assert later["first_kept_seq"] == kept.context_seq
+ rows.add("compaction", payload=later)
+ texts = [message.content[0].text for message in context_view(rows.rows).messages[1:]]
+ assert "summarized once" not in texts and "summarized too" not in texts
+ with pytest.raises(ValueError):
+ compaction_payload(
+ context_view(rows.rows[:-1]), 1, mode="dropped", reason="overflow", checkpoint="", state=(),
+ earlier_record=None, tokens_before=1, threshold=2, window=200_000, summarizer=None, usage=None,
+ )
+
+
+def test_a_result_cut_to_fit_can_still_be_cleared_when_it_is_old():
+ rows = Rows()
+ big = "o" * 20_000 # 5,000 tokens each
+ rows.input("turn 1")
+ old = [rows.tool("bash", big, call_id=f"old-{index}", command="ls") for index in range(11)]
+ first = next(row for row in rows.rows if row.kind == "tool_result")
+ rows.add("context_edit", payload=fit_edit(first, "o" * 4_000 + TOOL_TRUNCATED))
+ rows.input("turn 2")
+ rows.input("turn 3")
+ cleared = {entry.message.tool_call_id for entry in clearable_results(context_view(rows.rows))}
+ assert old[0].id in cleared
def test_clearing_spares_recent_turns_and_the_newest_results_and_nothing_else():
@@ -682,6 +787,7 @@ def test_a_checkpoint_carries_files_skills_and_pins_the_split_turn_input_across_
mode="normal",
reason="threshold",
checkpoint="# 1. Self and method\n- terse",
+ turn_inputs={request.context_seq},
state=("SKILLS",),
earlier_record="The full earlier conversation is stored; search it with `vibe data query`.",
tokens_before=1,
@@ -692,7 +798,7 @@ def test_a_checkpoint_carries_files_skills_and_pins_the_split_turn_input_across_
)
assert (first["files_read"], first["files_modified"]) == (["a.py"], ["b.py"])
assert not (first["files_read_omitted"] or first["files_modified_omitted"] or first["skills_omitted"])
- assert "current_request" not in first and "current_request_message_id" not in first
+ assert first["kept_inputs"] == [request.context_seq]
assert first["summary"] == "\n".join(
[
"<context-checkpoint>",
@@ -736,6 +842,7 @@ def test_a_checkpoint_carries_files_skills_and_pins_the_split_turn_input_across_
len(view.units) - 1,
mode="dropped",
reason="overflow",
+ turn_inputs={request.context_seq},
checkpoint="",
state=(),
earlier_record=None,
diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.py
index 4d01cca37..961d8b655 100644
--- a/tests/agent_core/agent/test_loop.py
+++ b/tests/agent_core/agent/test_loop.py
@@ -796,7 +796,8 @@ ERROR_SITES = {
{},
),
"a hook failure": ("exception", "RuntimeError", "local", [], {"hooks": [_Failing("before_model")]}),
- "a context that cannot fit": ("exhausted", "context_exhausted", "local", [], {"context": ContextConfig()}),
+ # A request whose newest unit alone cannot fit: moving the conversation out would not help, and the kind says so.
+ "an input that cannot fit": ("exhausted", "input_too_large", "local", [], {"context": ContextConfig()}),
"a cancelled dependency": ("cancelled", "dependency_cancelled", "local", [_cancelled], {}),
"a cleanup diagnostic": (
"diagnostic", "RuntimeError", "local", [[Done(assistant("ok"))]], {"hooks": [_Failing("after_run")]}
diff --git a/tests/agent_core/agent/test_projection.py b/tests/agent_core/agent/test_projection.py
index 21f49a3c5..912fd2601 100644
--- a/tests/agent_core/agent/test_projection.py
+++ b/tests/agent_core/agent/test_projection.py
@@ -4,7 +4,7 @@ from copy import deepcopy
import pytest
-from core.agent_core.harness.projection import INTERRUPTED, ProjectionError, project
+from core.agent_core.harness.projection import INTERRUPTED, ProjectionError, context_view, project
from core.agent_core.harness.store import ContextEntry
from core.agent_core.messages import ImageBlock, ToolCallBlock, ToolResultMessage, UserMessage, text
from tests.agent_core.fakes import assistant, user
@@ -64,6 +64,7 @@ def _checkpoint_payload(first_kept_seq, *, summary="SUMMARY", state=("STATE",),
"first_kept_seq": first_kept_seq,
"summarized_to_seq": first_kept_seq - 1,
"previous_compaction_id": None,
+ "kept_inputs": [],
"files_read": ["a.py"],
"files_modified": [],
"files_modified_omitted": False,
@@ -158,6 +159,10 @@ def _state_row(context):
_checkpoint_row(2, 1, files_read="a.py"),
_checkpoint_row(2, 1, files_modified=[1]),
_checkpoint_row(2, 1, mode="partial"),
+ # A kept input must be an input row before the kept rows.
+ _checkpoint_row(2, 1, kept_inputs=[1]),
+ _checkpoint_row(2, 2, kept_inputs=[9]),
+ _checkpoint_row(2, 2, kept_inputs=["1"]),
_checkpoint_row(2, 1, summarized_to_seq="1"),
_checkpoint_row(2, 1, threshold=1.5),
_checkpoint_row(2, 1, summarizer={"origin": {}, "prompt_version": "v", "rounds": 0}),
@@ -182,6 +187,49 @@ def test_a_complete_checkpoint_row_loads():
assert [block.text for block in projected.messages[0].content] == ["SUMMARY", "STATE"]
+def test_a_checkpoint_row_written_before_kept_inputs_keeps_the_pin_it_was_written_with():
+ # Rows written before the field pinned the latest input before first_kept_seq when the cut fell inside a turn;
+ # without the field, the same rule applies, so such a conversation keeps its request. An explicit empty list
+ # pins nothing.
+ def legacy(first_kept_seq, **fields):
+ payload = {key: value for key, value in _checkpoint_payload(first_kept_seq).items() if key != "kept_inputs"}
+ return ContextEntry("session", 9, "compaction", "c", payload={**payload, **fields})
+
+ rows = [
+ ContextEntry("session", 1, "input", "in-1", user("an older request")),
+ ContextEntry("session", 2, "response", "out-1", assistant("done")),
+ ContextEntry("session", 3, "input", "in-2", user("read f10 to f18")),
+ ContextEntry("session", 4, "response", "out-2", assistant("f10")),
+ ContextEntry("session", 5, "response", "out-3", assistant("f11")),
+ ]
+ texts = [message.content[0].text for message in project([*rows, legacy(5)]).messages]
+ assert texts == ["read f10 to f18", "SUMMARY", "f11"]
+ assert context_view([*rows, legacy(5)]).pinned == 1
+ # A cut at an input split nothing: nothing is pinned.
+ assert [m.content[0].text for m in project([*rows, legacy(3)]).messages][:2] == ["SUMMARY", "read f10 to f18"]
+ assert [m.content[0].text for m in project([*rows, legacy(5, kept_inputs=[])]).messages] == ["SUMMARY", "f11"]
+
+
+def test_the_kept_inputs_of_a_turn_stay_whole_in_order_before_the_checkpoint():
+ # The in-flight Turn's input and a steer it accepted, both before the cut: each stays as it was, in order.
+ call = ToolCallBlock("r1", "read", {"path": "a.py"})
+ rows = [
+ ContextEntry("session", 1, "input", "in-1", user("read f10 to f18")),
+ ContextEntry("session", 2, "response", "out-1", assistant(calls=[call])),
+ ContextEntry("session", 3, "tool_result", "res-1", ToolResultMessage("r1", "read", (text("f10"),))),
+ ContextEntry("session", 4, "input", "steer-1", user("also note each file's size")),
+ ContextEntry("session", 5, "response", "out-2", assistant("f11 next")),
+ _checkpoint_row(6, 5, kept_inputs=[1, 4]),
+ ]
+ messages = project(rows).messages
+ assert [message.content[0].text for message in messages] == [
+ "read f10 to f18",
+ "also note each file's size",
+ "SUMMARY",
+ "f11 next",
+ ]
+
+
def test_a_checkpoint_that_splits_a_turn_keeps_the_turn_input_whole_before_it_and_the_tail():
# The cut fell inside the turn: the turn's input stays as it was, image included, right before the checkpoint,
# whose state is then the latest environment the model reads; what came before the input is summarized.
@@ -200,7 +248,7 @@ def test_a_checkpoint_that_splits_a_turn_keeps_the_turn_input_whole_before_it_an
ContextEntry("session", 4, "response", "out-2", assistant(calls=[call])),
ContextEntry("session", 5, "tool_result", "res-2", ToolResultMessage("r1", "read", (text("a"),))),
ContextEntry("session", 6, "response", "out-3", assistant("the trace shows a stall")),
- _checkpoint_row(7, 6, state=("<environment>\ndate: 2026-10-05\n</environment>",)),
+ _checkpoint_row(7, 6, state=("<environment>\ndate: 2026-10-05\n</environment>",), kept_inputs=[3]),
]
messages = project(rows).messages
assert [type(message).__name__ for message in messages] == ["UserMessage", "UserMessage", "AssistantMessage"]
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index cbac89111..1b76f434e 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -180,6 +180,7 @@ COMPACTION = { # the current C-9 ``Compaction`` shape (transcript-rows.schema.j
"first_kept_seq": 3,
"summarized_to_seq": 2,
"previous_compaction_id": None,
+ "kept_inputs": [],
"files_read": ["core/paths.py"],
"files_modified": [],
"files_modified_omitted": False,
diff --git a/tests/test_avibe_agent_context.py b/tests/test_avibe_agent_context.py
index bca7d2dac..08934cb5a 100644
--- a/tests/test_avibe_agent_context.py
+++ b/tests/test_avibe_agent_context.py
@@ -95,7 +95,7 @@ async def test_a_threshold_checkpoint_carries_the_lookup_and_the_state_and_shows
assert is_checkpoint(harness.provider.requests[1])
compaction = [row for row in await harness.context_rows() if row.kind == "compaction"][0]
through = compaction.payload["summarized_to_seq"]
- assert f"session_id = '{SESSION}', context_seq <= {through}" in compaction.payload["summary"]
+ assert f"session_id='{SESSION}' AND context_seq <= {through} " in compaction.payload["summary"]
# Inside a run, the checkpoint carries the full environment block.
assert any(item.startswith("<environment>") for item in compaction.payload["state"])
# Silent: the user sees the two replies and nothing about the compaction.
@@ -116,6 +116,24 @@ async def test_an_8k_route_compacts_instead_of_exhausting(engine, session, tmp_p
assert _texts(harness, "result") == ["one", "two", "three"] and not harness.rows("notify")
+async def test_three_parallel_15k_reads_on_a_16k_route_complete(engine, session, tmp_path):
+ # The E2E Phase 1 repro, on a fresh Session: the Avibe system prompt and three 15.6 KB reads in one step cannot
+ # fit a 16,000-token route. The reads are cut to fit, each saying so, and the Turn answers instead of stopping.
+ from core.agent_core.harness.context import TOOL_TRUNCATED
+ from core.agent_core.messages import ToolResultMessage
+
+ calls = [ToolCallBlock(f"r{index}", "read", {"path": f"ctx/part0{index}.txt"}) for index in range(1, 4)]
+ scripts = [[Done(assistant("I'll read the first three files.", calls=calls))], [Done(assistant("codewords"))]]
+ reader = FakeTool("read", result=ToolResult((text("IMPORTANT: " + "x" * 15_589),)))
+ harness = _Harness(engine, tmp_path, "avibe", scripts, tools=[reader])
+ harness.controller.hub_limits = {"context_window": 16_000, "max_output_tokens": None}
+ await _turn(harness, "collect the codewords from ctx/part01.txt to ctx/part03.txt")
+ assert _texts(harness, "result") == ["codewords"] and not harness.rows("notify")
+ results = [m for m in harness.provider.requests[-1].messages if isinstance(m, ToolResultMessage)]
+ assert len(results) == 3 and all(result.content[0].text.startswith("IMPORTANT: ") for result in results)
+ assert all(result.content[0].text.endswith(TOOL_TRUNCATED) for result in results)
+
+
async def test_the_environment_survives_a_checkpoint_that_splits_the_turn(engine, session, tmp_path):
# The Turn's input carries its environment block; a checkpoint that splits the Turn keeps that input as it was,
# right before the checkpoint, so the rest of the Turn still has it.
@@ -204,8 +222,8 @@ async def test_a_context_that_cannot_fit_locally_is_never_reported_as_a_source_f
await _turn(harness, tokens(30_000))
assert not harness.provider.requests and not reported # stopped before the provider: no source was involved
assert harness.controller.terminals[-1]["is_error"] is True
- # The one user-visible compaction text: the conversation has grown too long; start a new session.
- assert _texts(harness, "notify") == [f"❌ {i18n_t('avibeAgent.error.contextExhausted', 'en')}"]
+ # The message itself cannot fit, so the notice says that, not that the conversation has grown too long.
+ assert _texts(harness, "notify") == [f"❌ {i18n_t('avibeAgent.error.inputTooLarge', 'en')}"]
async def _failing_commit(harness: _Harness) -> None:
@@ -336,13 +354,44 @@ async def test_the_earlier_record_hint_names_the_session_its_bound_and_its_fork_
_insert_session(conn, "ses_child", _SCOPES["avibe"], metadata)
host = AvibeContextHost(engine, environment=lambda _: {})
hint = host.earlier_record("ses_child", 7)
- assert "`vibe data query`" in hint and "table messages" in hint and "content_json.model.message" in hint
- assert "session_id = 'ses_child', context_seq <= 7" in hint
+ assert "messages table" in hint and "session_id = 'ses_child'" in hint and "through context_seq 7" in hint
+ # It says plainly what is not there: tool output is re-run, not looked up.
+ assert "Tool outputs are not stored there" in hint and "re-run" in hint
assert hint.endswith(f"This Session was forked from {SESSION} at context_seq 3.")
# A Session that is no fork has no fork line.
assert "forked" not in host.earlier_record(SESSION, 7)
+async def test_the_earlier_record_example_runs_through_the_real_read_only_guard(engine, session, tmp_path):
+ import shlex
+
+ from storage.pagination import PageRequest
+ from storage.read_only_query import run_read_only_query
+
+ # One runnable line, a fixed query with no CTE and no decoding: run as written, it returns the Session's earlier
+ # messages, newest first.
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("first reply"))], [Done(assistant("second"))]])
+ await _turn(harness, "the earliest question")
+ await _turn(harness, "a later one")
+ hint = AvibeContextHost(engine, environment=lambda _: {}).earlier_record(SESSION, 2)
+ (line,) = [line for line in hint.splitlines() if line.startswith("vibe data query ")]
+ argv = shlex.split(line)
+ assert argv[:4] == ["vibe", "data", "query", "--sql"] and len(argv) == 5
+ sql = argv[4]
+ assert "WITH" not in sql.upper().split()[0] and "json" not in sql.lower()
+ result = run_read_only_query(sql, db_path=Path(engine.url.database), page_request=PageRequest())
+ rows = [(row["context_seq"], row["type"]) for row in result.rows]
+ assert rows == [(2, "result"), (1, "user")] # through the bound, newest first
+ assert "the earliest question" in result.rows[-1]["substr(content_text,1,500)"]
+
+
+def test_the_earlier_record_example_is_left_out_for_an_id_it_could_not_quote():
+ from modules.agents.avibe.context import example_query
+
+ assert example_query("ses_ok-1", 4).startswith('vibe data query --sql "SELECT ')
+ assert example_query("ses'; DROP", 4) is None and example_query('ses"x', 4) is None
+
+
async def test_the_state_is_the_environment_core_fields_each_bounded_in_bytes(engine, session):
# The state is the environment's core fields only (no Watches, no skill bodies): the cwd whole (a cut absolute path
# would be false; the OS bounds it), every other field cut in the middle to 160 UTF-8 bytes whatever the script.
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 09d183bb7..dea0c7c8d 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1535,6 +1535,9 @@
"emptyResponse": "The model returned an empty reply. Try again or rephrase the request.",
"interrupted": "The Avibe Agent run was interrupted before it finished.",
"contextExhausted": "This conversation has grown too long to continue reliably. Start a new session with /new.",
+ "toolOutputTooLarge": "The latest tool output does not fit this model's context, even shortened. Ask for a smaller part (a narrower command, or a file range with offset and limit), or switch to a model with a larger context.",
+ "inputTooLarge": "This message does not fit this model's context. Send a shorter message, or switch to a model with a larger context.",
+ "stepTooLarge": "The latest step is too large for this model's context window. Ask for the work in smaller steps, or switch to a model with a larger context.",
"rateLimit": "The model provider is rate-limiting requests. Try again in a moment.",
"overloaded": "The model provider is overloaded. Try again in a moment.",
"network": "The model provider could not be reached. Check the network and the Model Hub source.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 585b3609a..80bbb6842 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1535,6 +1535,9 @@
"emptyResponse": "模型返回了空回复。请重试,或换一种说法。",
"interrupted": "Avibe Agent 的运行在完成前被中断。",
"contextExhausted": "本次对话已经太长,无法可靠地继续。请发送 /new 开始一个新会话。",
+ "toolOutputTooLarge": "最新的工具输出即使截短也放不进当前模型的上下文。请只取其中一部分(用更窄的命令,或用 offset/limit 读取文件的一段),或换用上下文更大的模型。",
+ "inputTooLarge": "这条消息放不进当前模型的上下文。请发送更短的消息,或换用上下文更大的模型。",
+ "stepTooLarge": "最新的一步对当前模型的上下文窗口来说太大。请让它分成更小的步骤来做,或换用上下文更大的模型。",
"rateLimit": "模型服务商正在限流,请稍后重试。",
"overloaded": "模型服务商当前过载,请稍后重试。",
"network": "无法连接模型服务商。请检查网络和 Model Hub 来源。",