DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(agent-loop): let a context checkpoint carry replaceable state
wangkai87a031725508
diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex f36c5a0d1..a287908a1 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -834,7 +834,7 @@ class AgentLoop:dispatch: DispatchOutcome,checkpoint_boundary: int,) -> int:- summary = _last_context_checkpoint_summary(dispatch)+ summary, state = _last_context_checkpoint(dispatch)if not summary:return checkpoint_boundaryprefix = messages[:checkpoint_boundary]@@ -844,8 +844,13 @@ class AgentLoop:"content": f"[Context checkpoint]\n{summary}",})+ boundary = len(prefix)+ if state:+ # State sits past the boundary, so the next fold replaces it rather+ # than leaving a stale copy beside every summary.+ prefix.append({"role": "system", "content": state})messages[:] = prefix- return len(messages)+ return boundaryasync def _reject_capability_finish(self) -> LoopOutcome:"""Fail a turn whose required interaction could not be completed."""@@ -1870,8 +1875,13 @@ async def _single_chunk_stream(response: Any) -> Any:)-def _last_context_checkpoint_summary(dispatch: DispatchOutcome) -> str:- summary = ""+def _last_context_checkpoint(dispatch: DispatchOutcome) -> tuple[str, str]:+ """``(summary, state)`` of the round's last checkpoint.++ ``summary`` is history the fold keeps; ``state`` is the optional current+ state that replaces the previous fold's copy instead of stacking with it.+ """+ summary, state = "", ""for tool_message in dispatch.tool_messages:tool_call_id = str(tool_message.get("tool_call_id") or "")metadata = dispatch.tool_metadata_by_id.get(tool_call_id) or {}@@ -1881,7 +1891,8 @@ def _last_context_checkpoint_summary(dispatch: DispatchOutcome) -> str:candidate = str(checkpoint.get("summary") or "").strip()if candidate:summary = candidate- return summary+ state = str(checkpoint.get("state") or "").strip()+ return summary, state__all__ = [diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex 84b78630e..dbd56ac12 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -2849,6 +2849,65 @@ async def test_context_checkpoint_folds_completed_tool_rounds(assert result.metadata["response"] == "Final from checkpoints."+async def test_context_checkpoint_state_replaces_instead_of_stacking(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _StatefulCheckpointRegistry(_Registry):+ async def execute(self, name: str, **kwargs):+ query = str(kwargs.get("query") or "")+ return ToolResult(+ content=f"noisy tool result for {query}",+ success=True,+ metadata={+ "_context_checkpoint": {+ "summary": f"checkpoint: {query}",+ "state": f"state after {query}",+ }+ },+ )++ def _search(call_id: str, query: str) -> SimpleNamespace:+ return _llm_chunk(+ tool_calls=[+ {"id": call_id, "name": "web_search", "arguments": json.dumps({"query": query})}+ ]+ )++ client = _ScriptedChatClient(+ [+ [_search("call-1", "step one")],+ [_search("call-2", "step two")],+ [_llm_chunk(content="Final.")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = _StatefulCheckpointRegistry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ await _run(+ pipeline,+ UnifiedContext(session_id="s1", user_message="Research this", enabled_tools=["web_search"]),+ )++ second_round = [m.get("content") for m in client.calls[1]["messages"]]+ assert second_round[-2:] == [+ "[Context checkpoint]\ncheckpoint: step one",+ "state after step one",+ ]+ third_round = client.calls[2]["messages"]+ contents = [str(m.get("content") or "") for m in third_round]+ # Summaries accumulate as history; only the latest state is kept, last.+ assert contents[-3:] == [+ "[Context checkpoint]\ncheckpoint: step one",+ "[Context checkpoint]\ncheckpoint: step two",+ "state after step two",+ ]+ assert "state after step one" not in contents+ assert not any(m.get("role") == "tool" for m in third_round)++@pytest.mark.asyncioasync def test_ask_user_available_every_round(monkeypatch: pytest.MonkeyPatch) -> None:"""The single loop offers the full tool belt — including ask_user — on