fix: keep chat tools[] and system prompt stable within a session

This commit is contained in:
zszz3
2026-11-25 02:31:03 +08:00
parent 224a08029d
commit d5ac66781f
9 changed files with 709 additions and 57 deletions

View File

@@ -157,6 +157,7 @@ knowledge_base_seed:
irrelevant; if they are not enough, retrieve more with rag.
notices:
research_tools_hint: "[Hint: if reading or auditing academic papers is needed, the research tools ({tools}) can be loaded with `load_tools`.]"
context_length_exceeded: "The conversation filled the model's context window, so the answer was cut off. Start a new chat or shorten the history and try again."
conversation_summary_header: "[Conversation summary]"
tool_result_snipped: "[earlier tool result snipped to stay within context window; call the same tool again if the content is still needed]"

View File

@@ -114,6 +114,7 @@ knowledge_base_seed:
将它们作为有根据的上下文。它们可能不完整或部分无关;如果仍不够,用 rag 继续检索。
notices:
research_tools_hint: "[提示:如果需要查找、阅读或核查论文,可以用 `load_tools` 加载研究工具({tools})。]"
context_length_exceeded: "对话已达到模型的上下文上限,回答因此中断。请新建对话或缩短历史记录后重试。"
conversation_summary_header: "[对话摘要]"
tool_result_snipped: "[较早的工具结果已裁剪以保持在上下文窗口内;如果仍需要该内容,请再次调用同一工具]"

View File

@@ -26,7 +26,7 @@ import asyncio
import logging
import os
from pathlib import Path
from typing import Any
from typing import Any, NamedTuple
from deeptutor.agents._shared.tool_composition import (
ToolMountFlags,
@@ -34,7 +34,6 @@ from deeptutor.agents._shared.tool_composition import (
default_optional_tools,
partner_can_record_questions,
user_has_mastery_topics,
user_has_memory,
user_has_notebooks,
user_has_question_bank,
)
@@ -101,6 +100,16 @@ logger = logging.getLogger(__name__)
_PARTNER_SUPPRESSED_TOOLS: tuple[str, ...] = ("read_memory", "write_memory")
class LocalDeferredTools(NamedTuple):
"""Built-in/capability tools a turn offers through ``load_tools``."""
names: tuple[str, ...]
#: Names of a mode the user opened; recorded as loaded for the session.
eager: set[str]
#: Usage rules returned by ``load_tools`` alongside a tool's schema.
guides: dict[str, str]
LOOP_EXCLUDED_TOOLS: set[str] = set()
LOOP_OPTIONAL_TOOLS = default_optional_tools(excluded=LOOP_EXCLUDED_TOOLS)
@@ -435,17 +444,7 @@ class AgenticLoopPipeline:
self._exec_enabled = await self._exec_allowed(context)
enabled_tools = self._compose_enabled_tools(context)
use_native_tools = bool(enabled_tools) and self._can_use_native_tool_calling()
tool_schemas = (
self._build_llm_tool_schemas(enabled_tools, context) if use_native_tools else None
)
if tool_schemas is not None and self._tool_view is not None:
self._tool_view.attach(tool_schemas)
if tool_schemas:
# Reuse the last admitted order, including deferred tools loaded
# during that turn. Removed/unauthorized tools stay removed.
prior = (context.runtime.previous_model_turn or {}).get("tools") or []
order = {item["function"]["name"]: i for i, item in enumerate(prior)}
tool_schemas.sort(key=lambda item: order.get(item["function"]["name"], len(order)))
tool_schemas = self._turn_tool_schemas(enabled_tools, context) if use_native_tools else None
if (
os.getenv("DEEPTUTOR_CHAT_ENGINE") == "typescript-native"
@@ -471,6 +470,27 @@ class AgenticLoopPipeline:
self.last_result = await loop.run()
return self.last_result
def _turn_tool_schemas(
self, enabled_tools: list[str], context: UnifiedContext
) -> list[dict[str, Any]]:
"""This turn's ``tools[]``: composed schemas, then the session's loaded ones.
The list is the first thing in the provider's cache key, so it is laid
out in the previous turn's order: with unchanged toggles it is the same
bytes, and anything new (a tool loaded last turn, a first favorite)
lands at the end.
"""
tool_schemas = self._build_llm_tool_schemas(enabled_tools, context)
if self._tool_view is not None:
self._tool_view.attach(tool_schemas)
if tool_schemas:
# Reuse the last admitted order, including deferred tools loaded
# during that turn. Removed/unauthorized tools stay removed.
prior = (context.runtime.previous_model_turn or {}).get("tools") or []
order = {item["function"]["name"]: i for i, item in enumerate(prior)}
tool_schemas.sort(key=lambda item: order.get(item["function"]["name"], len(order)))
return tool_schemas
def _native_compatibility_reason(self) -> str:
"""Admit explicit recovery policies to the shared effects host."""
if self.reasoning_budget_recovery.strategy != "prompt":
@@ -735,6 +755,138 @@ class AgenticLoopPipeline:
# Kept as a plain list: the context-budget chip counts the provider
# tools whose schemas never entered the window.
self._deferred_pool = list(view.pool)
self._mount_local_deferred_tools(context)
# ---- locally deferred tools ------------------------------------------
#
# Built-in and capability tools that used to be mounted by a per-message
# heuristic (research tools when a message says "论文", setup tools when it
# says "switch the model", or on an unconfigured install's first message).
# Mounting them per message made ``tools[]`` — the very start of the cached
# prompt — differ between two turns of one conversation. They are listed in
# the Extended Tools catalog instead and reach ``tools[]`` only through the
# session's loaded set, which only grows.
def _deferral_allowed(self, context: UnifiedContext) -> bool:
"""Whether optional tools can be offered through ``load_tools`` this turn."""
if self._exclusive_capability_active(context):
return False # The capability owns the surface; no catalog is shown.
allowed = context.allowed_builtin_tools
if allowed is not None and "load_tools" not in allowed:
return False # A restricted caller keeps eager access instead.
lookup_get = getattr(self.tool_lookup, "get", None)
return callable(lookup_get) and lookup_get("load_tools") is not None
def _local_deferred_tools(self, context: UnifiedContext) -> LocalDeferredTools:
"""Which built-in/capability tools this turn offers through ``load_tools``.
``eager`` names belong to a capability that is active this turn (an
explicitly opened setup mode): they are recorded as loaded for the
session rather than mounted, so they arrive in the same place and stay
after the mode is left.
"""
names: list[str] = []
eager: set[str] = set()
guides: dict[str, str] = {}
builtin_whitelist = context.allowed_builtin_tools
from deeptutor.modules.catalog import module_enabled
if module_enabled("research"):
from deeptutor.tools.research_tools import SCIENTIFIC_TOOL_NAMES, scientific_context
# The message is deliberately not consulted: a regex hit only earns
# a hint in the user message (``_turn_disclosure_notes``). Deep
# research and the ``paper_search`` toggle are the user's own mode
# switches, so there the tools are mounted outright — and leave
# with the toggle — exactly like any other toggled tool.
if not scientific_context("", context.active_capability, context.enabled_tools or []):
names.extend(
name
for name in SCIENTIFIC_TOOL_NAMES
if builtin_whitelist is None or name in builtin_whitelist
)
from deeptutor.capabilities import all_loop_capabilities
for cap in all_loop_capabilities(context):
cap_names = [str(name) for name in getattr(cap, "deferred_tools", ()) or ()]
if not cap_names:
continue
names.extend(cap_names)
if cap.is_active(context):
eager.update(cap_names)
guide_hook = getattr(cap, "deferred_tool_guide", None)
if callable(guide_hook):
try:
guide = guide_hook(language=self.language, prompts=self._prompts)
except Exception:
logger.warning("deferred tool guide failed for %s", cap.name, exc_info=True)
guide = ""
if guide:
for name in cap_names:
guides[name] = guide
return LocalDeferredTools(names=tuple(dict.fromkeys(names)), eager=eager, guides=guides)
def _mount_local_deferred_tools(self, context: UnifiedContext) -> None:
"""Add this turn's locally deferred tools to the provider tool view."""
from deeptutor.capabilities.disclosure import set_deferral_available
self._local_deferred_names: set[str] = set()
self._eager_guides: list[str] = []
available = self._deferral_allowed(context)
# Recorded before any capability is asked whether it is active, so a
# heuristically-triggered capability stays inactive on this turn.
set_deferral_available(context, available)
if not available:
return
local = self._local_deferred_tools(context)
view = self._tool_view
tools = [view.registry.get(name) for name in local.names]
tools = [tool for tool in tools if tool is not None]
if not tools:
return
from deeptutor.runtime.registry.deferred_tools import (
DeferredToolLoader,
render_deferred_tools_manifest,
)
from deeptutor.services.mcp import load_loaded_tools, record_loaded_tools
local_names = {tool.name for tool in tools}
self._local_deferred_names = local_names
pool = (*view.pool, *tools)
persisted = load_loaded_tools(context.session_id)
loaded = persisted | (view.loader.loaded_names if view.loader else set())
eager = local.eager & local_names
# Rules for tools that reach ``tools[]`` without a ``load_tools`` call
# (an opened mode): delivered once, in this turn's user message.
self._eager_guides = list(
dict.fromkeys(
local.guides[name] for name in sorted(eager - loaded) if name in local.guides
)
)
if not eager <= loaded:
loaded |= eager
# Persist now: an eagerly-opened mode's tools stay in this
# conversation's ``tools[]`` after the mode is left.
record_loaded_tools(context.session_id, persisted | eager)
loader = DeferredToolLoader(
registry=view.registry,
session_id=context.session_id,
loaded=loaded,
allowed={tool.name for tool in pool},
capability_names=local_names,
guides={name: text for name, text in local.guides.items() if name in local_names},
)
self._tool_view = ProviderToolView(
registry=view.registry,
loader=loader,
pool=pool,
# One catalog for provider and local tools alike: rendering the
# whole pool keeps the snapshot a function of the pool, not of how
# it was assembled.
manifest=render_deferred_tools_manifest(list(pool), language=self.language),
)
self._deferred_loader = loader
self._deferred_pool = list(pool)
def _tool_scope(self, context: UnifiedContext) -> ToolScope:
"""Per-turn policy inputs for the provider layer."""
@@ -829,13 +981,22 @@ class AgenticLoopPipeline:
is_partner = self._is_partner_turn(context)
from deeptutor.modules.catalog import module_enabled
local_deferred = getattr(self, "_local_deferred_names", set())
scientific = False
if module_enabled("research"):
from deeptutor.tools.research_tools import scientific_context
from deeptutor.tools.research_tools import SCIENTIFIC_TOOL_NAMES, scientific_context
scientific = scientific_context(
# Deferred research tools reach ``tools[]`` through the session's
# loaded set only; the message regex no longer mounts them.
scientific = not set(SCIENTIFIC_TOOL_NAMES) <= local_deferred and scientific_context(
context.user_message, context.active_capability, context.enabled_tools or []
)
# Tools gated on the user's *data* (a first favorite, a first saved
# question, a first mastery topic) stay mounted for the rest of the
# conversation once they appeared: the data showing up mid-session must
# not rewrite the cached tool list, and it never disappears again in a
# way the model must be shielded from.
sticky = self._previously_mounted_tools(context)
def has_book_authoring():
from deeptutor.modules.catalog import module_enabled
@@ -863,14 +1024,21 @@ class AgenticLoopPipeline:
# Keep it off the answer surface even when sources are present.
has_sources=False,
has_book_authoring=has_book_authoring(),
has_memory=user_has_memory(),
has_notebooks=user_has_notebooks(),
# ``read_memory`` (80 tokens) is mounted whenever memory is
# on, even before there is anything to read: an empty read is a
# valid answer, and gating it on content meant the first
# ``write_memory`` of a conversation changed ``tools[]``.
has_memory=module_enabled("memory"),
has_notebooks="list_favorites" in sticky or user_has_notebooks(),
# A partner turn mounts the bank even when it is still empty:
# the tool's record action must be available to file the FIRST
# wrong question the learner owns up to (#1244). Product chat
# keeps the entries-exist gate.
has_question_bank=user_has_question_bank() or partner_can_record_questions(),
has_skills=bool(context.skills_manifest or context.active_skills_context),
has_question_bank="question_bank" in sticky
or user_has_question_bank()
or partner_can_record_questions(),
has_skills="read_skill" in sticky
or bool(context.skills_manifest or context.active_skills_context),
has_deferred_tools=getattr(self, "_deferred_loader", None) is not None,
has_exec=getattr(self, "_exec_enabled", False),
# Reaching a mastery topic is a chat-wide affordance, not part
@@ -881,10 +1049,11 @@ class AgenticLoopPipeline:
# A mastery turn mounts navigation from the start: its first
# turn usually creates the topic, and mounting it only then
# grew tools[] on the second turn (one full cache miss).
has_mastery_nav=bool(context.metadata.get("mastery_mode"))
has_mastery_nav="mastery_sessions" in sticky
or bool(context.metadata.get("mastery_mode"))
or self._mastery_nav_available(context),
has_mastery_topics=(
self._mastery_nav_available(context)
("mastery_topics" in sticky or self._mastery_nav_available(context))
and not context.metadata.get("mastery_mode")
),
),
@@ -907,7 +1076,21 @@ class AgenticLoopPipeline:
lookup_get = getattr(self.tool_lookup, "get", None)
if callable(lookup_get) and lookup_get("workspace_export") is not None:
composed.append("workspace_export")
return list(dict.fromkeys(composed))
# Locally deferred tools arrive through the loader (``attach``), never
# through the composed list — even when this turn would have mounted
# them — so their position and bytes never depend on the message.
return [name for name in dict.fromkeys(composed) if name not in local_deferred]
@staticmethod
def _previously_mounted_tools(context: UnifiedContext) -> set[str]:
"""Tool names the previous model turn of this conversation was offered."""
prior = (context.runtime.previous_model_turn or {}).get("tools") or []
names: set[str] = set()
for item in prior:
function = item.get("function") if isinstance(item, dict) else None
if isinstance(function, dict) and function.get("name"):
names.add(str(function["name"]))
return names
def _mastery_nav_available(self, context: UnifiedContext) -> bool:
"""Whether this turn should be able to point at a mastery topic.
@@ -1026,8 +1209,45 @@ class AgenticLoopPipeline:
for cap in self._active_loop_capabilities(context)
if (seed := cap.pre_loop_seed(context))
]
seeds.extend(self._turn_disclosure_notes(context))
return "\n\n".join(seed for seed in seeds if seed)
def _turn_disclosure_notes(self, context: UnifiedContext) -> list[str]:
"""Per-message pointers at deferred tools, for the end of the user message.
This is where a message heuristic ends up: it costs a sentence in the
newest message instead of rewriting ``tools[]`` and the system prompt.
"""
local_deferred = getattr(self, "_local_deferred_names", set())
if not local_deferred:
return []
loader = self._deferred_loader
loaded = loader.loaded_names if loader is not None else set()
notes: list[str] = list(getattr(self, "_eager_guides", []))
from deeptutor.tools.research_tools import SCIENTIFIC_TOOL_NAMES, scientific_context
research = [n for n in SCIENTIFIC_TOOL_NAMES if n in local_deferred and n not in loaded]
if research and scientific_context(context.user_message):
notes.append(
self._t("notices.research_tools_hint").format(
tools=", ".join(f"`{name}`" for name in research)
)
)
from deeptutor.capabilities import all_loop_capabilities
for cap in all_loop_capabilities(context):
hook = getattr(cap, "turn_note", None)
if not callable(hook):
continue
try:
note = hook(context, language=self.language)
except Exception:
logger.warning("turn note failed for capability %s", cap.name, exc_info=True)
continue
if note:
notes.append(note.strip())
return [note for note in notes if note]
def _capability_skips_kb_seed(self, context: UnifiedContext) -> bool:
"""Let an active capability say this turn's message is not a query.

View File

@@ -0,0 +1,37 @@
"""Whether this turn discloses optional tools through ``load_tools``.
A loop turn can offer a tool in two ways: mount its schema in ``tools[]``, or
list it in the Extended Tools catalog and let the model ``load_tools`` it when
it actually needs it. Mounting per message ("this message mentions a paper",
"this message says *switch the model*") makes ``tools[]`` differ between two
turns of one conversation, which invalidates the provider's prompt cache from
the first tool on. Deferred tools only ever grow: a loaded schema stays loaded
for the rest of the session.
The loop pipeline decides once per turn whether deferral is available (the
turn is not owned by an exclusive capability, and ``load_tools`` itself is
allowed) and records it here *before* any capability's ``is_active`` is asked.
A capability whose tools would otherwise be mounted by a message heuristic
reads it to stay inactive — and to keep its system block out — on such turns.
Callers that never set it (other pipelines, direct tests) keep the eager
behaviour.
"""
from __future__ import annotations
from deeptutor.core.context import UnifiedContext
_EXTENSION = "tool_disclosure"
_DEFERRAL_KEY = "deferral_available"
def set_deferral_available(context: UnifiedContext, available: bool) -> None:
context.extension(_EXTENSION)[_DEFERRAL_KEY] = bool(available)
def deferral_available(context: UnifiedContext) -> bool:
"""``True`` once the pipeline has confirmed optional tools can be deferred."""
return bool(context.extension(_EXTENSION).get(_DEFERRAL_KEY))
__all__ = ["deferral_available", "set_deferral_available"]

View File

@@ -289,18 +289,17 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
session_id=context.session_id,
loaded=loaded,
allowed={tool.name for tool in pool},
capability_names=self._deferred_outline_names,
# This loader replaces the base one, so it must keep honouring the
# base pipeline's own deferred names (research, setup).
capability_names=self._deferred_outline_names
| getattr(self, "_local_deferred_names", set()),
guides=view.loader.guides if view.loader else None,
)
self._tool_view = ProviderToolView(
registry=view.registry,
loader=loader,
pool=pool,
manifest="\n\n".join(
filter(
None,
[view.manifest, render_deferred_tools_manifest(local, language=self.language)],
)
),
manifest=render_deferred_tools_manifest(list(pool), language=self.language),
)
self._deferred_loader = loader
self._deferred_pool = list(pool)

View File

@@ -8,14 +8,28 @@ surface — knowledge bases, web search, the lot — and these four tools are ad
on top. An exclusive capability would strip exactly the abilities a
configuration conversation is often about.
Activation is decided by :func:`~deeptutor.capabilities.setup.binding.is_setup_turn`
Activation is decided by :func:`~deeptutor.capabilities.setup.binding.setup_activation`
on objective signals rather than by the model's sense of relevance; see that
module for why.
The system block carries the install's current gaps. That is what lets the
model open with something useful ("your knowledge bases can't be built yet —
no embedding model is selected") instead of a menu, and it costs one filesystem
pass that ``is_active`` has already paid for.
How the four tools reach the model depends on why the turn is a setup turn.
``intent`` (the message pairs "switch" with "model") and ``intro`` (first
conversation on an install with a blocking gap) are message heuristics: when
the loop can defer tools (:mod:`deeptutor.capabilities.disclosure`) they no
longer mount anything. The tools stay listed under Extended Tools on every
turn, their usage protocol is returned by ``load_tools`` (see
:meth:`SetupCapability.deferred_tool_guide`), and the turn gets a short note at
the end of the user message instead (:meth:`SetupCapability.turn_note`). The
note carries the install's current gaps — what lets the model open with
something useful ("your knowledge bases can't be built yet — no embedding model
is selected") instead of a menu. ``tools[]`` and the system prompt therefore
stay byte-identical whether or not a message happens to mention configuration.
``explicit`` (the user opened setup mode) is a mode switch: the capability is
active and the pipeline records the tools as loaded, so they join ``tools[]``
on that turn and stay there after the user leaves the mode. The protocol is put
in that turn's user message once, the way ``load_tools`` would have returned
it; the system prompt is never touched.
"""
from __future__ import annotations
@@ -23,11 +37,11 @@ from __future__ import annotations
from importlib import resources
from typing import Any
from deeptutor.capabilities.disclosure import deferral_available
from deeptutor.capabilities.protocol import PromptBlock
from deeptutor.capabilities.setup.binding import (
SETUP_CAPABILITY_NAME,
cached_gaps,
is_setup_turn,
mark_intro_shown,
setup_activation,
)
@@ -41,9 +55,17 @@ class SetupCapability:
name = SETUP_CAPABILITY_NAME
owned_tools = SETUP_TOOL_NAMES
#: Offered through ``load_tools`` on every turn that can defer tools.
deferred_tools = SETUP_TOOL_NAMES
def is_active(self, context: UnifiedContext) -> bool:
return is_setup_turn(context)
reason = setup_activation(context)
if reason == "explicit":
return True
# A message heuristic must not change the turn's tool surface or system
# prompt; where deferral is available the tools are one ``load_tools``
# away and :meth:`turn_note` tells the model so.
return bool(reason) and not deferral_available(context)
def system_block(
self,
@@ -55,33 +77,71 @@ class SetupCapability:
reason = setup_activation(context)
if not reason:
return None
override = _prompt_text(prompts, ("setup", "system"))
content = override or _load_system_prompt(language)
gaps = cached_gaps(context)
if gaps:
lines = "\n".join(f"- {gap.summary} {gap.remedy}".strip() for gap in gaps)
content = f"{content}\n\n## What this install is currently missing\n{lines}"
else:
content = f"{content}\n\n## What this install is currently missing\n- Nothing."
if deferral_available(context):
# Nothing in the system prompt: the protocol travels with the tools
# (``load_tools`` result, or this turn's user message when an opened
# mode loads them) and the gaps ride in :meth:`turn_note`. Entering
# or leaving setup mode therefore never rewrites the system prompt.
return None
content = _protocol(language, prompts)
content = f"{content}\n\n{_gaps_section(context)}"
if reason == "intro":
# The user did not raise this subject, so the opening has to earn its
# place: name the one thing that is missing, offer to fix it, and
# drop it if they would rather do something else.
content = (
f"{content}\n\n## This is the user's first conversation\n"
"They have not asked about configuration. Answer whatever they "
"actually said first. Then, in one or two sentences at the end, "
"mention the single most important gap above and offer to set it "
"up. Do not list every gap, do not open with it, and do not "
"raise it again if they move on."
)
content = f"{content}\n\n{_INTRO_SECTION}"
# Spent only here: an explicit or intent-driven turn must not consume
# the one proactive offer an unconfigured install gets.
mark_intro_shown()
return PromptBlock(SETUP_CAPABILITY_NAME, content)
def deferred_tool_guide(self, *, language: str, prompts: dict[str, Any]) -> str:
"""The protocol for the four tools, returned when ``load_tools`` loads them."""
return _protocol(language, prompts)
def turn_note(self, context: UnifiedContext, *, language: str) -> str:
"""Per-turn setup facts for the end of the user message.
Only emitted where deferral is available — otherwise the legacy system
block carries the same facts.
"""
reason = setup_activation(context)
if not reason or not deferral_available(context):
return ""
zh = str(language or "en").lower().startswith("zh")
tools = ", ".join(f"`{name}`" for name in SETUP_TOOL_NAMES)
if reason == "explicit":
lead = (
"用户打开了配置模式,配置工具已加载,按此前给出的配置工具使用规范操作。"
if zh
else "The user opened setup mode; the setup tools are loaded. Follow the "
"rules for using them given when they were loaded."
)
elif reason == "intent":
lead = (
"这条消息像是要修改 DeepTutor 自身的配置。配置工具"
f"({tools})在扩展工具里:先用 `load_tools` 加载需要的那几个,"
"它的返回里附有这些工具的使用规范,照规范操作。"
"如果这条消息其实和 DeepTutor 的配置无关,忽略这段提示。"
if zh
else "This message looks like a request to change DeepTutor's own "
f"configuration. The setup tools ({tools}) are listed under "
"Extended Tools: load the ones you need with `load_tools` first — "
"its result includes the rules for using them, follow them. If the "
"message is not actually about DeepTutor's configuration, ignore "
"this note."
)
else: # intro
lead = f"{_INTRO_SECTION}\n" + (
f"如果用户接受,先用 `load_tools` 加载配置工具({tools}),它的返回里附有使用规范。"
if zh
else "If they accept, load the setup tools "
f"({tools}) with `load_tools` first; its result includes the "
"rules for using them."
)
# Spent only here, as in the legacy system block.
mark_intro_shown()
header = "[配置助手]" if zh else "[Setup]"
parts = [header, _gaps_section(context), lead]
return "\n".join(part for part in parts if part)
def augment_kwargs(
self,
tool_name: str,
@@ -105,4 +165,30 @@ def _load_system_prompt(language: str) -> str:
return prompt.read_text(encoding="utf-8").strip()
def _protocol(language: str, prompts: dict[str, Any]) -> str:
override = _prompt_text(prompts, ("setup", "system"))
return override or _load_system_prompt(language)
def _gaps_section(context: UnifiedContext) -> str:
gaps = cached_gaps(context)
lines = (
"\n".join(f"- {gap.summary} {gap.remedy}".strip() for gap in gaps) if gaps else "- Nothing."
)
return f"## What this install is currently missing\n{lines}"
# The user did not raise this subject, so the opening has to earn its place:
# name the one thing that is missing, offer to fix it, and drop it if they would
# rather do something else.
_INTRO_SECTION = (
"## This is the user's first conversation\n"
"They have not asked about configuration. Answer whatever they "
"actually said first. Then, in one or two sentences at the end, "
"mention the single most important gap above and offer to set it "
"up. Do not list every gap, do not open with it, and do not "
"raise it again if they move on."
)
__all__ = ["SetupCapability"]

View File

@@ -0,0 +1,213 @@
"""``tools[]`` and the system prompt stay put across the turns of one chat.
Both sit at the very start of the provider's prompt-cache key. Before this
was pinned, a single conversation rewrote them on ordinary messages:
* the first turn of an unconfigured install mounted the four setup tools and a
~1k-token ``## setup`` system block (``intro``), and the second turn removed
them again;
* "把语言切换成中文" mounted them again (``intent``);
* "论文" mounted the three research tools for that one message;
* a first favorite / saved question mid-conversation added a tool, and losing
it again removed one.
Each of those turned the whole request into a cache miss. These tests drive the
real chat pipeline's tool assembly through such a conversation and require
every turn's ``tools[]`` to equal — or only extend — the previous turn's, and
the system prompt to be byte-identical.
"""
from __future__ import annotations
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.capabilities.setup import SETUP_TOOL_NAMES
from deeptutor.core.context import TurnRuntimeContext, UnifiedContext
from deeptutor.tools.research_tools import SCIENTIFIC_TOOL_NAMES
SESSION = "stable-tools-session"
@pytest.fixture(autouse=True)
def _isolated_runtime(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, bool]:
from deeptutor.services.path_service import PathService
monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
paths = PathService(workspace_root=tmp_path / "data")
monkeypatch.setattr(PathService, "_instance", paths)
paths.ensure_all_directories()
monkeypatch.setattr(
"deeptutor.agents.loop.pipeline.get_llm_config",
lambda: SimpleNamespace(
binding="openai",
model="gpt-test",
api_key="k",
base_url="u",
api_version=None,
extra_headers={},
reasoning_effort=None,
),
)
# The user's data, switchable mid-conversation.
data = {"notebooks": False, "question_bank": False}
monkeypatch.setattr(
"deeptutor.agents.loop.pipeline.user_has_notebooks", lambda: data["notebooks"]
)
monkeypatch.setattr(
"deeptutor.agents.loop.pipeline.user_has_question_bank", lambda: data["question_bank"]
)
return data
class _Conversation:
"""Runs consecutive turns of one session the way ``run()`` assembles them."""
def __init__(self, *, language: str = "zh") -> None:
self.language = language
self.history: list[dict[str, Any]] = []
self.previous: dict[str, Any] | None = None
async def turn(self, message: str, **context_kwargs: Any) -> dict[str, Any]:
pipeline = AgenticChatPipeline(language=self.language)
context = UnifiedContext(
session_id=SESSION,
user_message=message,
language=self.language,
conversation_history=list(self.history),
runtime=TurnRuntimeContext(previous_model_turn=self.previous),
**context_kwargs,
)
await pipeline._prepare_deferred_tools(context)
pipeline._exec_enabled = False
enabled = pipeline._compose_enabled_tools(context)
schemas = pipeline._turn_tool_schemas(enabled, context)
system = pipeline._build_system_prompt(enabled, context)
note = pipeline._capability_pre_loop_seed(context)
self.previous = {"tools": json.loads(json.dumps(schemas)), "system": system}
self.history += [
{"role": "user", "content": message},
{"role": "assistant", "content": "ok"},
]
return {
"pipeline": pipeline,
"tools": schemas,
"names": [item["function"]["name"] for item in schemas],
"system": system,
"note": note,
"manifest": pipeline._deferred_tools_manifest(),
}
def _only_extends(before: list[dict[str, Any]], after: list[dict[str, Any]]) -> bool:
return json.dumps(after[: len(before)]) == json.dumps(before)
@pytest.mark.asyncio
async def test_one_conversation_keeps_tools_and_system_stable(
_isolated_runtime: dict[str, bool],
) -> None:
chat = _Conversation()
# Turn 1: a fresh install's first conversation — the setup intro fires.
first = await chat.turn("什么是导数?")
assert not set(SETUP_TOOL_NAMES) & set(first["names"])
assert not set(SCIENTIFIC_TOOL_NAMES) & set(first["names"])
assert "load_tools" in first["names"]
assert "## setup" not in first["system"]
# The product behaviour survives: the model hears about the blocking gap.
assert "first conversation" in first["note"]
assert "What this install is currently missing" in first["note"]
# Every deferred tool is listed in the catalog from the first turn on.
for name in (*SETUP_TOOL_NAMES, *SCIENTIFIC_TOOL_NAMES):
assert name in first["manifest"]
# Turn 2: the research regex only earns a hint.
paper = await chat.turn("请帮我找一篇关于导数教学的论文")
assert paper["tools"] == first["tools"]
assert paper["system"] == first["system"]
assert paper["manifest"] == first["manifest"]
assert "load_tools" in paper["note"] and "preprint" in paper["note"]
# Turn 3: a configuration request only earns a note.
switch = await chat.turn("把语言切换成中文")
assert switch["tools"] == first["tools"]
assert switch["system"] == first["system"]
assert "load_tools" in switch["note"] and "apply_setting" in switch["note"]
assert "first conversation" not in switch["note"], "the intro is offered once"
# Turn 4: the user's first favorite and saved question appear.
_isolated_runtime.update(notebooks=True, question_bank=True)
data = await chat.turn("那二阶导数呢?")
assert _only_extends(switch["tools"], data["tools"])
assert {"list_favorites", "save_favorite", "question_bank"} <= set(data["names"])
assert data["system"] == first["system"]
assert not data["note"]
# Turn 5: the data is gone again — the tools stay for this conversation.
_isolated_runtime.update(notebooks=False, question_bank=False)
after = await chat.turn("谢谢,再举个例子")
assert after["tools"] == data["tools"]
assert after["system"] == first["system"]
@pytest.mark.asyncio
async def test_loaded_tools_join_the_end_and_stay(_isolated_runtime: dict[str, bool]) -> None:
chat = _Conversation(language="en")
first = await chat.turn("find me an arxiv paper on teaching derivatives")
result = first["pipeline"]._deferred_loader.load(["preprint", "inspect_setup"])
assert result["loaded"] == ["preprint", "inspect_setup"]
# The setup protocol travels with the setup tools, not in the system prompt.
assert len(result["guides"]) == 1 and "inspect_setup" in result["guides"][0]
first_tools = first["tools"] # The live list the loader appended to.
chat.previous["tools"] = json.loads(json.dumps(first_tools))
assert first_tools[-2]["function"]["name"] == "preprint"
second = await chat.turn("thanks")
assert second["tools"] == first_tools
third = await chat.turn("and once more")
assert third["tools"] == first_tools
assert third["system"] == first["system"]
@pytest.mark.asyncio
async def test_opening_setup_mode_loads_the_tools_once_and_never_touches_system(
_isolated_runtime: dict[str, bool],
) -> None:
chat = _Conversation(language="en")
plain = await chat.turn("hello")
opened = await chat.turn("show me my settings", active_capability="setup")
assert _only_extends(plain["tools"], opened["tools"])
assert set(SETUP_TOOL_NAMES) <= set(opened["names"])
assert opened["system"] == plain["system"]
# The rules arrive once, with the tools.
assert "inspect_setup" in opened["note"] and "setup mode" in opened["note"]
again = await chat.turn("and the language?", active_capability="setup")
assert again["tools"] == opened["tools"]
assert again["system"] == plain["system"]
left = await chat.turn("back to calculus")
assert left["tools"] == opened["tools"]
assert left["system"] == plain["system"]
assert not left["note"]
@pytest.mark.asyncio
async def test_unchanged_toggles_give_byte_identical_tools(
_isolated_runtime: dict[str, bool],
) -> None:
chat = _Conversation()
first = await chat.turn("hi", enabled_tools=["web_search", "reason"])
second = await chat.turn("论文", enabled_tools=["web_search", "reason"])
assert json.dumps(second["tools"]) == json.dumps(first["tools"])
# Turning a tool off is the user's call: its schema leaves (one miss).
third = await chat.turn("hi", enabled_tools=["web_search"])
assert "reason" not in third["names"]
fourth = await chat.turn("hi again", enabled_tools=["web_search"])
assert json.dumps(fourth["tools"]) == json.dumps(third["tools"])

View File

@@ -389,3 +389,28 @@ async def test_a_plain_chat_turn_between_mastery_turns_keeps_the_outline_tools(m
assert {"mastery_build", "mastery_revise"} <= state["synthetic"]
assert await mastery_turn("study") == outline
@pytest.mark.asyncio
async def test_outline_loader_keeps_the_base_pipelines_deferred_tools(monkeypatch, tmp_path):
"""Mastery replaces the turn's loader; research/setup tools must survive it."""
from deeptutor.services.path_service import PathService
paths = PathService(workspace_root=tmp_path / "data")
monkeypatch.setattr(PathService, "_instance", paths)
pipeline = MasteryLoopPipeline(language="en")
context = UnifiedContext(
session_id="synthetic-base",
metadata={"mastery_mode": True, "mastery_path_id": "p", "mastery_session_mode": "study"},
)
await pipeline._prepare_deferred_tools(context)
manifest = pipeline._deferred_tools_manifest()
for name in ("mastery_build", "inspect_setup", "preprint"):
assert name in manifest
names = pipeline._compose_enabled_tools(context)
assert "inspect_setup" not in names and "preprint" not in names
schemas = pipeline._build_llm_tool_schemas(names, context)
pipeline._tool_view.attach(schemas)
result = pipeline._deferred_loader.load(["preprint", "inspect_setup", "mastery_build"])
assert result["loaded"] == ["preprint", "inspect_setup", "mastery_build"]
assert result["guides"], "the setup protocol rides along with its tools"

View File

@@ -721,3 +721,73 @@ def test_system_block_names_the_installs_gaps(isolated_settings: Path) -> None:
assert block is not None
assert "missing" in block.content
assert setup_gaps(), "a fresh install has gaps, so the block should list them"
# ---------------------------------------------------------------------------
# Deferred disclosure — heuristics must not touch tools[] or the system prompt
# ---------------------------------------------------------------------------
def _deferring(context: UnifiedContext) -> UnifiedContext:
from deeptutor.capabilities.disclosure import set_deferral_available
set_deferral_available(context, True)
return context
def test_an_intent_turn_only_gets_a_note_when_tools_can_be_deferred(
isolated_settings: Path,
) -> None:
context = _deferring(
UnifiedContext(
user_message="把界面语言切成中文",
conversation_history=[{"role": "user", "content": "hi"}],
)
)
capability = SetupCapability()
assert not capability.is_active(context), "intent must not mount the tools"
assert capability.system_block(context, language="zh", prompts={}) is None
note = capability.turn_note(context, language="zh")
assert "load_tools" in note and "apply_setting" in note
assert "What this install is currently missing" in note
def test_the_intro_note_carries_the_offer_and_spends_it_once(isolated_settings: Path) -> None:
from deeptutor.capabilities.setup.binding import setup_activation
capability = SetupCapability()
first = _deferring(UnifiedContext(user_message="你好", conversation_history=[]))
assert not capability.is_active(first)
note = capability.turn_note(first, language="en")
assert "first conversation" in note and "load_tools" in note
second = UnifiedContext(user_message="你好", conversation_history=[])
assert setup_activation(second) == "", "the offer must not repeat every new chat"
def test_explicit_mode_stays_active_but_keeps_the_system_prompt(isolated_settings: Path) -> None:
context = _deferring(UnifiedContext(user_message="hello", active_capability="setup"))
capability = SetupCapability()
assert capability.is_active(context)
assert capability.system_block(context, language="en", prompts={}) is None
assert "setup mode" in capability.turn_note(context, language="en")
def test_the_protocol_is_returned_with_the_loaded_tools(isolated_settings: Path) -> None:
guide = SetupCapability().deferred_tool_guide(language="en", prompts={})
assert "inspect_setup" in guide and "request_credential" in guide
def test_an_unrelated_turn_gets_no_note(isolated_settings: Path) -> None:
from deeptutor.capabilities.setup.binding import mark_intro_shown
mark_intro_shown()
context = _deferring(
UnifiedContext(
user_message="帮我总结这篇论文",
conversation_history=[{"role": "user", "content": "hi"}],
)
)
assert SetupCapability().turn_note(context, language="zh") == ""