## Summary
The host agent answered even a one-line question like a report: headers,
bullet menus, bold labels and emoji. Its identity said nothing about how
to reply beyond "You are Raven, a helpful AI assistant", and the soul
template listed adjectives ("Helpful and friendly", "Concise and to the
point") that no reply can be checked against, so the model fell back on
its own defaults.
`identity_text` now carries a `## How you reply` section after Raven
Guidelines. It tells the model that the reader may not have seen its
tool results or reasoning, to lead with the answer, to answer a simple
question in plain prose with no headers, bullet list or closing recap,
to keep replies short by leaving things out rather than compressing what
is left, to skip stock openers and closers in any language, and to keep
errors, failing test output, security warnings and caveats the user must
act on in full. A format the user asks for overrides it.
Decisions a reviewer may want to check:
- Host only. Every agent under `agents/` except raven-research renders
this identity, and each carries its own conduct for how it reports. The
section renders through `_reply_style()`, which is empty in a process
the host launched, on the `RAVEN_SUBAGENT` signal `_subagent_note()`
already reads; in such a process the identity text is byte-identical to
`main`. The in-process sub-agent builds its own prompt and never renders
this identity.
- One English section for both reply languages. The language directive
above it still names the language, and the section says it does not
decide one.
- One home for the intent rule. Raven Guidelines already says "State
intent before tool calls"; the new bullet names that rule and adds only
that it is one sentence, said once, with no narration of each routine
tool call.
- The soul template now carries stance and voice only (have a view, know
when to stay quiet, ask only when the answer would change what you do,
no corporate filler), so it does not repeat the format rules. The agent
template drops its duplicate "Be concise, accurate, and friendly" line.
Template sync fills only missing files in Agent home, so both changes
reach new installs only.
- `tests/test_agent_loop_token_budget.py`: the `available_history >
127_000` bound had about 70 tokens of slack once the tool surface had
grown, so any host prompt growth tripped it. It moves to 126_000 with
the trade noted beside it, as the `reserved_tools` notes below it do.
System prompt growth still has no bound of its own.
Not covered: an agent under `agents/` started directly rather than by a
host has no `RAVEN_SUBAGENT` and renders the section, the same boundary
`_subagent_note()` has.
Measured with real one-shot turns (`raven agent`) on the default model,
openrouter/z-ai/glm-5.3-flash: six prompts (a simple question, small
talk, a bad idea to push back on, explaining a project, running a
failing check, an English question), three samples each, each sample in
a fresh Agent home with memory writes and outbound tools off. Before is
`main`, after is this branch. Means per reply:
```text
chars headers bullets bold emoji failing-check error kept
before (main) 699 1.8 4.0 5.8 1.9 3/3
after (branch) 490 0.1 2.6 2.6 0.0 3/3
```
Headers and emoji are effectively gone, bold falls by more than half and
bullets by about a third, and replies are 30% shorter. Every
failing-check reply still quotes the failure, `expected 12, got 9`. Two
things did not move. Replies to requests that used tools still end by
offering the next step about as often as before; on the failing check
that is asking before fixing what the user only asked to check.
Narration before tool calls fell on the failing check (341 to 203
characters) but not on the read-only request (51 to 71). Openers could
not be measured: this model used none on either side. One model and
three samples a cell; another model may move differently.
## Type
- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
```text
uv run --frozen --all-extras pytest tests/ -q -p no:randomly
7 failed, 27459 passed, 116 skipped
uv run --frozen --all-extras pytest tests/test_segments.py tests/test_agent_loop_subagent_role.py tests/test_agent_loop_token_budget.py tests/test_security_untrusted_context.py tests/test_i18n_prompts.py -q
108 passed
make lint-python All checks passed; 2161 files already formatted
make lint-imports Contracts: 10 kept, 0 broken
make lint-types All checks passed
make check-commits exit 0
scripts/check_source_language.py origin/main...HEAD exit 0
scripts/check_large_files.py origin/main...HEAD exit 0
pre-commit run --from-ref origin/main --to-ref HEAD exit 0, no file modified
```
The 7 failures are five proxy tests in
`tests/test_config_update_providers.py` (this machine exports an HTTP
proxy),
`tests/test_install_script.py::test_resolve_node_dir_answers_each_case_it_exists_for`
and
`tests/test_subagent_node_runtime.py::test_what_cannot_be_read_names_nothing`.
The same 7 ids fail with the change backed out on the same base; CI is
the second machine.
The three new tests in `tests/test_agent_loop_subagent_role.py` were
each checked against a mutant of `render.py`: dropping the section
reddens all three, removing the role gate the first, a stray newline on
either branch the second, and deleting the language clause the third.
With `RAVEN_SUBAGENT=1`, this branch's `identity_text` was compared with
`main`'s and is identical.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed
Docs box left blank: no user-facing document describes the identity text
or the soul template's contents. The Workspace Template entry in
`CONTEXT.md` calls `SOUL.md` the agent persona, which still holds.
## Risk
- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes
Prompt text only. The untrusted-content rule is unchanged and comes
first; the override clause covers formatting only. The host prompt grows
by about 260 tokens per turn, inside its stable prefix. Existing
installs keep their `soul.md` and `agent.md`, since template sync never
overwrites. To roll back, revert the squash commit; installs created
while it was live keep the new soul and agent files until those two are
deleted and re-seeded.
## Related Issues
N/A
---------
Co-authored-by: Claude (claude-opus-5-5[1m]) <noreply@anthropic.com>
217 lines
11 KiB
Python
217 lines
11 KiB
Python
"""How much of the context window a turn holds back for the answer.
|
|
|
|
A request names an output ceiling, so the reservation is that exact number: the
|
|
prompt and that reply have to fit the window together, and handing out more
|
|
means the sum is refused at request time -- a refusal whose recovery only
|
|
elides tool bodies, so a history grown on conversation dies there.
|
|
|
|
Which makes the *spelling* load-bearing, not only the arithmetic. The
|
|
reservation and the request have to resolve from the same model id, and the id
|
|
a request goes out under is not always the one it was configured with (see
|
|
`_wire_output_ceiling`). What the catalogue's implausible rows used to make of
|
|
this -- a ceiling equal to the window, leaving nothing for history -- is
|
|
handled upstream, where such a row is distrusted (see `providers.rates`).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
import raven.agent.harness.memory as budget_owner
|
|
from raven.agent.loop import AgentLoop
|
|
from raven.agent.loop.bundles import ToolWiring, TurnPolicy
|
|
from raven.providers.base import LLMProvider, LLMResponse, send_max_tokens
|
|
from raven.providers.binding import ModelBinding
|
|
|
|
|
|
class _StubProvider(LLMProvider):
|
|
def get_default_model(self) -> str:
|
|
return "stub"
|
|
|
|
async def chat(self, messages, tools=None, model=None, **kwargs) -> LLMResponse:
|
|
return LLMResponse(content="ok", finish_reason="stop")
|
|
|
|
|
|
@pytest.fixture
|
|
def workspace():
|
|
with tempfile.TemporaryDirectory() as td:
|
|
yield Path(td)
|
|
|
|
|
|
def _loop(workspace: Path, *, window: int, ceiling: int, monkeypatch, tools: ToolWiring | None = None) -> AgentLoop:
|
|
monkeypatch.setattr(budget_owner, "send_max_tokens", lambda *a, **k: ceiling)
|
|
agent = AgentLoop(
|
|
provider=_StubProvider(),
|
|
workspace=workspace,
|
|
model="stub",
|
|
policy=TurnPolicy(max_iterations=2),
|
|
tools=tools if tools is not None else ToolWiring(restrict_to_workspace=True),
|
|
)
|
|
# The window is the binding's, so the fixture sets it where it lives
|
|
# rather than on the loop -- which no longer has one of its own.
|
|
agent._default_binding = ModelBinding(agent._default_binding.provider, agent._default_binding.model, window)
|
|
return agent
|
|
|
|
|
|
def test_the_reservation_reads_the_id_the_request_goes_out_under(workspace, monkeypatch) -> None:
|
|
"""The reservation and the request have to resolve from one spelling.
|
|
|
|
Measured on the deck agent's own model: configured `z-ai/glm-5.3-flash` has
|
|
no catalogue row under that name, so the reservation fell to half the
|
|
default window (32768) while the request -- built from the wire spelling
|
|
`openrouter/z-ai/glm-5.3-flash`, which does have one -- carried 64000. The
|
|
loop then handed out a prompt sized against a reply twice as large as it
|
|
had reserved for.
|
|
"""
|
|
import litellm
|
|
|
|
from raven.providers import rates
|
|
|
|
# Nothing in LiteLLM under either spelling, which is the deck model's real
|
|
# situation: the declaration lives only in OpenRouter's catalogue, and that
|
|
# tier answers for an id naming OpenRouter and for no other.
|
|
monkeypatch.setattr(litellm, "model_cost", {})
|
|
monkeypatch.setattr(litellm, "get_model_info", lambda *a, **k: {})
|
|
rates.reset_openrouter_cache()
|
|
monkeypatch.setattr(
|
|
rates,
|
|
"_OPENROUTER_CACHE",
|
|
{"vendor/thing": {"context_length": 400_000, "max_completion_tokens": 8_000}},
|
|
raising=False,
|
|
)
|
|
monkeypatch.setattr(rates, "_OPENROUTER_CACHE_TIME", 0.0, raising=False)
|
|
|
|
class _PrefixingProvider(_StubProvider):
|
|
def wire_model_id(self, model: str) -> str:
|
|
return model if model.startswith("openrouter/") else f"openrouter/{model}"
|
|
|
|
agent = AgentLoop(
|
|
provider=_PrefixingProvider(),
|
|
workspace=workspace,
|
|
model="vendor/thing",
|
|
policy=TurnPolicy(max_iterations=2),
|
|
tools=ToolWiring(restrict_to_workspace=True),
|
|
)
|
|
|
|
assert agent._wire_output_ceiling() == 8_000, "the wire spelling reaches the catalogue, so it answers"
|
|
assert send_max_tokens(None, "vendor/thing", allow_fetch=False) == rates.MAX_OUTPUT_TOKENS_PER_ITERATION, (
|
|
"the configured spelling reaches nothing, so no declaration bounds it and the per-iteration bound answers"
|
|
)
|
|
|
|
|
|
def test_a_ceiling_as_large_as_the_window_still_leaves_room_for_history(workspace, monkeypatch) -> None:
|
|
"""Measured before this bound: `openrouter/anthropic/claude-haiku-4.5`
|
|
reports a 200000 ceiling on a 200000 window, so `available_history` was
|
|
exactly 0 -- no history fits in the budget, on every turn.
|
|
"""
|
|
budget = _loop(workspace, window=200_000, ceiling=64_000, monkeypatch=monkeypatch)._make_token_budget()
|
|
|
|
assert budget.reserved_output == 64_000, "what the reply may actually use"
|
|
# Two bounds, because two different things were being guarded through one
|
|
# number and the tighter of them rode on where the repo is checked out.
|
|
#
|
|
# `available_history` is the docstring's subject: the measured 0 that
|
|
# started this, history squeezed to nothing by an honest-but-huge ceiling.
|
|
# A loose bound is the right shape for it -- `reserved_system` embeds the
|
|
# workspace path, so this figure moves with the length of a temp directory:
|
|
# measured 129_090 / 129_060 / 129_035 at path lengths 22 / 62 / 121.
|
|
#
|
|
# Lowered from 127_000 (measured 127_067, ~70 to spare once the tool surface
|
|
# below had grown) when the host prompt gained its `## How you reply`
|
|
# section: ~260 tokens, measured 126_823 here. What was trimmed first: the
|
|
# first draft cost ~390; its worked examples went, and so did a rule the
|
|
# Raven Guidelines above it already state. Still loose, as this bound is
|
|
# meant to be: the regression it guards is history at zero.
|
|
assert budget.available_history > 126_000, "an honest ceiling must not squeeze history toward zero"
|
|
# `reserved_tools` is what the old 129_000 bound was really watching, and it
|
|
# is invariant across those same three paths: paid on every turn of every
|
|
# conversation. Asserted directly so a grown tool description trips it for
|
|
# that reason rather than because a worktree sits deeper than the one this
|
|
# was measured on. Trim somewhere before raising it, and say what was
|
|
# traded.
|
|
#
|
|
# Raised from 6_000 (measured 5773) when the eight `browser_*` tools were
|
|
# admitted: their schemas cost ~1100 tokens, measured 7115 here. What was
|
|
# traded for it, and what was trimmed first: every description was cut to
|
|
# the facts a caller cannot infer from the parameters, and the hand-off
|
|
# note (a login or payment is the user's to do) now rides on
|
|
# `browser_navigate` alone rather than on three tools. The remainder is the
|
|
# surface itself -- one tool per verb, because the permission gate rules by
|
|
# tool name and a single `browser(action=...)` tool would put clicking and
|
|
# reading on one tier. The bill is only paid where the browser extra is
|
|
# installed: without playwright the tools report themselves unconfigured
|
|
# and never reach the schema.
|
|
#
|
|
# Raised from 7_400 (measured 7407) when `raven_config` was admitted. What
|
|
# was traded: its first draft listed every action and cost ~540 tokens; the
|
|
# schema now names no setting and no action beyond the enum, and the how-to
|
|
# lives in the raven-self-config skill, read on demand -- ~130 tokens left.
|
|
assert budget.reserved_tools < 7_500, f"tool surface grew: {budget.reserved_tools} tokens reserved"
|
|
|
|
|
|
def test_an_honest_but_large_ceiling_does_not_eat_the_window(workspace, monkeypatch) -> None:
|
|
"""`z-ai/glm-4.6` really does allow 131000 output tokens on a 202800 window.
|
|
|
|
Nothing about that number is wrong; reserving all of it is. The turn that
|
|
spends its whole ceiling on one answer is rare, and paying for it on every
|
|
other turn costs two thirds of the history.
|
|
"""
|
|
budget = _loop(workspace, window=202_800, ceiling=131_000, monkeypatch=monkeypatch)._make_token_budget()
|
|
|
|
assert budget.reserved_output == 131_000, "the model really can emit this much"
|
|
# 60_000 rather than 65_000: the system prompt embeds the workspace path,
|
|
# so the measured figure rides a few dozen tokens with tmp-path length.
|
|
# The bound guards history keeping most of the leftover window, not an
|
|
# exact split, so it stands clear of the boundary instead of on it.
|
|
assert budget.available_history > 60_000
|
|
|
|
|
|
def test_a_ceiling_below_the_share_is_reserved_in_full(workspace, monkeypatch) -> None:
|
|
"""The bound is a cap, not a target. gpt-4o's 16384 on a 128000 window is
|
|
well under the share, and reserving the share instead would hold back
|
|
15616 tokens the model cannot use.
|
|
"""
|
|
budget = _loop(workspace, window=128_000, ceiling=16_384, monkeypatch=monkeypatch)._make_token_budget()
|
|
|
|
assert budget.reserved_output == 16_384
|
|
|
|
|
|
def test_a_configured_window_smaller_than_the_model_s_still_leaves_a_budget(workspace, monkeypatch) -> None:
|
|
"""A user who pins a small context window must not end up with a negative
|
|
one: the ceiling is the model's, and it can exceed a window chosen by hand.
|
|
"""
|
|
budget = _loop(workspace, window=32_000, ceiling=64_000, monkeypatch=monkeypatch)._make_token_budget()
|
|
|
|
assert budget.reserved_output == 32_000, "never more than the window it is carved from"
|
|
assert budget.available_history == 0
|
|
|
|
|
|
def test_what_enabling_a2a_costs_the_tool_surface(workspace, monkeypatch) -> None:
|
|
"""`a2a_send` registers only with a peer configured, so the ceiling test above
|
|
measures a face that does not carry it. That makes the feature's real cost
|
|
invisible to the bound, which is the opposite of what that bound is for -- so
|
|
the cost is measured here instead of going unmeasured.
|
|
|
|
What is asserted is the increment, because that is what this feature controls.
|
|
What is NOT asserted, deliberately: the peer-configured total sits above the
|
|
6_000 line the test above holds for the default face. Whether that line moves
|
|
is a question about the whole tool surface and belongs to whoever owns it, not
|
|
to the feature that happened to arrive when the headroom had run out.
|
|
"""
|
|
from raven.config.schema import A2aConfig, A2aPeerConfig
|
|
|
|
peers = ToolWiring(
|
|
restrict_to_workspace=True,
|
|
a2a_config=A2aConfig(peers=[A2aPeerConfig(origin="https://peer.example.com")]),
|
|
)
|
|
plain = _loop(workspace, window=200_000, ceiling=64_000, monkeypatch=monkeypatch)._make_token_budget()
|
|
enabled = _loop(
|
|
workspace, window=200_000, ceiling=64_000, monkeypatch=monkeypatch, tools=peers
|
|
)._make_token_budget()
|
|
|
|
cost = enabled.reserved_tools - plain.reserved_tools
|
|
assert 0 < cost < 200, f"a2a_send's schema now costs {cost} tokens on every turn of every conversation"
|