Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent): inject runtime state awareness into conversation context (#2134)
DavdGao29792cd92136
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex fa2041103..408fa76cf 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -107,7 +107,7 @@ repos:--max-nested-blocks=7,--max-statements=100,--max-returns=10,- --max-module-lines=3000,+ --max-module-lines=5000,]- repo: https://github.com/regebro/pyromarev: "5.0"diff --git a/pyproject.toml b/pyproject.tomlindex 881146cec..887ad6305 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -43,6 +43,8 @@ dependencies = ["tree_sitter","tree_sitter_bash","jsonschema",+ # The IANA timezone database, which is absent on Windows and slim images+ "tzdata",][project.optional-dependencies]diff --git a/src/agentscope/agent/__init__.py b/src/agentscope/agent/__init__.pyindex 39a93b8b5..e3c134d6d 100644--- a/src/agentscope/agent/__init__.py+++ b/src/agentscope/agent/__init__.py@@ -1,6 +1,12 @@# -*- coding: utf-8 -*-"""Initialize the agent module."""from ._agent import Agent-from ._config import ContextConfig, ModelConfig, ReActConfig+from ._config import ContextConfig, InjectionConfig, ModelConfig, ReActConfig-__all__ = ["Agent", "ContextConfig", "ModelConfig", "ReActConfig"]+__all__ = [+ "Agent",+ "ContextConfig",+ "InjectionConfig",+ "ModelConfig",+ "ReActConfig",+]diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex d85ce1c91..859fb3f0d 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -1,10 +1,14 @@# -*- coding: utf-8 -*-"""The unified agent class in AgentScope library."""import asyncio+import collectionsimport inspect+import refrom asyncio import Queuefrom copy import deepcopy+from datetime import datetime, timezone, tzinfo+from zoneinfo import ZoneInfo, ZoneInfoNotFoundErrorfrom typing import (Any,AsyncGenerator,@@ -16,7 +20,7 @@ from typing import (import jsonschema-from ._config import ContextConfig, ReActConfig, ModelConfig+from ._config import ContextConfig, ReActConfig, ModelConfig, InjectionConfigfrom ..state import AgentStatefrom ._utils import _ToolCallBatchfrom .._logging import logger@@ -54,6 +58,7 @@ from ..event import (ExceedMaxItersEvent,ReplyFinishedReason,UserInterruptEvent,+ HintBlockEvent,)from ..exception import AgentOrientedExceptionfrom ..model import (@@ -99,6 +104,21 @@ else:MiddlewareBase = Any+def _resolve_timezone(name: str) -> tzinfo:+ """Resolve the given timezone name, falling back to UTC when the name is+ invalid or the timezone database is unavailable, e.g. on Windows or slim+ images without the ``tzdata`` package."""+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError):+ logger.warning(+ "Failed to resolve the timezone %s, fallback to UTC. Install the "+ "'tzdata' package if the timezone database is missing.",+ repr(name),+ )+ return timezone.utc++class Agent:"""The agent class."""@@ -115,6 +135,7 @@ class Agent:model_config: ModelConfig | None = None,context_config: ContextConfig | None = None,react_config: ReActConfig | None = None,+ injection_config: InjectionConfig | None = None,) -> None:"""Initialize the agent class in AgentScope.@@ -147,6 +168,10 @@ class Agent:compression.react_config (`ReActConfig | None`, optional):The config for the reasoning-acting loop.+ injection_config (`InjectionConfig | None`, optional):+ The runtime state injection config, which controls how the+ time, (plan) tasks and context usage are injected into the+ context to help the agent better reason and act."""self.name = nameself._system_prompt = system_prompt@@ -156,6 +181,8 @@ class Agent:self.model_config = model_config or ModelConfig()self.context_config = context_config or ContextConfig()self.react_config = react_config or ReActConfig()+ self.injection_config = injection_config or InjectionConfig()+ self._validate_configs()# The permission engineself._engine = PermissionEngine(self.state.permission_context)@@ -192,6 +219,39 @@ class Agent:_ for _ in middlewares if _.is_implemented("on_compress_context")]+ def _validate_configs(self) -> None:+ """Validate the config combinations that a single config class cannot+ check by itself.++ Raises:+ `ValueError`:+ If the reserved/buffer ratios don't leave room ahead of the+ context compression threshold.+ """+ if (+ self.context_config.reserve_ratio+ >= self.context_config.trigger_ratio+ ):+ raise ValueError(+ "The 'reserve_ratio' of the context config must be smaller "+ "than its 'trigger_ratio', got "+ f"{self.context_config.reserve_ratio} and "+ f"{self.context_config.trigger_ratio}.",+ )++ if (+ self.injection_config.inject_runtime_state+ and self.injection_config.context_buffer_ratio+ >= self.context_config.trigger_ratio+ ):+ raise ValueError(+ "The 'context_buffer_ratio' of the injection config must be "+ "smaller than the 'trigger_ratio' of the context config, so "+ "that the context length is injected before the compression, "+ f"got {self.injection_config.context_buffer_ratio} and "+ f"{self.context_config.trigger_ratio}.",+ )+# =======================================================================# Agent public methods# =======================================================================@@ -766,6 +826,10 @@ class Agent:# Compressed the memory if needed before reasoningawait self.compress_context()+ # Inject runtime state if needed before reasoning+ async for evt in self._inject_runtime_state():+ yield evt+# Perform reasoninginterrupted = Falseasync for evt in self._reasoning():@@ -924,6 +988,249 @@ class Agent:yield end_event+ async def _inject_runtime_state(+ self,+ ) -> AsyncGenerator[HintBlockEvent, None]:+ """Inject the current runtime state (time, plan tasks and context+ usage) into the conversation context as a ``HintBlock``, so the agent+ stays aware of the information that changes across turns/replies.++ .. note:: The injection is **not** ephemeral. It is appended to the+ persistent context on purpose, so the agent can perceive how time+ elapses and what it did at each step, building a sense of time.++ .. note:: We attach a ``HintBlock`` instead of mutating the system+ prompt, so that prompt caching still works while the agent remains+ aware of the changing time / tasks / context.++ .. note:: Only information that *changes* within a conversation is+ injected here. Fixed information should live in the system prompt.++ The injection timing is decided per dimension:++ - **Time**: injected when (1) no time is recorded in the context (i.e.+ the first reply or right after a context compression), or (2) the+ elapsed time since the recorded one exceeds+ ``injection_config.time_interval`` hours. The injected time is the+ wall-clock time of ``injection_config.timezone``, and the timezone+ is injected next to it so that the elapsed time is still correct+ when the configured timezone changes within a conversation.+ - **Plan tasks**: injected when there are pending or in-progress tasks+ while the context contains neither task-related tool calls (e.g.+ they have been compressed away) nor a previous tasks injection.+ - **Context**: injected at the first iteration of a reply when the+ current input tokens are within+ ``injection_config.context_buffer_ratio`` of the compression+ threshold, letting the agent perceive that a compression is near.+ This dimension is evaluated independently of the two above.++ The user defined ``injection_config.extra_fields`` are attached to+ every injection, but never trigger one by themselves.++ Yields:+ `HintBlockEvent`:+ Emitted when a runtime-state hint is injected and+ ``injection_config.emit_hint_event`` is enabled.+ """+ if not self.injection_config.inject_runtime_state:+ return++ injections: dict = {}++ # The wall-clock time in the configured timezone. It's kept timezone+ # aware for the elapsed time calculation, while ``time_format`` decides+ # whether the timezone is carried in the injected text.+ now = datetime.now(_resolve_timezone(self.injection_config.timezone))++ # A fixed source used to detect existing injection+ injection_source = self.injection_config.injection_source++ # =====================================================================+ # Step 1: Analyze the current context+ # - The latest injection that records a time (if any)+ # - If the agent is already aware of the uncompleted tasks+ # =====================================================================+ task_status: dict = collections.defaultdict(int)+ for task in self.state.tasks_context.tasks:+ task_status[task.state] += 1++ has_uncompleted_tasks = (+ task_status["pending"] > 0 or task_status["in_progress"] > 0+ )++ # The text of the newest injection that records a time. An injection+ # only carries the fields triggered at that moment, so the newest one+ # doesn't necessarily record a time.+ last_time_text: str | None = None++ # The agent is aware of the tasks when the context contains the task+ # related tool calls or a previous tasks injection. Without uncompleted+ # tasks the flag is never used, so skip the detection entirely.+ aware_of_tasks = not has_uncompleted_tasks++ for msg in reversed(self.state.context):+ if last_time_text is not None and aware_of_tasks:+ # Both dimensions are settled, no need to scan the older+ # context+ break++ if msg.role != "assistant":+ continue++ for block in reversed(msg.content):+ if (+ isinstance(block, HintBlock)+ and block.source == injection_source+ ):+ if isinstance(block.hint, str):+ text = block.hint+ else:+ text = "".join(+ _.text+ for _ in block.hint+ if isinstance(_, TextBlock)+ )++ if last_time_text is None and "<current-time>" in text:+ last_time_text = text+ if not aware_of_tasks and "<tasks>" in text:+ aware_of_tasks = True++ elif (+ isinstance(block, ToolCallBlock)+ and block.name in self.injection_config.task_tool_names+ ):+ aware_of_tasks = True++ # =====================================================================+ # Step 2: Check Time Injection+ # =====================================================================+ # No time recorded in the context, e.g. the first reply or right after+ # a context compression, so inject to be safe+ inject_time = True+ if last_time_text is not None:+ # Extract the recorded time from the injection, e.g.+ # <current-time>2026-07-01T12:00:00</current-time>+ match = re.search(+ r"<current-time>(.*?)</current-time>",+ last_time_text,+ )+ last_time = None+ if match is not None:+ try:+ last_time = datetime.strptime(+ match.group(1).strip(),+ self.injection_config.time_format,+ )+ except ValueError:+ # Fail to parse the recorded time, e.g. the time format has+ # changed, so inject again to be safe+ last_time = None++ if last_time is not None:+ if last_time.tzinfo is None:+ # The recorded time is the wall-clock time of the timezone+ # recorded next to it, e.g.+ # <timezone>Asia/Shanghai</timezone>. Restore it so that+ # the comparison holds even if the configured timezone has+ # changed since then.+ match_tz = re.search(+ r"<timezone>(.*?)</timezone>",+ last_time_text,+ )+ last_time = last_time.replace(+ tzinfo=_resolve_timezone(+ match_tz.group(1).strip()+ if match_tz+ else self.injection_config.timezone,+ ),+ )++ elapsed_hours = (now - last_time).total_seconds() / 3600+ # A negative elapsed time means the recorded time is in the+ # future, e.g. the machine clock went backwards, so inject+ # again to be safe+ inject_time = not (+ 0 <= elapsed_hours <= self.injection_config.time_interval+ )++ if inject_time:+ injections["current-time"] = now.strftime(+ self.injection_config.time_format,+ )+ injections["timezone"] = self.injection_config.timezone++ # =====================================================================+ # Step 3: Check Plan Tasks+ # =====================================================================+ # If exists uncompleted tasks and the agent isn't aware of them, e.g.+ # the task related tool calls have been compressed away, so that the+ # same reminder isn't repeated on every iteration+ if has_uncompleted_tasks and not aware_of_tasks:+ injections["tasks"] = (+ f"You have {task_status['in_progress']} in-progress tasks "+ f"and {task_status['pending']} pending tasks. "+ f"Use `TaskList` to view them if you don't know."+ )++ # =====================================================================+ # Step 4: Context Length+ # =====================================================================+ # The context length is checked independently of the dimensions above,+ # and only at the beginning of a reply, where the context has just+ # grown by the new input+ if self.state.cur_iter == 0:+ # Count the current tokens+ kwargs = await self._prepare_model_input()+ input_tokens = await self.model.count_tokens(**kwargs)++ trigger_tokens = int(+ self.context_config.trigger_ratio * self.model.context_size,+ )++ if input_tokens > (+ max(+ 0.0,+ self.context_config.trigger_ratio+ - self.injection_config.context_buffer_ratio,+ )+ * self.model.context_size+ ):+ # To trigger memory compress+ injections["context-length"] = (+ f"Your current context contains {input_tokens} "+ f"tokens. When reaching {trigger_tokens} tokens, "+ f"your context will be compressed."+ )++ if injections:+ # The user defined fields, which don't trigger an injection by+ # themselves+ injections.update(self.injection_config.extra_fields)++ hint_block = HintBlock(+ source=injection_source,+ # Use replace instead of format, so that the other curly+ # braces in the template are kept as-is+ hint=self.injection_config.template.replace(+ "{runtime_state}",+ "\n".join(+ f"<{k}>{v}</{k}>" for k, v in injections.items()+ ),+ ),+ )+ self.state.append_context(+ self.name,+ [hint_block],+ )+ if self.injection_config.emit_hint_event:+ yield HintBlockEvent(+ reply_id=self.state.reply_id,+ block_id=hint_block.id,+ source=hint_block.source,+ hint=hint_block.hint,+ )+async def _reasoning(self,tool_choice: ToolChoice | None = None,diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.pyindex b9e6e55bd..f40f266d8 100644--- a/src/agentscope/agent/_config.py+++ b/src/agentscope/agent/_config.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-"""The agent config classes."""-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validatorfrom ..model import ChatModelBase@@ -139,6 +139,146 @@ class ContextConfig(BaseModel):"""The tool result limit to avoid tool result bursting."""+class InjectionConfig(BaseModel):+ """The state injection related configuration in AgentScope."""++ inject_runtime_state: bool = Field(+ title="Inject Runtime State",+ description=(+ "Inject the runtime state to context, including current time,"+ "tasks state, context length, etc."+ ),+ default=True,+ )+ """Whether to inject the runtime state to context, including current time,+ tasks state, context length, etc."""++ timezone: str = Field(+ title="Timezone",+ default="UTC",+ description=(+ "The injected timezone. e.g. 'America/New_York' or "+ "'Asia/Shanghai'."+ ),+ )+ """The timezone to inject into the context, follow the standard timezone+ database format, e.g. 'America/New_York' or 'Asia/Shanghai'."""++ time_format: str = Field(+ title="Time Format",+ default="%Y-%m-%dT%H:%M:%S",+ description=(+ "The format to inject and parse the time information, which must "+ "round-trip a full timestamp, i.e. carry the date part. A "+ "time-only format such as '%H:%M:%S' makes the parsed time fall "+ "back to year 1900, so that the time is injected in every "+ "iteration."+ ),+ )+ """The format to inject and parse the time information, which must carry+ the date part to round-trip a full timestamp."""++ time_interval: float = Field(+ title="Time Interval",+ default=0.5,+ ge=0,+ description=(+ "The minimum time interval in hours from the last injection to "+ "trigger new time injection"+ ),+ )+ """The minimum elapsed time in **hours** from the recorded time to trigger+ a new time injection."""++ context_buffer_ratio: float = Field(+ title="Context Buffer",+ default=0.2,+ ge=0,+ le=1,+ description=(+ "The buffer that will activate context length injection before "+ "context compression, which should be smaller than the "+ "'trigger_ratio' of the context config."+ ),+ )+ """The buffer ahead of the compression threshold, e.g. with a trigger ratio+ of 0.8 and a buffer of 0.2, the context length is injected once the input+ tokens exceed 60% of the model context size."""++ template: str = Field(+ title="Template",+ default="""<system-reminder>Treat the following as the ground truth \+at this point of the conversation. Anything stated earlier is outdated, and a \+later reminder, if any, supersedes this one:+{runtime_state}+</system-reminder>""",+ description=(+ "The template to wrap the injected runtime state, where the "+ "'{runtime_state}' placeholder will be replaced by the injected "+ "fields."+ ),+ )+ """The template to wrap the injected runtime state, which must contain the+ ``{runtime_state}`` placeholder."""++ @field_validator("template")+ @classmethod+ def _check_template(cls, value: str) -> str:+ """Ensure the template won't silently drop the injected fields."""+ if "{runtime_state}" not in value:+ raise ValueError(+ "The injection template must contain the '{runtime_state}' "+ f"placeholder, got {value!r}.",+ )+ return value++ injection_source: str = Field(+ title="Injection Source",+ default='{"label": "System", "sublabel": "Runtime State"}',+ description=(+ "The source of the injected hint block, which is also used to "+ "identify the previous injections within the context."+ ),+ )+ """The source of the injected hint block, used to identify the agent's own+ injections when scanning the context."""++ task_tool_names: list[str] = Field(+ title="Task Tool Names",+ default_factory=lambda: [+ "TaskCreate",+ "TaskGet",+ "TaskList",+ "TaskUpdate",+ ],+ description=(+ "The names of the task related tools. Their presence in the "+ "context suppresses the tasks injection."+ ),+ )+ """The names of the task related tools, whose tool calls in the context+ indicate the agent is already aware of the tasks."""++ extra_fields: dict[str, str] = Field(+ title="Extra Fields",+ default_factory=dict,+ description=(+ "The extra fields to inject, which will be wrapped into the "+ "'<{key}>{value}</{key}>' format."+ ),+ )+ """The user defined fields to inject, which are attached to the injection+ without triggering one by themselves."""++ emit_hint_event: bool = Field(+ title="Emit Hint Event",+ default=True,+ description=(+ "If emit the HintBlockEvent when runtime state injection happens."+ ),+ )++class ReActConfig(BaseModel):"""The reasoning related configuration"""diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex 1bfe26c94..d3f9f07c7 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -5,7 +5,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, ContextConfig, InjectionConfigfrom agentscope.model import ChatResponsefrom agentscope.tool import (ToolBase,@@ -110,6 +110,9 @@ class AgentBasicTest(IsolatedAsyncioTestCase):system_prompt="You are a helpful assistant.",model=self.model,toolkit=Toolkit(),+ # The runtime state injection is covered by agent_injection_test,+ # turn it off here to keep the event assertions focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)def _get_event_base(self, reply_id: str) -> dict:@@ -153,10 +156,12 @@ class AgentBasicTest(IsolatedAsyncioTestCase):self.assertIsNot(agent_1.model_config, agent_2.model_config)self.assertIsNot(agent_1.context_config, agent_2.context_config)self.assertIsNot(agent_1.react_config, agent_2.react_config)+ self.assertIsNot(agent_1.injection_config, agent_2.injection_config)agent_1.model_config.max_retries = 3agent_1.context_config.tool_result_limit = 123agent_1.react_config.max_iters = 2+ agent_1.injection_config.timezone = "Asia/Shanghai"self.assertNotEqual(agent_1.model_config.max_retries,@@ -170,6 +175,33 @@ class AgentBasicTest(IsolatedAsyncioTestCase):agent_1.react_config.max_iters,agent_2.react_config.max_iters,)+ self.assertNotEqual(+ agent_1.injection_config.timezone,+ agent_2.injection_config.timezone,+ )++ async def test_inconsistent_ratios_are_rejected(self) -> None:+ """The ratios across the context and injection configs must leave room+ ahead of the compression threshold."""+ with self.assertRaises(ValueError):+ Agent(+ name="agent",+ system_prompt="You are an agent.",+ model=MockModel(),+ context_config=ContextConfig(+ trigger_ratio=0.5,+ reserve_ratio=0.6,+ ),+ )++ with self.assertRaises(ValueError):+ Agent(+ name="agent",+ system_prompt="You are an agent.",+ model=MockModel(),+ context_config=ContextConfig(trigger_ratio=0.5),+ injection_config=InjectionConfig(context_buffer_ratio=0.5),+ )async def test_streaming_reasoning(self) -> None:"""Test the streaming model inference without tool calls generated,diff --git a/tests/agent_injection_test.py b/tests/agent_injection_test.pynew file mode 100644index 000000000..0a63d87fa--- /dev/null+++ b/tests/agent_injection_test.py@@ -0,0 +1,379 @@+# -*- coding: utf-8 -*-+"""Unit tests for the runtime state injection of the agent, i.e. the+``Agent._inject_runtime_state`` method."""+from datetime import datetime, tzinfo+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch++from pydantic import ValidationError++from utils import AnyString, MockModel++from agentscope.agent import Agent, InjectionConfig+from agentscope.message import HintBlock+from agentscope.state import Task+from agentscope.tool import Toolkit+++# The fixed source used by the agent to mark its own runtime-state injection.+INJECTION_SOURCE = '{"label": "System", "sublabel": "Runtime State"}'++# The frozen "now" used across the tests, so time-related assertions are+# deterministic.+FROZEN_NOW = datetime(2026, 7, 1, 12, 0, 0)+++class _FrozenDatetime(datetime):+ """A ``datetime`` subclass whose ``now`` always returns a fixed instant,+ while keeping the other classmethods (``strptime``/``strftime``) intact."""++ @classmethod+ def now( # type: ignore[override]+ cls,+ tz: tzinfo | None = None,+ ) -> datetime:+ """Return the frozen instant (optionally attached with ``tz``)."""+ if tz is not None:+ return FROZEN_NOW.replace(tzinfo=tz)+ return FROZEN_NOW+++class AgentInjectionTest(IsolatedAsyncioTestCase):+ """Test cases for the runtime state injection."""++ async def asyncSetUp(self) -> None:+ """Create a fresh agent with a mock model for each test."""+ self.model = MockModel(context_size=1000)+ self.agent = Agent(+ name="Friday",+ system_prompt="You are a helpful assistant.",+ model=self.model,+ toolkit=Toolkit(),+ injection_config=InjectionConfig(),+ )+ self.agent.state.reply_id = "reply-1"+ self.agent.state.cur_iter = 0++ # Freeze the wall-clock time for all the test cases+ patcher = patch("agentscope.agent._agent.datetime", _FrozenDatetime)+ patcher.start()+ self.addCleanup(patcher.stop)++ # ------------------------------------------------------------------ utils+ async def _run_injection(self) -> list:+ """Drive the async generator and collect the yielded events."""+ return [+ # pylint: disable=protected-access+ evt+ async for evt in self.agent._inject_runtime_state()+ ]++ def _add_injection(self, time_str: str, timezone: str = "UTC") -> None:+ """Append an existing runtime-state injection carrying ``time_str``,+ which is the wall-clock time of ``timezone``."""+ self.agent.state.append_context(+ self.agent.name,+ [+ HintBlock(+ source=INJECTION_SOURCE,+ hint=(+ f"<current-time>{time_str}</current-time>\n"+ f"<timezone>{timezone}</timezone>"+ ),+ ),+ ],+ )++ @staticmethod+ def _expected_event(hint: str, reply_id: str = "reply-1") -> dict:+ """Build the expected ``HintBlockEvent`` dump for the given hint."""+ return {+ "id": AnyString(),+ "created_at": AnyString(),+ "metadata": {},+ "type": "HINT_BLOCK",+ "reply_id": reply_id,+ "block_id": AnyString(),+ "source": INJECTION_SOURCE,+ "hint": hint,+ }++ @staticmethod+ def _expected_hint_block(hint: str) -> dict:+ """Build the expected persisted ``HintBlock`` dump."""+ return {+ "type": "hint",+ "hint": hint,+ "id": AnyString(),+ "source": INJECTION_SOURCE,+ }++ # ------------------------------------------------------------------ tests+ async def test_first_reply_triggers_time_injection(self) -> None:+ """The first reply (empty context) should trigger a time injection."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>\n"+ "</system-reminder>"+ )+ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )+ self.assertEqual(+ [self._expected_hint_block(expected_hint)],+ [_.model_dump() for _ in self.agent.state.context[-1].content],+ )++ async def test_long_interval_triggers_time_injection(self) -> None:+ """A stale last injection (long elapsed time) should re-inject, while a+ recent one should not."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>\n"+ "</system-reminder>"+ )+ # Avoid the context-length branch, which only runs on the first iter.+ self.agent.state.cur_iter = 1++ # Case 1: last injection was 6 hours ago -> re-inject.+ self._add_injection("2026-07-01T06:00:00")+ events = await self._run_injection()+ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ # Case 2: last injection was 10 minutes ago (< time_interval) -> skip.+ self.agent.state.context = []+ self._add_injection("2026-07-01T11:50:00")+ events = await self._run_injection()+ self.assertEqual([], events)++ async def test_injection_after_compression(self) -> None:+ """A recent injection should not re-inject, but once the context is+ compressed away, the next call should inject again."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>\n"+ "</system-reminder>"+ )+ self.agent.state.cur_iter = 1++ # There is a recent injection before compression -> no new injection.+ self._add_injection("2026-07-01T12:00:00")+ events = await self._run_injection()+ self.assertEqual([], events)++ # Simulate a compression that drops the old context (and injection).+ self.agent.state.context = []+ self.agent.state.summary = "A summary of the previous work."+ events = await self._run_injection()+ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ async def test_pending_task_triggers_injection(self) -> None:+ """Pending tasks without task-related tool calls in the context should+ trigger a tasks injection."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<tasks>You have 0 in-progress tasks and 1 pending tasks. "+ "Use `TaskList` to view them if you don't know.</tasks>\n"+ "</system-reminder>"+ )+ self.agent.state.cur_iter = 1+ # A recent injection so the time branch is not triggered.+ self._add_injection("2026-07-01T12:00:00")+ self.agent.state.tasks_context.tasks = [+ Task(+ subject="Write the report",+ description="Draft the quarterly report.",+ metadata={},+ state="pending",+ ),+ ]+ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ # The tasks reminder is already in the context -> no repeated injection+ events = await self._run_injection()+ self.assertEqual([], events)++ async def test_recorded_timezone_is_honored(self) -> None:+ """The recorded timezone should be used to restore the recorded time,+ so a changed ``timezone`` config doesn't distort the elapsed time."""+ self.agent.state.cur_iter = 1++ # The frozen now is 12:00 UTC, i.e. 20:00 in Shanghai. An injection+ # recorded 10 minutes ago in Shanghai -> within the interval, skip.+ self._add_injection("2026-07-01T19:50:00", timezone="Asia/Shanghai")+ events = await self._run_injection()+ self.assertEqual([], events)++ # The same wall-clock time read as UTC would be 7h50m in the future,+ # so a negative elapsed time must trigger an injection instead of+ # being silently swallowed.+ self.agent.state.context = []+ self._add_injection("2026-07-01T19:50:00")+ events = await self._run_injection()+ self.assertEqual(1, len(events))++ async def test_extra_fields_are_attached(self) -> None:+ """The extra fields should be attached to a triggered injection."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>\n"+ "<workspace>/home/friday</workspace>\n"+ "</system-reminder>"+ )+ self.agent.injection_config = InjectionConfig(+ extra_fields={"workspace": "/home/friday"},+ )+ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ async def test_extra_fields_do_not_trigger_injection(self) -> None:+ """The extra fields alone should not trigger an injection."""+ self.agent.injection_config = InjectionConfig(+ extra_fields={"workspace": "/home/friday"},+ )+ self.agent.state.cur_iter = 1+ # A recent injection so the time branch is not triggered.+ self._add_injection("2026-07-01T12:00:00")+ events = await self._run_injection()++ self.assertEqual([], events)++ async def test_disabled_injection(self) -> None:+ """Nothing should be injected when the injection is turned off."""+ self.agent.injection_config = InjectionConfig(+ inject_runtime_state=False,+ )+ events = await self._run_injection()++ self.assertEqual([], events)+ self.assertEqual([], self.agent.state.context)++ async def test_context_size_triggers_injection(self) -> None:+ """When the input tokens are close to the compression threshold, a+ context-length injection should be triggered."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<context-length>Your current context contains 700 tokens. "+ "When reaching 800 tokens, your context will be compressed."+ "</context-length>\n"+ "</system-reminder>"+ )+ # First iteration is required for the context-length branch.+ self.agent.state.cur_iter = 0+ # A recent injection so the time branch is not triggered.+ self._add_injection("2026-07-01T12:00:00")+ # 700 > max(0, 0.8 - 0.2) * 1000 == 600 -> triggers the injection.+ self.model.count_tokens = AsyncMock(return_value=700)++ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ async def test_context_size_is_independent_of_the_other_fields(+ self,+ ) -> None:+ """The context length should be reported even when the other+ dimensions are triggered in the same injection."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>\n"+ "<context-length>Your current context contains 700 tokens. "+ "When reaching 800 tokens, your context will be compressed."+ "</context-length>\n"+ "</system-reminder>"+ )+ # The first reply, where the time injection is always triggered.+ self.agent.state.cur_iter = 0+ self.model.count_tokens = AsyncMock(return_value=700)++ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )++ async def test_template_without_placeholder_is_rejected(self) -> None:+ """A template that would silently drop the injected fields should be+ rejected at the config level."""+ with self.assertRaises(ValidationError):+ InjectionConfig(template="<system-reminder></system-reminder>")++ async def test_template_with_curly_braces_is_kept(self) -> None:+ """The curly braces other than the placeholder should survive."""+ self.agent.injection_config = InjectionConfig(+ template='{"reminder": "{runtime_state}"}',+ )+ events = await self._run_injection()++ self.assertEqual(+ [+ self._expected_event(+ '{"reminder": "'+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>UTC</timezone>"+ '"}',+ ),+ ],+ [evt.model_dump() for evt in events],+ )++ async def test_invalid_timezone_falls_back_to_utc(self) -> None:+ """An unresolvable timezone shouldn't break the reply loop."""+ expected_hint = (+ "<system-reminder>Treat the following as the ground truth at this "+ "point of the conversation. Anything stated earlier is outdated, "+ "and a later reminder, if any, supersedes this one:\n"+ "<current-time>2026-07-01T12:00:00</current-time>\n"+ "<timezone>Mars/Olympus_Mons</timezone>\n"+ "</system-reminder>"+ )+ self.agent.injection_config = InjectionConfig(+ timezone="Mars/Olympus_Mons",+ )+ events = await self._run_injection()++ self.assertEqual(+ [self._expected_event(expected_hint)],+ [evt.model_dump() for evt in events],+ )diff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.pyindex 3fae79148..abaaaa369 100644--- a/tests/agent_interrupt_test.py+++ b/tests/agent_interrupt_test.py@@ -17,7 +17,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, InjectionConfigfrom agentscope.event import (ReplyEndEvent,UserInterruptEvent,@@ -284,6 +284,10 @@ class AgentInterruptCancelTest(IsolatedAsyncioTestCase):system_prompt="You are a test agent.",model=model,toolkit=Toolkit(tools=tools),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)return agent, model@@ -724,6 +728,10 @@ class AgentInterruptEventTest(IsolatedAsyncioTestCase):system_prompt="You are a test agent.",model=model,toolkit=Toolkit(tools=tools),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)return agent, modeldiff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.pyindex 770f43d4f..0a3833b9a 100644--- a/tests/hitl_external_execution_test.py+++ b/tests/hitl_external_execution_test.py@@ -6,7 +6,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, InjectionConfigfrom agentscope.model import ChatResponsefrom agentscope.tool import (ToolBase,@@ -111,6 +111,10 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):system_prompt="You are a helpful assistant.",model=self.model,toolkit=Toolkit(),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)self.tool_call_id_1 = "tool_call_1"self.tool_call_id_2 = "tool_call_2"diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.pyindex ac35b1d84..ed3557fa2 100644--- a/tests/hitl_user_confirmation_test.py+++ b/tests/hitl_user_confirmation_test.py@@ -5,7 +5,7 @@ from typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, InjectionConfigfrom agentscope.model import ChatResponsefrom agentscope.tool import (ToolBase,@@ -205,6 +205,10 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):system_prompt="You are a helpful assistant.",model=self.model,toolkit=Toolkit(),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)self.tool_call_id_1 = "tool_call_1"self.tool_call_id_2 = "tool_call_2"diff --git a/tests/middleware_filesystem_memory_test.py b/tests/middleware_filesystem_memory_test.pyindex 826638c7b..e6fddb21f 100644--- a/tests/middleware_filesystem_memory_test.py+++ b/tests/middleware_filesystem_memory_test.py@@ -9,7 +9,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom pydantic import BaseModelfrom utils import AnyString, AnyValue, MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, InjectionConfigfrom agentscope.message import (HintBlock,Msg,@@ -335,6 +335,10 @@ class AgenticMemoryMiddlewareTest(IsolatedAsyncioTestCase):model=model,toolkit=toolkit or Toolkit(),middlewares=[middleware],+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)async def test_agent_reply_creates_layout_and_injects_memory_prompt(diff --git a/tests/middleware_test.py b/tests/middleware_test.pyindex 381061263..93896f0e3 100644--- a/tests/middleware_test.py+++ b/tests/middleware_test.py@@ -8,7 +8,7 @@ from typing import Any, AsyncGenerator, Callable, Unionfrom utils import MockModelfrom pydantic import BaseModelfrom agentscope.event import AgentEvent-from agentscope.agent import Agent, ContextConfig+from agentscope.agent import Agent, ContextConfig, InjectionConfigfrom agentscope.middleware import MiddlewareBasefrom agentscope.model import ChatResponsefrom agentscope.message import (@@ -86,6 +86,10 @@ class TestMiddleware(IsolatedAsyncioTestCase):model=self.mock_model,toolkit=self.toolkit,middlewares=[middleware1, middleware2],+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)await agent.reply(UserMsg("user", "test message"))@@ -380,6 +384,9 @@ class TestMiddleware(IsolatedAsyncioTestCase):model=self.mock_model,toolkit=self.toolkit,middlewares=[middleware1, middleware2],+ # The runtime state injection is covered by agent_injection_test,+ # turn it off to keep the assertions focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)await agent.reply(UserMsg("user", "test message"))@@ -473,6 +480,9 @@ class TestMiddleware(IsolatedAsyncioTestCase):model=self.mock_model,toolkit=self.toolkit,middlewares=[middleware],+ # The runtime state injection is covered by agent_injection_test,+ # turn it off to keep the assertions focused.+ injection_config=InjectionConfig(inject_runtime_state=False),)await agent.reply(UserMsg("user", "test message"))diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex d3edde18d..d9f2f9796 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -15,7 +15,7 @@ from urllib.request import url2pathnameimport aiofilesfrom utils import AnyString, MockModel-from agentscope.agent import Agent, ContextConfig+from agentscope.agent import Agent, ContextConfig, InjectionConfigfrom agentscope.model import ChatResponse, StructuredResponsefrom agentscope.state import AgentStatefrom agentscope.tool import (@@ -866,6 +866,10 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):context_config=ContextConfig(tool_result_limit=50,),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),offloader=LocalWorkspace(workdir=workdir,),@@ -1015,6 +1019,10 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):model=model,toolkit=Toolkit(),offloader=LocalWorkspace(workdir=workdir),+ # The runtime state injection is covered by+ # agent_injection_test, turn it off to keep the assertions+ # focused.+ injection_config=InjectionConfig(inject_runtime_state=False),state=AgentState(session_id=session_id),)