Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(anthropic): configurable CacheMarkerPolicy for cache_control placement

xf gong26fba41e39aa
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index 7d848ad..efdf0d3 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import asyncio
import time
-from typing import Any, Literal
+from typing import Any, Literal, Protocol, runtime_checkable
from cubepi.providers.base import (
AssistantMessage,
@@ -29,17 +29,47 @@ from cubepi.providers.models import clamp_thinking_level
CacheRetention = Literal["short", "long", "none"]
+@runtime_checkable
+class CacheMarkerPolicy(Protocol):
+ """Policy controlling where Anthropic cache_control markers are inserted.
+
+ See `cubepi/docs/specs/2026-05-13-cubepi-cubebox-readiness-design.md` § D3.
+ """
+
+ def mark_system(self) -> bool: ...
+ def mark_last_tool(self) -> bool: ...
+ def message_breakpoint_indices(
+ self,
+ messages: list[Message],
+ ) -> list[int]: ...
+
+
+class DefaultCacheMarkerPolicy:
+ """Preserves cubepi v0.2 behavior: system + last message + last tool."""
+
+ def mark_system(self) -> bool:
+ return True
+
+ def mark_last_tool(self) -> bool:
+ return True
+
+ def message_breakpoint_indices(self, messages: list[Message]) -> list[int]:
+ return [len(messages) - 1] if messages else []
+
+
class AnthropicProvider:
def __init__(
self,
*,
api_key: str | None = None,
cache_retention: CacheRetention = "short",
+ cache_policy: CacheMarkerPolicy | None = None,
) -> None:
import anthropic
self._client = anthropic.AsyncAnthropic(api_key=api_key)
self._cache_retention = cache_retention
+ self._cache_policy: CacheMarkerPolicy = cache_policy or DefaultCacheMarkerPolicy()
async def stream(
self,
@@ -57,7 +87,8 @@ class AnthropicProvider:
cache_control = self._get_cache_control()
api_messages = [self._convert_message(m) for m in messages]
if cache_control:
- self._apply_message_cache_control(api_messages, cache_control)
+ indices = self._cache_policy.message_breakpoint_indices(messages)
+ self._apply_indices_markers(api_messages, indices, cache_control)
max_tokens, thinking_budget = adjust_max_tokens_for_thinking(
base_max_tokens=model.max_tokens,
@@ -76,12 +107,16 @@ class AnthropicProvider:
{
"type": "text",
"text": system_prompt,
- **({"cache_control": cache_control} if cache_control else {}),
+ **(
+ {"cache_control": cache_control}
+ if cache_control and self._cache_policy.mark_system()
+ else {}
+ ),
}
]
if tools:
api_tools = [self._convert_tool(t) for t in tools]
- if cache_control and api_tools:
+ if cache_control and api_tools and self._cache_policy.mark_last_tool():
api_tools[-1]["cache_control"] = cache_control
kwargs["tools"] = api_tools
if thinking != "off" and thinking_budget > 0:
@@ -167,6 +202,26 @@ class AnthropicProvider:
cc["ttl"] = "1h"
return cc
+ def _apply_indices_markers(
+ self,
+ api_messages: list[dict[str, Any]],
+ indices: list[int],
+ cache_control: dict[str, str],
+ ) -> None:
+ """Apply cache_control to the last content block of each indexed message."""
+ for idx in indices:
+ if 0 <= idx < len(api_messages):
+ msg = api_messages[idx]
+ content = msg.get("content")
+ if isinstance(content, list) and content:
+ last_block = content[-1]
+ if isinstance(last_block, dict):
+ content[-1] = {**last_block, "cache_control": cache_control}
+ elif isinstance(content, str):
+ msg["content"] = [
+ {"type": "text", "text": content, "cache_control": cache_control}
+ ]
+
@staticmethod
def _apply_message_cache_control(
api_messages: list[dict[str, Any]],
diff --git a/tests/providers/test_anthropic_cache_policy.py b/tests/providers/test_anthropic_cache_policy.py
new file mode 100644
index 0000000..e4dc1b1
--- /dev/null
+++ b/tests/providers/test_anthropic_cache_policy.py
@@ -0,0 +1,107 @@
+"""AnthropicProvider configurable cache_policy tests (D3)."""
+
+import pytest
+
+from cubepi.providers.anthropic import (
+ AnthropicProvider,
+ CacheMarkerPolicy,
+ DefaultCacheMarkerPolicy,
+)
+from cubepi.providers.base import Message, TextContent, UserMessage
+
+
+def test_default_policy_marks_system() -> None:
+ assert DefaultCacheMarkerPolicy().mark_system() is True
+
+
+def test_default_policy_marks_last_tool() -> None:
+ assert DefaultCacheMarkerPolicy().mark_last_tool() is True
+
+
+def test_default_policy_indices_picks_last() -> None:
+ p = DefaultCacheMarkerPolicy()
+ msgs: list[Message] = [
+ UserMessage(content=[TextContent(text="a")]),
+ UserMessage(content=[TextContent(text="b")]),
+ ]
+ assert p.message_breakpoint_indices(msgs) == [1]
+
+
+def test_default_policy_indices_empty() -> None:
+ assert DefaultCacheMarkerPolicy().message_breakpoint_indices([]) == []
+
+
+def test_provider_uses_default_policy_when_none_passed() -> None:
+ p = AnthropicProvider(api_key="x")
+ assert isinstance(p._cache_policy, DefaultCacheMarkerPolicy)
+
+
+def test_provider_uses_custom_policy() -> None:
+ class _NoSystem:
+ def mark_system(self) -> bool:
+ return False
+ def mark_last_tool(self) -> bool:
+ return False
+ def message_breakpoint_indices(self, messages):
+ return []
+
+ p = AnthropicProvider(api_key="x", cache_policy=_NoSystem())
+ assert p._cache_policy.mark_system() is False
+
+
+def test_apply_indices_markers_marks_specified_indices() -> None:
+ """Marker is applied to the last content block of each indexed message."""
+ p = AnthropicProvider(api_key="x")
+ api_messages = [
+ {"role": "user", "content": [{"type": "text", "text": "a"}]},
+ {"role": "user", "content": [{"type": "text", "text": "b"}]},
+ ]
+ p._apply_indices_markers(api_messages, indices=[0], cache_control={"type": "ephemeral"})
+ assert api_messages[0]["content"][-1].get("cache_control") == {"type": "ephemeral"}
+ # message 1 untouched
+ assert "cache_control" not in api_messages[1]["content"][-1]
+
+
+def test_apply_indices_markers_converts_string_content() -> None:
+ """When a message has string content, _apply_indices_markers converts to block list and marks it."""
+ p = AnthropicProvider(api_key="x")
+ api_messages = [
+ {"role": "user", "content": "plain string"},
+ ]
+ p._apply_indices_markers(api_messages, indices=[0], cache_control={"type": "ephemeral"})
+ assert isinstance(api_messages[0]["content"], list)
+ assert api_messages[0]["content"][0] == {
+ "type": "text",
+ "text": "plain string",
+ "cache_control": {"type": "ephemeral"},
+ }
+
+
+async def test_custom_policy_drives_message_marker_placement() -> None:
+ """Custom policy that marks index 0 should result in marker on first message, not last."""
+ class _FirstOnly:
+ def mark_system(self) -> bool:
+ return False
+ def mark_last_tool(self) -> bool:
+ return False
+ def message_breakpoint_indices(self, messages):
+ return [0] if messages else []
+
+ p = AnthropicProvider(api_key="x", cache_policy=_FirstOnly())
+ msgs: list[Message] = [
+ UserMessage(content=[TextContent(text="zero")]),
+ UserMessage(content=[TextContent(text="one")]),
+ ]
+ api_msgs = [p._convert_message(m) for m in msgs]
+ p._apply_indices_markers(api_msgs, indices=[0], cache_control={"type": "ephemeral"})
+
+ first_blocks = api_msgs[0]["content"]
+ assert isinstance(first_blocks, list)
+ assert first_blocks[-1].get("cache_control") == {"type": "ephemeral"}
+
+ second_blocks = api_msgs[1]["content"]
+ if isinstance(second_blocks, list) and second_blocks:
+ last = second_blocks[-1]
+ if isinstance(last, dict):
+ assert "cache_control" not in last