feat: ephemeral per-request context parts for capabilities and hooks

Closed
DO
2mo ago
+320-0

What

A blessed seam for capabilities and hooks to contribute ephemeral, per-request context the model sees but that is never persisted into history โ€” budget lines, staleness notices, harness-state notes, cross-model labels. Core blesses only one ephemeral channel today (instructions); system-reminder-style content that should sit adjacent to the conversation has no supported seam, so harness capabilities (Planning, StalenessTracker) each hand-roll it via wrap_model_request + tail-append + CachePoint, and getting it wrong either persists synthetic parts into user-owned history or busts the cache prefix.

How

Investigation (code truth): in _agent_graph._prepare_request, before_model_request edits to messages are written back to ctx.state.message_history โ€” i.e. they persist. Only the later post-clean outgoing list is non-persisted, which is why capabilities hand-roll the notice channel.

The seam:

  • ModelRequestContext.ephemeral_parts: list[UserContent] + add_ephemeral_part(content: str | UserContent), called from before_model_request.
  • Core renders the parts once, in the shared _prepare_request, after the durable history is written back and messages are cleaned โ€” appending one trailing UserPromptPart (preceded by a CachePoint) to a non-persisted copy of the outgoing messages. Single render site covering both run and run_stream; short-circuits when empty.

Deliberate scope

  • Contribution via before_model_request (natural request-shaping hook with full RunContext); migrating the harness capabilities onto it is a scoped follow-up.
  • Auto-inserts a CachePoint (ttl 5m) before the ephemeral tail so the stable prefix stays cacheable (mirrors Planning); CachePoint is safely dropped by non-caching providers.
  • Core imposes no semantic delimiter โ€” callers frame their own (<system-reminder> etc.), avoiding double-wrapping the harness's existing tags.

Tests

5 new cases: content reaches the provider behind a CachePoint while all_messages() stays byte-identical; deterministic multi-contributor ordering; the Hooks seam + non-str UserContent; run_stream; empty = untouched request. Docs: a "two ephemeral channels" section in docs/hooks.md. 100% coverage.

๐Ÿค– Generated with Claude Code