DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(pageindex): add OSS knowledge bases and reasoning-based retrieval (#907)
Bukely_07abbd7326eb
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex e3f49df7a..7e7f0a27c 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -481,7 +481,20 @@ class AgenticChatPipeline:``runtime.providers``. All the pipeline owns is translating the turn'scontext into a :class:`ToolScope`."""- self._pageindex_docs = self._pageindex_doc_maps(context)+ self._pageindex_providers: set[str] = set()+ self._pageindex_cloud_instructions = ""+ self._pageindex_oss_instructions = ""+ pageindex_tools: list[Any] = []+ try:+ for kb, bundle in await self._pageindex_sdk_tool_bundles(context):+ self._pageindex_providers.add(bundle.provider)+ if bundle.provider == "pageindex-oss":+ self._pageindex_oss_instructions = bundle.instructions+ else:+ self._pageindex_cloud_instructions = bundle.instructions+ pageindex_tools.extend(bundle.tools)+ except Exception:+ logger.warning("PageIndex SDK tool preparation failed", exc_info=True)try:view = await build_tool_view(base_registry=self.registry,@@ -494,6 +507,8 @@ class AgenticChatPipeline:"the tools listed in the prompt can be called."),),+ overlay_tools=pageindex_tools,+ preloaded_names=[tool.name for tool in pageindex_tools],)except Exception:# ``build_tool_view`` is contractually non-raising; this is defence@@ -509,8 +524,6 @@ class AgenticChatPipeline:def _tool_scope(self, context: UnifiedContext) -> ToolScope:"""Per-turn policy inputs for the provider layer."""- from deeptutor.services.mcp.pageindex_server import PAGEINDEX_SERVER_NAME-raw_filter = context.metadata.get("mcp_tools_filter")return ToolScope(owner_id=self._current_owner_id(),@@ -521,33 +534,39 @@ class AgenticChatPipeline:if isinstance(raw_filter, list)else None),- # Attaching a PageIndex knowledge base authorises that server:- # access to the KB *is* the permission, and its tools are preloaded- # so retrieval works without a load_tools round-trip.- implicit_provider_ids=(- frozenset({PAGEINDEX_SERVER_NAME}) if self._pageindex_docs else frozenset()- ),exclusive_capability=self._exclusive_capability_active(context),)- def _pageindex_doc_maps(self, context: UnifiedContext) -> dict[str, dict[str, str]]:- """kb_name -> {file: doc_id} for bound KBs on the pageindex provider."""- out: dict[str, dict[str, str]] = {}+ async def _pageindex_sdk_tool_bundles(self, context: UnifiedContext):+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.factory import PAGEINDEX_OSS_PROVIDER, PAGEINDEX_PROVIDER+ from deeptutor.services.rag.pipelines.pageindex.tools import build_sdk_tool_bundle+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ bundles = []+ seen_providers: set[str] = set()for kb in self._selected_kbs(context):- try:- from deeptutor.multi_user.knowledge_access import resolve_kb- from deeptutor.services.rag.factory import PAGEINDEX_PROVIDER- from deeptutor.services.rag.pipelines.pageindex.pipeline import PageIndexPipeline- from deeptutor.services.rag.provider_binding import resolve_bound_provider-- resource = resolve_kb(kb, require_write=False)- base_dir = str(resource.base_dir)- if resolve_bound_provider(base_dir, resource.name) != PAGEINDEX_PROVIDER:- continue- out[kb] = PageIndexPipeline(kb_base_dir=base_dir).document_map(resource.name)- except Exception:- logger.debug("pageindex doc-map resolution failed for %r", kb, exc_info=True)- return out+ resource = resolve_kb(kb, require_write=False)+ base_dir = str(resource.base_dir)+ provider = resolve_bound_provider(base_dir, resource.name)+ if provider not in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ continue+ # Cloud tools are account-wide and OSS selection already permits at+ # most one local library, so one SDK bundle per provider is enough.+ if provider in seen_providers:+ continue+ bundles.append(+ (+ kb,+ await build_sdk_tool_bundle(+ resource.name,+ base_dir,+ provider=provider,+ ),+ )+ )+ seen_providers.add(provider)+ return bundlesdef _deferred_tools_manifest(self) -> str:view = getattr(self, "_tool_view", None)@@ -1144,12 +1163,9 @@ class AgenticChatPipeline:context: UnifiedContext,stream: StreamBus,) -> str:- # Seed every selected KB except those owned by an exclusive capability- # (an Obsidian vault is read agentically via its own tools, not seeded).- # Co-selected LlamaIndex KBs are still seeded so their context reaches- # the model even when a vault owns the turn (issue #650).- owned = self._capability_owned_kbs(context)- kbs = [kb for kb in self._selected_kbs(context) if kb not in owned]+ # Only traditional RAG KBs are pre-seeded. PageIndex and capability-owned+ # KBs are read with their tools inside the reasoning loop.+ kbs = self._coexisting_rag_kbs(context)query = (context.user_message or "").strip()if not kbs or not query:return ""@@ -1412,9 +1428,10 @@ class AgenticChatPipeline:return [str(kb).strip() for kb in context.knowledge_bases if str(kb).strip()]def _rag_kbs(self, context: UnifiedContext) -> list[str]:- """Attached KBs served by the rag tool (PageIndex KBs are read via MCP)."""- pageindex = getattr(self, "_pageindex_docs", None) or {}- return [kb for kb in self._selected_kbs(context) if kb not in pageindex]+ """Attached KBs served by rag; PageIndex KBs use their SDK tools."""+ from deeptutor.services.rag.pipelines.pageindex import is_pageindex_kb++ return [kb for kb in self._selected_kbs(context) if not is_pageindex_kb(kb)]def _capability_owned_kbs(self, context: UnifiedContext) -> set[str]:"""Selected KBs consumed by an active capability's own tools (not rag).@@ -1485,7 +1502,7 @@ class AgenticChatPipeline:round-trip.PageIndex KBs are excluded: ``_pageindex_system_note`` already lists- their documents, with the doc_ids its MCP tools need. Fails soft — a KB+ their documents for the SDK tools. Fails soft — a KBwhose files cannot be read costs the manifest, not the turn."""self._kb_manifests = []@@ -1520,35 +1537,51 @@ class AgenticChatPipeline:return f"\n{note}" if note else ""def _pageindex_system_note(self) -> str:- """Doc list + retrieval instructions for attached PageIndex KBs.+ """Retrieval instructions for attached PageIndex KBs.Populated by ``_prepare_deferred_tools`` once per turn, so the systemprompt stays byte-stable for the whole turn (KB cache prefix)."""- doc_maps = getattr(self, "_pageindex_docs", None) or {}- if not doc_maps:+ providers = getattr(self, "_pageindex_providers", None) or set()+ if not providers:return ""- lines = []- for kb, doc_map in sorted(doc_maps.items()):- listed = "; ".join(- f"{name} (doc_id: {doc_id})" for name, doc_id in sorted(doc_map.items())- )- lines.append(f"- {kb}: {listed or '(no indexed documents)'}")- docs_block = "\n".join(lines)- if self.language == "zh":- return (- "\n以下知识库使用托管的 PageIndex 引擎,其文档通过已加载的 "- "PageIndex MCP 工具阅读:先用 mcp_pageindex_get_document_structure "- "查看结构,再用 mcp_pageindex_get_page_content 读取相关页面。文档清单:\n"- f"{docs_block}"- )- return (- "\nThe following knowledge bases are on the hosted PageIndex engine; read "- "their documents with the preloaded PageIndex MCP tools: "- "mcp_pageindex_get_document_structure for the outline, then "- "mcp_pageindex_get_page_content for the relevant pages. Documents:\n"- f"{docs_block}"- )++ blocks: list[str] = []+ if "pageindex" in providers:+ instructions = str(getattr(self, "_pageindex_cloud_instructions", "") or "").strip()+ if self.language == "zh":+ blocks.append(+ "\n以下知识库使用 PageIndex Cloud。使用已加载的 pageindex_cloud_* "+ "SDK 工具先查看文档结构、再读取相关页面;不要使用 rag 读取这些 "+ "PageIndex 知识库。\n\nPageIndex SDK 阅读说明:\n"+ f"{instructions}"+ )+ else:+ blocks.append(+ "\nThe following knowledge bases use PageIndex Cloud. Read them with "+ "the preloaded pageindex_cloud_* SDK tools; inspect structure, then "+ "read relevant pages. Do not use rag to read these PageIndex knowledge "+ "bases.\n\nPageIndex SDK reading instructions:\n"+ f"{instructions}"+ )+ if "pageindex-oss" in providers:+ instructions = str(getattr(self, "_pageindex_oss_instructions", "") or "").strip()+ if self.language == "zh":+ blocks.append(+ "\n以下知识库使用 PageIndex OSS。使用已加载的 pageindex_oss_* 工具,"+ "在当前推理循环中先查看文档结构、再读取相关页面;不要使用 rag 读取这些 "+ "PageIndex 知识库。\n\nPageIndex SDK 阅读说明:\n"+ f"{instructions}"+ )+ else:+ blocks.append(+ "\nThe following knowledge bases use PageIndex OSS. Use the preloaded "+ "pageindex_oss_* tools inside this reasoning loop; inspect structure, "+ "then read relevant pages. Do not use rag to read these PageIndex knowledge "+ "bases.\n\nPageIndex SDK reading instructions:\n"+ f"{instructions}"+ )+ return "".join(blocks)def _workspace_system_note(self, context: UnifiedContext) -> str:if not getattr(self, "_exec_enabled", False):diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.pyindex bbc1659c6..fa634b35b 100644--- a/deeptutor/agents/question/pipeline.py+++ b/deeptutor/agents/question/pipeline.py@@ -472,6 +472,7 @@ class QuestionPipeline:client = build_openai_client(self.client_config)try:+ await self._prepare_pageindex_tools()return await self._run_inner(context=context,user_message=user_message,@@ -1477,9 +1478,25 @@ class QuestionPipeline:# ------------------------------------------------------------------# Tool integration (mirrors chat's policy)# ------------------------------------------------------------------+ async def _prepare_pageindex_tools(self) -> None:+ from deeptutor.services.rag.pipelines.pageindex.tools import (+ build_pageindex_tool_context,+ )++ self._pageindex_tool_context = await build_pageindex_tool_context(+ self.kb_name,+ base_registry=self.registry,+ )+ if self._pageindex_tool_context is not None:+ self.registry = self._pageindex_tool_context.registry++ def _pageindex_tool_names(self) -> list[str]:+ tool_context = getattr(self, "_pageindex_tool_context", None)+ return [tool.name for tool in tool_context.tools] if tool_context is not None else []+def _mount_flags(self, context: UnifiedContext) -> ToolMountFlags:return ToolMountFlags(- has_kb=bool(self.kb_name),+ has_kb=bool(self.kb_name and not getattr(self, "_pageindex_tool_context", None)),has_sources=bool(self._source_index(context)),has_memory=user_has_memory(),has_notebooks=user_has_notebooks(),@@ -1487,12 +1504,13 @@ class QuestionPipeline:)def _resolved_tools(self, context: UnifiedContext) -> list[str]:- return compose_enabled_tools(+ names = compose_enabled_tools(registry=self.registry,requested_tools=self.enabled_tools,optional_whitelist=self._optional_tools,mount_flags=self._mount_flags(context),)+ return list(dict.fromkeys([*names, *self._pageindex_tool_names()]))def _use_native_tools(self, context: UnifiedContext) -> bool:"""Native tool calling is only worth enabling when (a) the binding /@@ -1609,6 +1627,28 @@ class QuestionPipeline:def _kb_system_note(self) -> str:if not self.kb_name:return ""+ tool_context = getattr(self, "_pageindex_tool_context", None)+ if tool_context is not None:+ docs = (+ "; ".join(+ f"{name} (doc_id: {doc_id})"+ for name, doc_id in sorted(tool_context.documents.items())+ )+ or "(no indexed documents)"+ )+ tools = ", ".join(self._pageindex_tool_names())+ instructions = tool_context.instructions.strip()+ if self.language == "zh":+ return (+ f"已挂载 PageIndex 知识库 {self.kb_name!r}。使用这些工具在当前推理循环中"+ f"阅读文档,不要调用 rag:{tools}。文档:{docs}。"+ + (f"\nPageIndex SDK 阅读说明:\n{instructions}" if instructions else "")+ )+ return (+ f"Attached PageIndex knowledge base: {self.kb_name!r}. Read it inside this "+ f"reasoning loop with these tools; do not call rag: {tools}. Documents: {docs}."+ + (f"\nPageIndex SDK reading instructions:\n{instructions}" if instructions else "")+ )if self.language == "zh":return f"用户已挂载知识库:{self.kb_name}。调用 rag 时,kb_name 必须填这个名称。"return (@@ -1919,7 +1959,7 @@ class _BaseLoopHost:requested=len(tool_calls),limit=MAX_PARALLEL_TOOL_CALLS,)- return await dispatch_tool_calls(+ outcome = await dispatch_tool_calls(tool_calls=tool_calls,context=self._context,stream=self._stream,@@ -1945,6 +1985,12 @@ class _BaseLoopHost:),trace_id_prefix=self._trace_id_prefix,)+ pageindex_sources = [+ source for source in outcome.sources if source.get("type") == "pageindex"+ ]+ if pageindex_sources:+ await self._stream.sources(pageindex_sources, source=SOURCE, stage=self._stage)+ return outcomeasync def resolve_pause(self, dispatch: DispatchOutcome) -> bool:# ``ask_user`` would pause the turn — quiz pipeline v1 doesn't wire updiff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.pyindex ca1a173b5..9f8b8c5ba 100644--- a/deeptutor/agents/research/pipeline.py+++ b/deeptutor/agents/research/pipeline.py@@ -215,6 +215,11 @@ CITABLE_TOOLS: frozenset[str] = frozenset(})++def _is_citable_tool(name: str) -> bool:+ return name in CITABLE_TOOLS or name.startswith(("pageindex_cloud_", "pageindex_oss_"))++# Token budget for the note summarization sidecar.DEFAULT_NOTE_MAX_TOKENS = 1500# How much of the raw tool output we feed into the note summarizer.@@ -463,6 +468,7 @@ class ResearchPipeline:client = self._build_client()try:+ await self._prepare_pageindex_tools()return await self._run_inner(context=context,topic=topic,@@ -1003,6 +1009,23 @@ class ResearchPipeline:),kb_name=self.kb_name,)+ tool_context = getattr(self, "_pageindex_tool_context", None)+ if tool_context is not None:+ tools = ", ".join(tool.name for tool in tool_context.tools)+ docs = (+ "; ".join(+ f"{name} (doc_id: {doc_id})"+ for name, doc_id in sorted(tool_context.documents.items())+ )+ or "(no indexed documents)"+ )+ instructions = tool_context.instructions.strip()+ return (+ f"Attached PageIndex knowledge base: {self.kb_name!r}. Read it with "+ f"these tools inside the research loop; do not call rag: {tools}. "+ f"Documents: {docs}."+ + (f"\nPageIndex SDK reading instructions:\n{instructions}" if instructions else "")+ )return self._t("system.kb_system_note",default=(@@ -1784,6 +1807,22 @@ class ResearchPipeline:# ------------------------------------------------------------------# Tool composition for the block loop# ------------------------------------------------------------------+ async def _prepare_pageindex_tools(self) -> None:+ from deeptutor.services.rag.pipelines.pageindex.tools import (+ build_pageindex_tool_context,+ )++ self._pageindex_tool_context = await build_pageindex_tool_context(+ self.kb_name,+ base_registry=self.registry,+ )+ if self._pageindex_tool_context is not None:+ self.registry = self._pageindex_tool_context.registry++ def _pageindex_tool_names(self) -> list[str]:+ tool_context = getattr(self, "_pageindex_tool_context", None)+ return [tool.name for tool in tool_context.tools] if tool_context is not None else []+def _block_tool_names(self) -> list[str]:"""Tools available inside the per-block research loop.@@ -1806,7 +1845,11 @@ class ResearchPipeline:requested_tools=self.enabled_tools,optional_whitelist=RESEARCH_OPTIONAL_TOOLS,mount_flags=ToolMountFlags(- has_kb=bool(self.kb_name and not self._is_obsidian_kb),+ has_kb=bool(+ self.kb_name+ and not self._is_obsidian_kb+ and not getattr(self, "_pageindex_tool_context", None)+ ),has_sources=False,has_memory=user_has_memory(),has_notebooks=user_has_notebooks(),@@ -1824,7 +1867,8 @@ class ResearchPipeline:for name in RESEARCH_OBSIDIAN_READ_TOOLSif name in RESEARCH_BLOCK_TOOL_ALLOWLIST and self._tool_in_registry(name))- return names+ names.extend(self._pageindex_tool_names())+ return list(dict.fromkeys(names))def _build_block_tool_schemas(self,@@ -2392,6 +2436,11 @@ class _BlockLoopHost:),trace_id_prefix=f"research-{self._block.block_id}-iter",)+ pageindex_sources = [+ source for source in outcome.sources if source.get("type") == "pageindex"+ ]+ if pageindex_sources:+ await self._stream.sources(pageindex_sources, source=SOURCE, stage="researching")if tool_calls:self._tool_rounds_used += 1await self._summarise_and_record(tool_calls, outcome)@@ -2440,7 +2489,7 @@ class _BlockLoopHost:for tm in outcome.tool_messages:tool_call_id = str(tm.get("tool_call_id") or "")tool_name, tool_args = call_meta_by_id.get(tool_call_id, ("", {}))- if tool_name not in CITABLE_TOOLS:+ if not _is_citable_tool(tool_name):continueraw_answer = str(tm.get("content") or "")if not raw_answer.strip():diff --git a/deeptutor/agents/research/utils/citation_manager.py b/deeptutor/agents/research/utils/citation_manager.pyindex f797e4e81..57ed7ef34 100644--- a/deeptutor/agents/research/utils/citation_manager.py+++ b/deeptutor/agents/research/utils/citation_manager.py@@ -302,9 +302,11 @@ class CitationManager:try:tool_type_lower = tool_type.lower()- if tool_type_lower in ("rag", "rag_naive", "rag_hybrid"):+ if tool_type_lower in ("rag", "rag_naive", "rag_hybrid") or tool_type_lower.startswith(+ ("pageindex_cloud_", "pageindex_oss_")+ ):citation_info = self._extract_rag_citation(- citation_id, "rag", raw_answer, tool_trace, tool_metadata+ citation_id, tool_type, raw_answer, tool_trace, tool_metadata)elif tool_type_lower == "web_search":citation_info = self._extract_web_citation(diff --git a/deeptutor/api/routers/chat.py b/deeptutor/api/routers/chat.pyindex 1c8cc19bc..eaf3fc740 100644--- a/deeptutor/api/routers/chat.py+++ b/deeptutor/api/routers/chat.py@@ -11,8 +11,12 @@ import loggingfrom fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnectfrom deeptutor.agents.chat import ChatAgent, SessionManager+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEventType+from deeptutor.runtime.orchestrator import ChatOrchestratorfrom deeptutor.services.config import PROJECT_ROOT, load_config_with_mainfrom deeptutor.services.llm.config import get_llm_config+from deeptutor.services.rag.pipelines.pageindex import is_pageindex_kbfrom deeptutor.services.settings.interface_settings import get_response_languageconfig = load_config_with_main("main.yaml", PROJECT_ROOT)@@ -22,6 +26,39 @@ logger = logging.getLogger(__name__)router = APIRouter()+async def _run_pageindex_chat(+ websocket: WebSocket,+ *,+ message: str,+ history: list[dict],+ session_id: str,+ kb_name: str,+ language: str,+ enable_web_search: bool,+) -> tuple[str, dict]:+ full_response = ""+ sources = {"rag": [], "web": []}+ context = UnifiedContext(+ session_id=session_id,+ user_message=message,+ conversation_history=history,+ enabled_tools=["web_search"] if enable_web_search else [],+ knowledge_bases=[kb_name],+ language=language,+ )+ async for event in ChatOrchestrator().handle(context):+ if event.type is StreamEventType.CONTENT and event.content:+ full_response += event.content+ await websocket.send_json({"type": "stream", "content": event.content})+ elif event.type is StreamEventType.SOURCES:+ rows = event.metadata.get("sources")+ if isinstance(rows, list):+ sources["rag"].extend(rows)+ elif event.type is StreamEventType.ERROR:+ raise RuntimeError(event.content or "PageIndex chat failed")+ return full_response, sources++def _get_session_manager() -> SessionManager:return SessionManager()@@ -141,6 +178,34 @@ async def websocket_chat(websocket: WebSocket):content=message,)+ if enable_rag and kb_name and is_pageindex_kb(kb_name):+ await websocket.send_json(+ {+ "type": "status",+ "stage": "generating",+ "message": "Generating response...",+ }+ )+ full_response, sources = await _run_pageindex_chat(+ websocket,+ message=message,+ history=history,+ session_id=session_id,+ kb_name=kb_name,+ language=language,+ enable_web_search=enable_web_search,+ )+ if sources["rag"] or sources["web"]:+ await websocket.send_json({"type": "sources", **sources})+ await websocket.send_json({"type": "result", "content": full_response})+ sm.add_message(+ session_id=session_id,+ role="assistant",+ content=full_response,+ sources=sources if (sources["rag"] or sources["web"]) else None,+ )+ continue+try:llm_config = get_llm_config()api_key = llm_config.api_keydiff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.pyindex 464583004..2797c0a28 100644--- a/deeptutor/api/routers/co_writer.py+++ b/deeptutor/api/routers/co_writer.py@@ -26,6 +26,7 @@ from deeptutor.co_writer.storage import (from deeptutor.core.stream_bus import StreamBusfrom deeptutor.services.config import PROJECT_ROOT, load_config_with_mainfrom deeptutor.services.llm import clean_thinking_tags+from deeptutor.services.rag.pipelines.pageindex import is_pageindex_kbfrom deeptutor.services.settings.interface_settings import get_response_languagerouter = APIRouter()@@ -245,10 +246,14 @@ async def _run_react_edit(query = instruction or selected_text[:400]context_blocks: list[str] = []tools_used: list[str] = []+ pageindex_source = "rag" in tools and is_pageindex_kb(request.kb_name)for tool in tools:kb_name = request.kb_name if tool == "rag" else Noneif tool == "rag" and not kb_name:continue+ if tool == "rag" and pageindex_source:+ # The edit loop below receives PageIndex tools directly.+ continueif stream is not None:await stream.tool_call(tool,@@ -287,8 +292,33 @@ async def _run_react_edit()response_chunks: list[str] = []+ pageindex_sources: list[dict[str, object]] = []async def _consume() -> None:+ if pageindex_source and request.kb_name:+ from deeptutor.services.rag.pipelines.pageindex.reasoning import (+ read_pageindex_with_agent,+ )++ reading = await read_pageindex_with_agent(+ kb_name=request.kb_name,+ system_prompt=system_prompt,+ user_prompt=prompt,+ stream=stream,+ source="co_writer_react_edit",+ stage="responding",+ )+ if reading.text:+ response_chunks.append(reading.text)+ pageindex_sources.extend(reading.sources)+ tools_used.append("rag")+ if stream is not None:+ await stream.content(+ reading.text,+ source="co_writer_react_edit",+ stage="responding",+ )+ returnasync for chunk in agent.stream_llm(user_prompt=prompt,system_prompt=system_prompt,@@ -329,6 +359,7 @@ async def _run_react_edit("instruction": instruction,},"output": {"edited_text": edited_text},+ "sources": pageindex_sources,"model": agent.get_model(),})diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 498c70564..01ed4440b 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -57,6 +57,7 @@ from deeptutor.services.rag.factory import (DEFAULT_PROVIDER,GRAPHRAG_PROVIDER,LIGHTRAG_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,normalize_provider_name,provider_uses_embedding_versions,@@ -595,9 +596,9 @@ def _task_log(task_id: str, message: str, level: str = "info") -> None:log_method = getattr(logger, level, None)if callable(log_method):- log_method(f"[{task_id}] {message}")+ log_method(f"[{task_id}] {message}", extra={PROCESS_LOG_PRIVATE_ATTR: True})else:- logger.info(f"[{task_id}] {message}")+ logger.info(f"[{task_id}] {message}", extra={PROCESS_LOG_PRIVATE_ATTR: True})def _server_task_trace(task_id: str, trace: str) -> None:@@ -652,6 +653,24 @@ def _assert_provider_ready(provider: str) -> None:),)+ if provider == PAGEINDEX_OSS_PROVIDER:+ from deeptutor.services.rag.preflight import engine_preflight++ report = engine_preflight(provider)+ failed_checks = [+ check+ for check in report.get("checks", [])+ if not check.get("optional") and not check.get("ok")+ ]+ if failed_checks:+ details = "; ".join(+ str(check.get("detail") or check.get("label") or "Requirement not met")+ for check in failed_checks+ )+ raise HTTPException(+ status_code=409, detail=f"PageIndex OSS preflight failed: {details}"+ )+if provider == GRAPHRAG_PROVIDER:from deeptutor.services.rag.pipelines.graphrag.config import is_graphrag_available@@ -699,19 +718,26 @@ def _assert_provider_ready(provider: str) -> None:def _enforce_provider_formats(provider: str, files: list[UploadFile]) -> None:"""Reject files PageIndex's document endpoint does not accept, up front."""- if provider != PAGEINDEX_PROVIDER:+ if provider not in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:return- from deeptutor.services.rag.pipelines.pageindex.pipeline import SUPPORTED_EXTENSIONS+ from deeptutor.services.rag.pipelines.pageindex.pipeline import (+ OSS_SUPPORTED_EXTENSIONS,+ SUPPORTED_EXTENSIONS,+ )++ extensions = (+ OSS_SUPPORTED_EXTENSIONS if provider == PAGEINDEX_OSS_PROVIDER else SUPPORTED_EXTENSIONS+ )unsupported = [f.filenamefor f in filesif f.filename- and not f.filename.lower().endswith(".zip")- and Path(f.filename).suffix.lower() not in SUPPORTED_EXTENSIONS+ and not (provider == PAGEINDEX_PROVIDER and f.filename.lower().endswith(".zip"))+ and Path(f.filename).suffix.lower() not in extensions]if unsupported:- supported = ", ".join(sorted(SUPPORTED_EXTENSIONS))+ supported = ", ".join(sorted(extensions))raise HTTPException(status_code=400,detail=(@@ -931,7 +957,7 @@ async def run_upload_processing_task(_task_log(task_id, f"Processing {len(uploaded_file_paths)} file(s) for KB '{kb_name}'")progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,- f"Processing {len(uploaded_file_paths)} files...",+ f"Validating {len(uploaded_file_paths)} file(s)...",current=0,total=len(uploaded_file_paths),)@@ -955,6 +981,12 @@ async def run_upload_processing_task(source_root=folder_root,)_task_log(task_id, f"Staged {len(staged_files)} new file(s)")+ progress_tracker.update(+ ProgressStage.PROCESSING_DOCUMENTS,+ f"Staged {len(staged_files)} new file(s)",+ current=0,+ total=len(staged_files),+ )if not staged_files:_task_log(task_id, "No new files to process (all duplicates or invalid)")@@ -1007,6 +1039,12 @@ async def run_upload_processing_task()return+ progress_tracker.update(+ ProgressStage.PROCESSING_DOCUMENTS,+ "Saving metadata...",+ current=index_result.processed_count,+ total=len(staged_files),+ )adder.update_metadata(index_result.processed_count)if folder_id and processed_files:@@ -1138,7 +1176,6 @@ class PageIndexConfigUpdate(BaseModel):# Tri-state api_key: omit/None keeps the stored key, "" clears it, any other# value replaces it — so the masked UI never round-trips the real secret.api_key: str | None = None- api_base_url: str | None = Nonedef _pageindex_config_payload() -> dict:@@ -1147,7 +1184,6 @@ def _pageindex_config_payload() -> dict:settings = get_runtime_settings_service().load_pageindex()return {- "api_base_url": settings.get("api_base_url") or "","api_key_set": bool(settings.get("api_key")),"configured": bool(settings.get("api_key")),}@@ -1165,10 +1201,9 @@ async def get_pageindex_pipeline_config():@router.put("/rag-pipelines/pageindex/config")async def update_pageindex_pipeline_config(payload: PageIndexConfigUpdate):- """Persist the PageIndex API key / base URL for this user's account."""+ """Persist the deployment-level PageIndex Cloud credential."""try:from deeptutor.services.config import get_runtime_settings_service- from deeptutor.services.rag.pipelines.pageindex.config import DEFAULT_API_BASE_URLservice = get_runtime_settings_service()current = service.load_pageindex(include_process_overrides=False)@@ -1177,20 +1212,7 @@ async def update_pageindex_pipeline_config(payload: PageIndexConfigUpdate):if payload.api_key is not None:api_key = payload.api_key.strip()- api_base_url = current.get("api_base_url") or DEFAULT_API_BASE_URL- if payload.api_base_url is not None and payload.api_base_url.strip():- api_base_url = payload.api_base_url.strip()-- service.save_pageindex({"api_key": api_key, "api_base_url": api_base_url})-- # The built-in pageindex MCP server derives its URL/Bearer header from- # these settings — resync connections so key changes apply immediately.- try:- from deeptutor.services.mcp import get_mcp_manager-- await get_mcp_manager().reload()- except Exception:- logger.warning("MCP reload after PageIndex config change failed", exc_info=True)+ service.save_pageindex({"api_key": api_key})return _pageindex_config_payload()except Exception as e:@@ -2409,10 +2431,19 @@ async def delete_kb_file(kb_name: str, filename: str):whether a re-index is needed to purge the file from retrieval."""manager, kb_name, _ = _writable_kb(kb_name)- _assert_kb_writable_or_409(kb_name, _load_kb_entry_or_404(manager, kb_name))+ kb_entry = _load_kb_entry_or_404(manager, kb_name)+ _assert_kb_writable_or_409(kb_name, kb_entry)target = _resolve_kb_raw_file_or_404(kb_name, filename)kb_dir = manager.get_knowledge_base_path(kb_name)+ provider = _validate_registered_provider(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)+ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ from deeptutor.services.rag.factory import get_pipeline++ await get_pipeline(provider, kb_base_dir=str(manager.base_dir)).remove_document(+ kb_name,+ target.name,+ )removal = remove_raw_document(Path(kb_dir), target)return {"status": "ok",@@ -2533,6 +2564,7 @@ async def create_knowledge_base(name: str = Form(...),files: list[UploadFile] = File(...),rag_provider: str = Form(DEFAULT_PROVIDER),+ pageindex_mode: str = Form(""),rel_paths: list[str] = Form(None),):"""Create a new knowledge base and initialize it with files."""@@ -2548,6 +2580,16 @@ async def create_knowledge_base(raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")rag_provider = _validate_registered_provider(rag_provider)+ pageindex_mode = str(pageindex_mode or "").strip().lower()+ if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode not in {+ "",+ "flash",+ "standard",+ }:+ raise HTTPException(+ status_code=400,+ detail="PageIndex OSS mode must be 'flash', 'standard', or omitted.",+ )_assert_provider_ready(rag_provider)_enforce_provider_formats(rag_provider, files)allowed_extensions = FileTypeRouter.get_supported_extensions()@@ -2576,6 +2618,8 @@ async def create_knowledge_base(if name in manager.config.get("knowledge_bases", {}):manager.config["knowledge_bases"][name]["rag_provider"] = rag_providermanager.config["knowledge_bases"][name]["needs_reindex"] = False+ if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode:+ manager.config["knowledge_bases"][name]["pageindex_mode"] = pageindex_modemanager._save_config()progress_tracker = ProgressTracker(name, kb_base_dir)diff --git a/deeptutor/api/utils/task_log_stream.py b/deeptutor/api/utils/task_log_stream.pyindex ab4696a84..2f7861c11 100644--- a/deeptutor/api/utils/task_log_stream.py+++ b/deeptutor/api/utils/task_log_stream.py@@ -23,6 +23,7 @@ def _format_sse(event: str, payload: dict[str, Any]) -> str:class KnowledgeTaskStreamManager:+ _HEARTBEAT_SECONDS = 15.0_MAX_EVENTS_PER_TASK = 500_MAX_BYTES_PER_TASK = 2 * 1024 * 1024_MAX_RETAINED_TASKS = 32@@ -257,7 +258,14 @@ class KnowledgeTaskStreamManager:returnwhile True:- item = await queue.get()+ try:+ item = await asyncio.wait_for(queue.get(), timeout=self._HEARTBEAT_SECONDS)+ except TimeoutError:+ # SSE comments are ignored by EventSource but keep every+ # intermediary proxy from treating an idle indexing phase+ # as a dead connection.+ yield ": keep-alive\n\n"+ continueyield _format_sse(item["event"], item["payload"])if item["event"] in {"complete", "failed"}:break@@ -338,6 +346,10 @@ def capture_task_logs(task_id: str):manager.ensure_task(task_id)def emit(event: ProcessLogEvent) -> None:+ if event.logger in {"root", "asyncio"}:+ return+ if event.logger == "deeptutor.knowledge.progress_tracker":+ returnmanager.emit_process_log(task_id, event)with bind_log_context(task_id=task_id, capability="knowledge", sink="ui"):diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 8cb6ea1e4..65be67fd8 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -34,6 +34,8 @@ import loggingfrom typing import Anyfrom deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBusfrom deeptutor.utils.json_parser import parse_json_responsefrom ..models import (@@ -187,11 +189,17 @@ class SourceExplorer(BaseAgent):book_id: str,proposal: BookProposal,inputs: BookInputs,+ stream: StreamBus | None = None,) -> ExplorationReport:"""Run the full design → retrieve → summarise pipeline."""intent = (inputs.user_intent or proposal.description or "").strip()kb_list = list(inputs.knowledge_bases or [])+ from deeptutor.services.rag.pipelines.pageindex import (+ validate_pageindex_oss_selection,+ )++ validate_pageindex_oss_selection(kb_list)queries = await self._design_queries(proposal=proposal, inputs=inputs)if not queries:@@ -200,7 +208,7 @@ class SourceExplorer(BaseAgent):chunks: list[SourceChunk] = []if kb_list:- chunks.extend(await self._retrieve_kb_chunks(queries, kb_list))+ chunks.extend(await self._retrieve_kb_chunks(queries, kb_list, stream=stream))chunks.extend(self._collect_non_kb_chunks(inputs))@@ -363,13 +371,9 @@ class SourceExplorer(BaseAgent):self,queries: list[str],kb_list: list[str],+ *,+ stream: StreamBus | None = None,) -> list[SourceChunk]:- try:- from deeptutor.tools.rag_tool import rag_search- except Exception as exc: # pragma: no cover - import guard- logger.warning(f"rag_tool unavailable: {exc}")- return []-kb_list, connected = self.partition_knowledge_bases(kb_list)if connected:self.skipped_knowledge_bases = list(connected)@@ -379,6 +383,41 @@ class SourceExplorer(BaseAgent):", ".join(connected),)+ pageindex_kbs: list[str] = []+ traditional_kbs: list[str] = []+ for kb in kb_list:+ try:+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.factory import (+ PAGEINDEX_OSS_PROVIDER,+ PAGEINDEX_PROVIDER,+ )+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ resource = resolve_kb(kb, require_write=False)+ provider = resolve_bound_provider(str(resource.base_dir), resource.name)+ except Exception:+ provider = ""+ (+ pageindex_kbs+ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}+ else traditional_kbs+ ).append(kb)++ pageindex_chunks = await self._retrieve_pageindex_chunks(+ queries,+ pageindex_kbs,+ stream=stream,+ )+ if not traditional_kbs:+ return pageindex_chunks++ try:+ from deeptutor.tools.rag_tool import rag_search+ except Exception as exc: # pragma: no cover - import guard+ logger.warning(f"rag_tool unavailable: {exc}")+ return pageindex_chunks+async def _one_query(kb: str, query: str) -> list[SourceChunk]:try:result = await rag_search(query=query, kb_name=kb)@@ -440,7 +479,7 @@ class SourceExplorer(BaseAgent):# Query-major, not KB-major: the pair list gets trimmed below, and# trimming a KB-major list would starve the last knowledge bases of# every query. Interleaving keeps coverage even when the budget bites.- pairs = [(kb, q) for q in queries for kb in kb_list]+ pairs = [(kb, q) for q in queries for kb in traditional_kbs]if not pairs:return []@@ -450,7 +489,7 @@ class SourceExplorer(BaseAgent):pairs = pairs[:MAX_RETRIEVAL_CALLS]logger.info(f"source exploration capped at {MAX_RETRIEVAL_CALLS} retrievals "- f"({len(kb_list)} KBs x {len(queries)} queries); {dropped} skipped"+ f"({len(traditional_kbs)} KBs x {len(queries)} queries); {dropped} skipped")# Every pair is a retrieval plus, on most backends, an LLM synthesis@@ -468,7 +507,60 @@ class SourceExplorer(BaseAgent):chunks: list[SourceChunk] = []for batch in gathered:chunks.extend(batch)- return chunks+ return [*pageindex_chunks, *chunks]++ async def _retrieve_pageindex_chunks(+ self,+ queries: list[str],+ kb_list: list[str],+ *,+ stream: StreamBus | None,+ ) -> list[SourceChunk]:+ if not kb_list:+ return []+ from deeptutor.services.rag.pipelines.pageindex.reasoning import (+ read_pageindex_with_agent,+ )++ query_block = "\n".join(f"- {query}" for query in queries)++ async def read_one(kb: str) -> SourceChunk | None:+ try:+ result = await read_pageindex_with_agent(+ kb_name=kb,+ system_prompt=(+ "You are the SourceExplorer for a book workflow. Build a dense evidence "+ "brief that later planning and block-generation stages can reuse. Cover "+ "the supplied research questions, preserve concrete facts and page "+ "references, and do not draft the book itself."+ ),+ user_prompt=f"Collect source evidence for these questions:\n{query_block}",+ context=UnifiedContext(+ user_message=query_block,+ knowledge_bases=[kb],+ ),+ stream=stream,+ source="book_source_explorer",+ stage="exploration",+ )+ except Exception as exc:+ logger.warning("PageIndex SourceExplorer failed for %s: %s", kb, exc)+ return None+ if not result.text:+ return None+ return SourceChunk(+ chunk_id=f"pageindex::{kb}",+ kb_name=kb,+ source="kb",+ ref=f"pageindex::{kb}",+ text=_clip(result.text, 8000),+ score=1.0,+ query="; ".join(queries),+ metadata={"provider": result.tool_context.provider, "sources": result.sources},+ )++ rows = await asyncio.gather(*(read_one(kb) for kb in kb_list))+ return [row for row in rows if row is not None]# ------------------------------------------------------------------ ## Step 3 — non-KB sources (notebooks, chat, questions)diff --git a/deeptutor/book/blocks/_rag_helpers.py b/deeptutor/book/blocks/_rag_helpers.pyindex d6dfc39e5..cd1b53c89 100644--- a/deeptutor/book/blocks/_rag_helpers.py+++ b/deeptutor/book/blocks/_rag_helpers.py@@ -89,6 +89,20 @@ async def optional_rag_lookup(*, query: str, ctx) -> RagLookup:if not ctx.rag_enabled or not ctx.primary_kb:return RagLookup()+ try:+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.factory import PAGEINDEX_OSS_PROVIDER, PAGEINDEX_PROVIDER+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ resource = resolve_kb(ctx.primary_kb, require_write=False)+ provider = resolve_bound_provider(str(resource.base_dir), resource.name)+ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ # PageIndex evidence is gathered once by SourceExplorer's own agent+ # loop and reused through relevant_chunks; never fall back to search().+ return RagLookup()+ except Exception:+ pass+try:from deeptutor.tools.rag_tool import rag_searchdiff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pyindex ad96012c7..1989a48bf 100644--- a/deeptutor/book/engine.py+++ b/deeptutor/book/engine.py@@ -476,6 +476,7 @@ class BookEngine:book_id=book.id,proposal=proposal,inputs=inputs,+ stream=bus,)self.storage.save_exploration(book.id, exploration)if (book.metadata or {}).get("exploration_failed"):diff --git a/deeptutor/co_writer/edit_agent.py b/deeptutor/co_writer/edit_agent.pyindex 13a1ff564..b74218887 100644--- a/deeptutor/co_writer/edit_agent.py+++ b/deeptutor/co_writer/edit_agent.py@@ -14,6 +14,7 @@ from deeptutor.co_writer.storage import _atomic_write_jsonfrom deeptutor.runtime.registry.tool_registry import get_tool_registryfrom deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.path_service import get_path_service+from deeptutor.services.rag.pipelines.pageindex import is_pageindex_kbfrom deeptutor.tools.rag_tool import rag_searchfrom deeptutor.tools.web_search import web_search@@ -140,7 +141,8 @@ class EditAgent(BaseAgent):context = ""tool_call_file = None- if source:+ pageindex_source = source == "rag" and is_pageindex_kb(kb_name)+ if source and not pageindex_source:context, tool_call_file = await self.gather_context(source=source,query=instruction,@@ -181,16 +183,42 @@ class EditAgent(BaseAgent):)user_prompt += text_template.format(text=text)- # Call LLM using inherited method+ # PageIndex reading belongs inside the edit reasoning loop; traditional+ # RAG and web sources keep the existing prefetch path above.self.logger.info(f"Calling LLM for {action}...")- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage=f"edit_{action}",- ):- _chunks.append(_c)- response = clean_thinking_tags("".join(_chunks), self.binding, self.get_model())+ if pageindex_source and kb_name:+ from deeptutor.services.rag.pipelines.pageindex.reasoning import (+ read_pageindex_with_agent,+ )++ reading = await read_pageindex_with_agent(+ kb_name=kb_name,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ source="co_writer",+ stage=f"edit_{action}",+ )+ response = clean_thinking_tags(reading.text, self.binding, self.get_model())+ tool_call_file = save_tool_call(+ operation_id,+ "pageindex",+ {+ "type": "pageindex",+ "timestamp": datetime.now().isoformat(),+ "operation_id": operation_id,+ "kb_name": kb_name,+ "sources": reading.sources,+ },+ )+ else:+ _chunks: list[str] = []+ async for _c in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ stage=f"edit_{action}",+ ):+ _chunks.append(_c)+ response = clean_thinking_tags("".join(_chunks), self.binding, self.get_model())# Record operation historyappend_history(diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pyindex 498181b40..097e91b68 100644--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -294,7 +294,7 @@ class DocumentAdder:self.progress_tracker.update(ProgressStage.PROCESSING_FILE,f"Indexing {doc_file.name}",- current=idx,+ current=len(processed_files),total=total_files,)@@ -307,6 +307,13 @@ class DocumentAdder:# requests once per indexed file (#777).await asyncio.to_thread(self._record_successful_hash, doc_file)logger.info(f"Processed: {doc_file.name}")+ if self.progress_tracker is not None:+ self.progress_tracker.update(+ ProgressStage.PROCESSING_FILE,+ f"Indexed {doc_file.name}",+ current=len(processed_files),+ total=total_files,+ )else:error = "Provider returned failure without details."failures.append(DocumentIndexFailure(doc_file, error))diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 360abd056..a5ef68346 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -33,6 +33,8 @@ from deeptutor.services.rag.factory import (IMA_PROVIDER,KNOWN_PROVIDERS,LIGHTRAG_SERVER_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,+ PAGEINDEX_PROVIDER,has_ready_provider_index,normalize_provider_name,provider_uses_embedding_versions,@@ -465,9 +467,20 @@ class KnowledgeBaseManager:kb_config["progress"] = progressif status == "ready":- fp = _get_embedding_fingerprint()- if fp:- kb_config["embedding_model"], kb_config["embedding_dim"] = fp+ provider = normalize_provider_name(kb_config.get("rag_provider"))+ pageindex_provider = provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}+ if pageindex_provider:+ for key in (+ "embedding_model",+ "embedding_dim",+ "embedding_signature",+ "embedding_mismatch",+ ):+ kb_config.pop(key, None)+ else:+ fp = _get_embedding_fingerprint()+ if fp:+ kb_config["embedding_model"], kb_config["embedding_dim"] = fp# Record the active signature + the on-disk version registry so# the UI can render version chips without recomputing.try:@@ -475,12 +488,11 @@ class KnowledgeBaseManager:signature_from_embedding_config,)- sig = signature_from_embedding_config()+ sig = None if pageindex_provider else signature_from_embedding_config()if sig is not None:kb_config["embedding_signature"] = sig.hash()kb_dir = self.base_dir / nameif kb_dir.is_dir():- provider = normalize_provider_name(kb_config.get("rag_provider"))kb_config["index_versions"] = inspect_kb_versions(kb_dir, provider)except Exception: # pragma: no cover - best-effort metadatapass@@ -1306,7 +1318,8 @@ class KnowledgeBaseManager:kb_probe_dir = kb_dir if dir_exists else Nonerag_initialized = has_ready_provider- active_signature = signature_from_embedding_config()+ pageindex_provider = rag_provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}+ active_signature = None if pageindex_provider else signature_from_embedding_config()if provider_uses_embedding_versions(rag_provider):matched_entry = (find_matching_version(kb_probe_dir, active_signature)diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pyindex cdcd9a571..c2172f5dc 100644--- a/deeptutor/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -71,6 +71,31 @@ class ChatOrchestrator:if not context.session_id:context.session_id = str(uuid.uuid4())+ try:+ from deeptutor.services.rag.pipelines.pageindex import (+ validate_pageindex_oss_selection,+ )++ validate_pageindex_oss_selection(context.knowledge_bases)+ except ValueError as exc:+ bus = StreamBus()+ await bus.error(+ str(exc),+ source="orchestrator",+ metadata={"turn_terminal": True, "status": "failed"},+ )+ await bus.emit(+ StreamEvent(+ type=StreamEventType.DONE,+ source="orchestrator",+ metadata={"status": "failed"},+ )+ )+ await bus.close()+ async for event in bus.subscribe():+ yield event+ return+cap_name = context.active_capability or "chat"capability = self._cap_registry.get(cap_name)diff --git a/deeptutor/runtime/providers/authorize.py b/deeptutor/runtime/providers/authorize.pyindex 10b5cf0f1..6d80537c8 100644--- a/deeptutor/runtime/providers/authorize.py+++ b/deeptutor/runtime/providers/authorize.py@@ -27,7 +27,6 @@ def authorize_mcp_tools(*,scope: ToolScope,user_grant: Allowlist,- implicit_names: Iterable[str] = (),owned_names: Iterable[str] = (),) -> Allowlist:"""Which MCP tool names *scope* may see and call.@@ -37,19 +36,13 @@ def authorize_mcp_tools(*empty* for a non-admin whose grant omits the field, so deploymentservers fail closed).- ``implicit_names`` are the tool names that ``scope.implicit_provider_ids``- resolved to against the live pool — authorised by holding the resource.-``owned_names`` are tools from servers the caller configured themselves.They are authorised by ownership: the admin grant governs the deployment'sshared servers, and applying it to a user's own server would makeself-service configuration silently useless."""if scope.exclusive_capability:- # An exclusive knowledge capability replaces the tool surface. Only- # tools authorised by an attached resource survive — they are already- # preloaded, so the turn never needs to advertise anything else.- return Allowlist.of(implicit_names)+ return Allowlist.of([])caller = Allowlist.of(scope.caller_whitelist)# A partner turn is gated by the partner's own configured filter. It must@@ -60,7 +53,7 @@ def authorize_mcp_tools(if shared_gate.is_unrestricted:return Allowlist.unrestricted()- return shared_gate.widen(owned_names).widen(implicit_names)+ return shared_gate.widen(owned_names)__all__ = ["authorize_mcp_tools"]diff --git a/deeptutor/runtime/providers/scope.py b/deeptutor/runtime/providers/scope.pyindex f938640a5..41175323b 100644--- a/deeptutor/runtime/providers/scope.py+++ b/deeptutor/runtime/providers/scope.py@@ -32,12 +32,6 @@ class ToolScope:#: The caller's own configured whitelist (a partner's ``mcp_tools``).#: ``None`` = the caller imposes no restriction.caller_whitelist: frozenset[str] | None = None- #: Providers authorised by holding a *resource* rather than by a grant:- #: attaching a PageIndex knowledge base authorises that server. Given as- #: provider ids because the turn knows which resources it holds, not which- #: tool names they expand to — the view resolves that against the live- #: pool.- implicit_provider_ids: frozenset[str] = frozenset()#: An exclusive knowledge capability owns the turn and replaces the tool#: surface, so provider tools must not be advertised (see ``authorize``).exclusive_capability: bool = Falsediff --git a/deeptutor/runtime/providers/view.py b/deeptutor/runtime/providers/view.pyindex 512f753e9..893a3bc78 100644--- a/deeptutor/runtime/providers/view.py+++ b/deeptutor/runtime/providers/view.py@@ -16,7 +16,7 @@ from __future__ import annotationsimport asynciofrom dataclasses import dataclassimport logging-from typing import Any+from typing import Any, Iterablefrom deeptutor.core.tool_protocol import BaseTool, ToolLookupfrom deeptutor.runtime.providers.allowlist import Allowlist@@ -24,7 +24,6 @@ from deeptutor.runtime.providers.authorize import authorize_mcp_toolsfrom deeptutor.runtime.providers.scope import ToolScopefrom deeptutor.runtime.registry.deferred_tools import (DeferredToolLoader,- provider_identity,render_deferred_tools_manifest,)from deeptutor.runtime.registry.scoped_registry import ScopedToolRegistry@@ -74,6 +73,8 @@ async def build_tool_view(scope: ToolScope,language: str = "en",refusal_message: str = "",+ overlay_tools: Iterable[BaseTool] = (),+ preloaded_names: Iterable[str] = (),) -> ProviderToolView:"""Resolve the provider tools *scope* may use this turn."""try:@@ -82,6 +83,8 @@ async def build_tool_view(scope=scope,language=language,refusal_message=refusal_message,+ overlay_tools=tuple(overlay_tools),+ preloaded_names=frozenset(preloaded_names),)except Exception:logger.warning("provider tool view assembly failed; continuing without", exc_info=True)@@ -94,6 +97,8 @@ async def _build(scope: ToolScope,language: str,refusal_message: str,+ overlay_tools: tuple[BaseTool, ...],+ preloaded_names: frozenset[str],) -> ProviderToolView:from deeptutor.services.mcp import get_mcp_manager, load_loaded_tools@@ -103,21 +108,12 @@ async def _build(shared_pool = list(base_registry.deferred_tools())owned_pool = await _owned_tools(manager, scope)cli_pool = _cli_app_tools(scope)- if not shared_pool and not owned_pool and not cli_pool:+ if not shared_pool and not owned_pool and not cli_pool and not overlay_tools:return ProviderToolView.empty(base_registry)- # Resolve resource-derived authorisation (e.g. an attached PageIndex KB- # authorises that server) from provider ids to concrete tool names.- implicit_names = {- tool.get_definition().name- for tool in shared_pool- if provider_identity(tool)[1] in scope.implicit_provider_ids- }-allowed = authorize_mcp_tools(scope=scope,user_grant=_user_grant(scope),- implicit_names=implicit_names,# Servers the caller configured themselves are authorised by ownership:# the admin grant governs the deployment's shared servers, and applying# it here would make self-service configuration silently useless.@@ -128,10 +124,13 @@ async def _build(# names it approved are widened in here. Widening an unrestricted allowlist# is identity, so an administrator is unaffected.allowed = allowed.widen(tool.get_definition().name for tool in cli_pool)+ # Resource-bound overlays (including PageIndex SDK tools) are authorised by+ # possession of the selected resource and live only in this turn's registry.+ allowed = allowed.widen(tool.get_definition().name for tool in overlay_tools)pool = tuple(tool- for tool in (*shared_pool, *owned_pool, *cli_pool)+ for tool in (*shared_pool, *owned_pool, *cli_pool, *overlay_tools)if allowed.allows(tool.get_definition().name))registry = ScopedToolRegistry(@@ -139,7 +138,7 @@ async def _build(# Owner-scoped tools live only in this turn's overlay — they are never# published to the process registry, so two accounts whose servers share# a name cannot resolve to each other's session.- overlay=[*owned_pool, *cli_pool],+ overlay=[*owned_pool, *cli_pool, *overlay_tools],allowed=allowed,refusal_message=refusal_message,)@@ -154,7 +153,7 @@ async def _build(# Resource-authorised tools are preloaded: holding the resource is the# permission, so the model should not have to spend a `load_tools`# round-trip before its first retrieval.- loaded=load_loaded_tools(scope.session_id) | implicit_names,+ loaded=load_loaded_tools(scope.session_id) | set(preloaded_names),allowed=allowed.as_set(),)manifest = (diff --git a/deeptutor/runtime/registry/deferred_tools.py b/deeptutor/runtime/registry/deferred_tools.pyindex c62e5b9b2..8e983c1d9 100644--- a/deeptutor/runtime/registry/deferred_tools.py+++ b/deeptutor/runtime/registry/deferred_tools.py@@ -47,6 +47,8 @@ def _group_key(tool: BaseTool) -> tuple[str, str]:kind, provider_id = provider_identity(tool)if kind == "cli":return _CLI_GROUP+ if kind == "pageindex":+ return ("pageindex", provider_id)if provider_id:return ("mcp", provider_id)return _OTHER_GROUP@@ -96,6 +98,9 @@ def render_deferred_tools_manifest(tools: list[BaseTool], *, language: str = "en_kind, provider_id = groupif group == _CLI_GROUP:header = "### CLI 应用" if zh else "### CLI apps"+ elif group[0] == "pageindex":+ mode = "Cloud" if provider_id == "pageindex" else "OSS"+ header = f"### PageIndex {mode}"elif group == _OTHER_GROUP:header = "### 其他" if zh else "### Other"else:diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex ce2e3f568..9148feca1 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -222,14 +222,13 @@ DEFAULT_MINERU_SETTINGS: dict[str, Any] = _DEFAULT_MINERU_ENGINE# PageIndex cloud RAG engine. A KB indexed with the ``pageindex`` provider# ships its documents to the hosted PageIndex service for tree building and-# reasoning-based retrieval. Only an API key (per PageIndex account) and the-# API base URL are needed; the same key is reused by every ``pageindex`` KB.+# reasoning-based retrieval. The SDK owns the official endpoint; the same+# deployment-level credential is reused by every ``pageindex`` KB.# Kept in its own JSON file so the credential lives beside other per-feature# settings and never leaks into model/network config.DEFAULT_PAGEINDEX_SETTINGS: dict[str, Any] = {"version": 1,"api_key": "",- "api_base_url": "https://api.pageindex.ai",}# Tencent IMA. The credential pair (``client_id`` + ``api_key``, issued at@@ -767,16 +766,12 @@ class RuntimeSettingsService:payload = dict(settings)if value := self._process_env_value("PAGEINDEX_API_KEY"):payload["api_key"] = value- if value := self._process_env_value("PAGEINDEX_API_BASE_URL"):- payload["api_base_url"] = valuereturn self._normalize_pageindex(payload)def _normalize_pageindex(self, settings: dict[str, Any]) -> dict[str, Any]:return {"version": 1,"api_key": _string(settings.get("api_key")),- "api_base_url": _string(settings.get("api_base_url")).rstrip("/")- or "https://api.pageindex.ai",}def _apply_ima_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:diff --git a/deeptutor/services/mcp/config.py b/deeptutor/services/mcp/config.pyindex c0562f8d9..3998b095d 100644--- a/deeptutor/services/mcp/config.py+++ b/deeptutor/services/mcp/config.py@@ -47,8 +47,7 @@ class MCPServerConfig(BaseModel):# behaviourtool_timeout: int = Field(default=30, ge=1, le=600)enabled_tools: list[str] = Field(default_factory=lambda: ["*"])- # Blocklist applied after ``enabled_tools`` — for "everything except X"- # entries (used by the built-in pageindex server).+ # Blocklist applied after ``enabled_tools`` — for "everything except X".disabled_tools: list[str] = Field(default_factory=list)enabled: bool = True# authenticationdiff --git a/deeptutor/services/mcp/manager.py b/deeptutor/services/mcp/manager.pyindex 6d91fc512..435347db8 100644--- a/deeptutor/services/mcp/manager.py+++ b/deeptutor/services/mcp/manager.py@@ -46,15 +46,14 @@ from deeptutor.services.mcp.config import (MCPServerConfig,load_mcp_config,)-from deeptutor.services.mcp.pageindex_server import with_builtin_serverslogger = logging.getLogger(__name__)_CONNECT_TIMEOUT_S = 15_NAME_SANITIZE_RE = re.compile(r"[^a-zA-Z0-9_-]")-#: Owner key for the deployment's own servers (the admin ``mcp.json`` plus-#: injected built-ins). Connections are keyed by ``(owner, server_name)`` so a+#: Owner key for the deployment's servers from the admin ``mcp.json``.+#: Connections are keyed by ``(owner, server_name)`` so a#: future per-user server cannot collide with — or be routed into — another#: tenant's live session.SHARED_OWNER = "_shared"@@ -167,7 +166,10 @@ class MCPToolAdapter(BaseTool):)return ToolResult(content=text,- metadata={"mcp_server": self._server_name, "mcp_tool": self._original_name},+ metadata={+ "mcp_server": self._server_name,+ "mcp_tool": self._original_name,+ },)@@ -270,13 +272,13 @@ class MCPConnectionManager:async with self._lock_for(SHARED_OWNER):if self._started:return- await self._sync_to_config(with_builtin_servers(load_mcp_config()))+ await self._sync_to_config(load_mcp_config())self._started = Trueasync def reload(self) -> None:"""Re-read the persisted config and apply the diff to live connections."""async with self._lock_for(SHARED_OWNER):- await self._sync_to_config(with_builtin_servers(load_mcp_config()))+ await self._sync_to_config(load_mcp_config())self._started = Trueasync def shutdown(self) -> None:diff --git a/deeptutor/services/mcp/pageindex_server.py b/deeptutor/services/mcp/pageindex_server.pydeleted file mode 100644index 409494ff1..000000000--- a/deeptutor/services/mcp/pageindex_server.py+++ /dev/null@@ -1,50 +0,0 @@-"""Built-in PageIndex MCP server entry.--PageIndex retrieval is agentic: the chat agent reads documents through the-hosted PageIndex MCP server instead of a REST retrieval endpoint. When a-PageIndex API key is configured, the connection manager overlays a reserved-``pageindex`` server entry onto the user-editable MCP config at load time —-it is never persisted to ``mcp.json``, and a user-defined server of the same-name always wins. Credentials stay single-sourced in the pageindex runtime-settings; saving a new key hot-reloads the connection (the Bearer header-changes the connection signature).-"""--from __future__ import annotations--from deeptutor.services.mcp.config import MCPConfig, MCPServerConfig--PAGEINDEX_SERVER_NAME = "pageindex"---def builtin_pageindex_server() -> MCPServerConfig | None:- """The injected server entry, or ``None`` when no API key is configured."""- from deeptutor.services.rag.pipelines.pageindex.config import get_pageindex_config-- try:- cfg = get_pageindex_config()- except Exception:- return None- return MCPServerConfig(- type="streamableHttp",- url=cfg.api_base_url.rstrip("/") + "/mcp",- headers={"Authorization": f"Bearer {cfg.api_key}"},- tool_timeout=120,- # remove_document is the one api-proxy tool DeepTutor blocks: an agent- # deleting a cloud doc would silently orphan the doc_ids in the local- # KB manifest. Everything else the server advertises passes through.- disabled_tools=["remove_document"],- )---def with_builtin_servers(config: MCPConfig) -> MCPConfig:- """Overlay code-injected servers onto *config*; user entries win."""- if PAGEINDEX_SERVER_NAME in config.servers:- return config- entry = builtin_pageindex_server()- if entry is None:- return config- return MCPConfig(servers={**config.servers, PAGEINDEX_SERVER_NAME: entry})---__all__ = ["PAGEINDEX_SERVER_NAME", "builtin_pageindex_server", "with_builtin_servers"]diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.pyindex 1249d1d30..fbf4d90c8 100644--- a/deeptutor/services/rag/factory.py+++ b/deeptutor/services/rag/factory.py@@ -4,8 +4,8 @@ Selects a KB's index/retrieve engine by provider name. Three pipelines shiptoday:* ``llamaindex`` (default) — local vector retrieval with hybrid BM25 fusion.-* ``pageindex`` — hosted, vectorless reasoning retrieval (needs an- API key configured under Knowledge → RAG settings).+* ``pageindex`` — PageIndex Cloud (deployment credential + MCP tools).+* ``pageindex-oss`` — local PageIndex library using the active chat LLM.* ``graphrag`` — local knowledge-graph retrieval (microsoft/graphrag);optional dependency, ``pip install 'deeptutor[graphrag]'``.* ``lightrag`` — graph + vector retrieval (HKUDS/LightRAG, multimodal@@ -29,6 +29,7 @@ from typing import Any, Dict, List, Optional, TupleDEFAULT_PROVIDER = "llamaindex"PAGEINDEX_PROVIDER = "pageindex"+PAGEINDEX_OSS_PROVIDER = "pageindex-oss"GRAPHRAG_PROVIDER = "graphrag"LIGHTRAG_PROVIDER = "lightrag"LIGHTRAG_SERVER_PROVIDER = "lightrag-server"@@ -40,6 +41,7 @@ KNOWN_PROVIDERS = frozenset({DEFAULT_PROVIDER,PAGEINDEX_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,GRAPHRAG_PROVIDER,LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,@@ -82,6 +84,7 @@ def version_matches_provider(entry: dict[str, Any], provider: Optional[str]) ->if resolved == DEFAULT_PROVIDER:return entry_provider in {"", DEFAULT_PROVIDER} and signature not in {PAGEINDEX_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,GRAPHRAG_PROVIDER,LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,@@ -118,12 +121,12 @@ def provider_failure_summary(def _build_pipeline(provider: str, kb_base_dir: Optional[str], **kwargs: Any):- if provider == PAGEINDEX_PROVIDER:+ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:from .pipelines.pageindex.pipeline import PageIndexPipelineif kb_base_dir is not None:kwargs.setdefault("kb_base_dir", kb_base_dir)- return PageIndexPipeline(**kwargs)+ return PageIndexPipeline(provider=provider, **kwargs)if provider == GRAPHRAG_PROVIDER:from .pipelines.graphrag.pipeline import GraphRagPipeline@@ -188,6 +191,15 @@ def list_pipelines() -> List[Dict[str, Any]]:except Exception:pageindex_ready = False+ try:+ from .pipelines.pageindex.client import resolve_oss_sdk_config++ resolve_oss_sdk_config()+ pageindex_oss_ready, pageindex_oss_reason = True, ""+ except Exception as exc:+ pageindex_oss_ready = False+ pageindex_oss_reason = str(exc)+try:from .pipelines.ima.config import is_ima_configured@@ -231,11 +243,19 @@ def list_pipelines() -> List[Dict[str, Any]]:},{"id": PAGEINDEX_PROVIDER,- "name": "PageIndex",- "description": "Hosted, vectorless engine: the chat agent reads documents through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.",+ "name": "PageIndex Cloud",+ "description": "Hosted, vectorless engine: the chat agent reads documents through PageIndex SDK tools. Requires an API key; PDF, Office, text and Markdown formats.","configured": pageindex_ready,"requires_api_key": True,},+ {+ "id": PAGEINDEX_OSS_PROVIDER,+ "name": "PageIndex OSS",+ "description": "Local, chunkless and vectorless document indexing. Uses the active LLM and accepts PDF files.",+ "configured": pageindex_oss_ready,+ "requires_api_key": False,+ "readiness_reason": pageindex_oss_reason,+ },{"id": GRAPHRAG_PROVIDER,"name": "GraphRAG",@@ -288,6 +308,7 @@ def list_pipelines() -> List[Dict[str, Any]]:__all__ = ["DEFAULT_PROVIDER","PAGEINDEX_PROVIDER",+ "PAGEINDEX_OSS_PROVIDER","GRAPHRAG_PROVIDER","LIGHTRAG_PROVIDER","LIGHTRAG_SERVER_PROVIDER",diff --git a/deeptutor/services/rag/index_probe.py b/deeptutor/services/rag/index_probe.pyindex d23335109..0ba71dbd7 100644--- a/deeptutor/services/rag/index_probe.py+++ b/deeptutor/services/rag/index_probe.py@@ -18,6 +18,7 @@ from deeptutor.services.rag.factory import (DEFAULT_PROVIDER,GRAPHRAG_PROVIDER,LIGHTRAG_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,normalize_provider_name,version_matches_provider,@@ -44,8 +45,8 @@ def inspect_provider_index(path = Path(storage_dir) if storage_dir is not None else Noneif path is None:return ProviderIndexProbe(resolved, None, False, "No storage path recorded.")- if resolved == PAGEINDEX_PROVIDER:- return _inspect_pageindex(path)+ if resolved in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ return _inspect_pageindex(path, resolved)if resolved == GRAPHRAG_PROVIDER:return _inspect_graphrag(path)if resolved == LIGHTRAG_PROVIDER:@@ -173,21 +174,40 @@ def _inspect_llamaindex(storage_dir: Path) -> ProviderIndexProbe:)-def _inspect_pageindex(storage_dir: Path) -> ProviderIndexProbe:+def _inspect_pageindex(storage_dir: Path, provider: str) -> ProviderIndexProbe:from deeptutor.services.rag.pipelines.pageindex import storage- manifest = storage.read_manifest(storage_dir)+ manifest = storage.read_manifest(storage_dir, provider=provider)ids = storage.doc_ids(manifest)if not ids:return ProviderIndexProbe(- PAGEINDEX_PROVIDER,+ provider,str(storage_dir),False,"PageIndex manifest has no document ids.",doc_count=0,)+ if provider == PAGEINDEX_OSS_PROVIDER:+ docs_dir = storage.sdk_storage_path(storage_dir) / "docs"+ missing = [+ doc_id+ for doc_id in ids+ if not all(+ (docs_dir / doc_id / name).is_file()+ for name in ("doc.json", "tree.json", "pages.json")+ )+ ]+ if missing:+ return ProviderIndexProbe(+ provider,+ str(storage_dir),+ False,+ "PageIndex OSS Local Library is missing document artifacts.",+ doc_count=len(ids) - len(missing),+ diagnostics={"missing_doc_ids": missing[:10]},+ )return ProviderIndexProbe(- PAGEINDEX_PROVIDER,+ provider,str(storage_dir),True,doc_count=len(ids),diff --git a/deeptutor/services/rag/pipelines/pageindex/__init__.py b/deeptutor/services/rag/pipelines/pageindex/__init__.pyindex 2e4a2e2b1..707eee2d6 100644--- a/deeptutor/services/rag/pipelines/pageindex/__init__.py+++ b/deeptutor/services/rag/pipelines/pageindex/__init__.py@@ -1,14 +1,47 @@-"""PageIndex cloud-backed RAG pipeline.+"""PageIndex Cloud and OSS knowledge-base lifecycle.-A KB indexed with the ``pageindex`` provider ships its documents to the hosted-PageIndex service (https://pageindex.ai), which builds a hierarchical tree per-document and serves reasoning-based, vectorless retrieval. DeepTutor's own chat-LLM still writes the final answer — only retrieval is delegated. The pipeline-talks to PageIndex's documented REST API directly (see ``client``).+Both providers use turn-scoped PageIndex SDK tools: Cloud delegates its transport+to the SDK, while OSS binds the same interface to the KB's Local Library. Neither+provider answers through ``RAGPipeline.search``."""from __future__ import annotationsfrom .pipeline import PageIndexPipeline-__all__ = ["PageIndexPipeline"]++def _bound_pageindex_provider(kb_name: str | None) -> str | None:+ if not kb_name:+ return None+ try:+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ resource = resolve_kb(kb_name, require_write=False)+ return resolve_bound_provider(resource.base_dir, resource.name)+ except Exception:+ return None+++def is_pageindex_kb(kb_name: str | None) -> bool:+ from deeptutor.services.rag.factory import PAGEINDEX_OSS_PROVIDER, PAGEINDEX_PROVIDER++ return _bound_pageindex_provider(kb_name) in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}+++def validate_pageindex_oss_selection(knowledge_bases: list[str]) -> None:+ from deeptutor.services.rag.factory import PAGEINDEX_OSS_PROVIDER++ selected = [+ name+ for name in dict.fromkeys(str(item or "").strip() for item in knowledge_bases)+ if name and _bound_pageindex_provider(name) == PAGEINDEX_OSS_PROVIDER+ ]+ if len(selected) > 1:+ raise ValueError(+ "Select at most one PageIndex OSS knowledge base per request. "+ f"Selected: {', '.join(selected)}"+ )+++__all__ = ["PageIndexPipeline", "is_pageindex_kb", "validate_pageindex_oss_selection"]diff --git a/deeptutor/services/rag/pipelines/pageindex/client.py b/deeptutor/services/rag/pipelines/pageindex/client.pyindex 7413de58f..37b105709 100644--- a/deeptutor/services/rag/pipelines/pageindex/client.py+++ b/deeptutor/services/rag/pipelines/pageindex/client.py@@ -1,132 +1,146 @@-"""Thin async HTTP client for the hosted PageIndex REST API.--Upload and lifecycle only — retrieval happens agent-side through the PageIndex-MCP server:--* ``POST /doc/`` — submit a document for processing → ``doc_id``-* ``GET /doc/{doc_id}/`` — poll processing status-* ``DELETE /doc/{doc_id}/`` — best-effort cloud cleanup--The client keeps the dependency surface to ``httpx`` (already a dependency)-and is trivially mockable: inject an ``httpx`` transport or swap the whole-client out via ``PageIndexPipeline(client=...)`` in tests.-"""+"""Async adapter around the synchronous PageIndex SDK clients."""from __future__ import annotationsimport asyncio-import logging+from functools import lru_cachefrom pathlib import Path-from typing import Any, Optional+from typing import Any-import httpx+from deeptutor.services.provider_registry import find_by_name, strip_provider_prefixfrom .config import PageIndexConfig-logger = logging.getLogger(__name__)-_TERMINAL_OK = {"completed", "complete", "done", "ready", "success", "finished"}-_TERMINAL_FAIL = {"failed", "error", "cancelled", "canceled"}+def _sdk_types():+ from pageindex import PageIndexCloudClient, PageIndexLocalClient++ return PageIndexCloudClient, PageIndexLocalClient-class PageIndexAPIError(RuntimeError):- """Raised when the PageIndex API returns an error or unexpected payload."""+@lru_cache(maxsize=1)+def _cloud_sdk_client(api_key: str):+ """Reuse the SDK's MCP bridge until the global Cloud key changes."""+ cloud_type, _ = _sdk_types()+ return cloud_type(api_key)+++def _prefixed_model(prefix: str, model: str) -> str:+ return model if model.startswith(f"{prefix}/") else f"{prefix}/{model}"+++def resolve_oss_sdk_config() -> tuple[str, dict[str, Any]]:+ """Translate DeepTutor's active LLM into PageIndex's indexing lane."""+ from deeptutor.services.config import resolve_llm_runtime_config++ cfg = resolve_llm_runtime_config()+ model = str(getattr(cfg, "model", "") or "").strip()+ binding = str(+ getattr(cfg, "binding", None) or getattr(cfg, "provider_name", None) or "openai"+ ).strip()+ spec = find_by_name(binding)+ if not model:+ raise RuntimeError(+ "PageIndex OSS needs an active LLM. Configure one under Settings → Catalog."+ )+ if (+ spec is None+ or spec.is_oauth+ or spec.backend+ in {+ "openai_codex",+ "github_copilot",+ "codebuddy",+ }+ ):+ raise RuntimeError(+ "PageIndex OSS indexing needs an API-key or local LLM profile; "+ "the active OAuth-only provider cannot be used."+ )++ resolved_model = strip_provider_prefix(model, spec)+ prefix = {+ "anthropic": "anthropic",+ "azure_openai": "azure",+ "openai_compat": "openai",+ }.get(spec.backend)+ if prefix is None:+ raise RuntimeError("The active LLM transport is not supported by PageIndex OSS indexing.")++ sdk_model = _prefixed_model(prefix, resolved_model)+ backend: dict[str, Any] = {}+ api_key = str(getattr(cfg, "api_key", "") or "").strip()+ base_url = str(getattr(cfg, "base_url", "") or "").strip()+ api_version = str(getattr(cfg, "api_version", "") or "").strip()+ headers = getattr(cfg, "extra_headers", None)++ if spec.backend == "openai_compat":+ # PageIndex treats ``openai/...`` as the OpenAI-compatible fast path;+ # this also preserves gateway model ids such as anthropic/claude-*.+ backend["api_key"] = api_key or "sk-no-key-required"+ elif api_key:+ backend["api_key"] = api_key++ if base_url:+ backend["api_base"] = base_url+ if api_version and spec.backend != "openai_compat":+ backend["api_version"] = api_version+ if isinstance(headers, dict) and headers:+ if spec.backend == "openai_compat":+ backend["default_headers"] = dict(headers)+ else:+ backend["extra_headers"] = dict(headers)++ return sdk_model, backendclass PageIndexClient:- """Stateless wrapper over the PageIndex REST API.-- A fresh :class:`httpx.AsyncClient` is opened per call so the object is safe- to construct once and reuse across requests without managing a connection- lifecycle.- """-- def __init__(- self,- config: PageIndexConfig,- *,- timeout: float = 120.0,- transport: Optional[httpx.AsyncBaseTransport] = None,- ) -> None:- self._config = config- self._timeout = timeout- self._transport = transport-- def _open(self) -> httpx.AsyncClient:- return httpx.AsyncClient(- base_url=self._config.api_base_url,- headers={"Authorization": f"Bearer {self._config.api_key}"},- timeout=self._timeout,- transport=self._transport,+ """Small async facade used by the DeepTutor RAG lifecycle."""++ def __init__(self, sdk_client: Any) -> None:+ self.sdk_client = sdk_client++ @classmethod+ def cloud(cls, config: PageIndexConfig) -> "PageIndexClient":+ return cls(_cloud_sdk_client(config.api_key))++ @classmethod+ def local(cls, storage_path: str | Path) -> "PageIndexClient":+ _, local_type = _sdk_types()+ model, backend = resolve_oss_sdk_config()+ return cls(+ local_type(+ storage_path=str(storage_path),+ index_model=model,+ summary_model=model,+ index_backend=backend,+ ))- @staticmethod- def _json(resp: httpx.Response) -> dict[str, Any]:- if resp.status_code >= 400:- raise PageIndexAPIError(f"PageIndex API {resp.status_code}: {resp.text[:300]}")- try:- data = resp.json()- except Exception as exc: # pragma: no cover - defensive- raise PageIndexAPIError(f"PageIndex returned non-JSON response: {exc}") from exc- if not isinstance(data, dict):- raise PageIndexAPIError(f"PageIndex returned unexpected payload: {data!r}")- return data-- # ----- document processing (indexing) ----------------------------------- async def submit_document(self, file_path: str | Path) -> str:- path = Path(file_path)- async with self._open() as client:- with open(path, "rb") as handle:- resp = await client.post(- "/doc/",- files={"file": (path.name, handle, "application/octet-stream")},- )- data = self._json(resp)- doc_id = data.get("doc_id") or data.get("id")+ @classmethod+ def local_read(cls, storage_path: str | Path) -> "PageIndexClient":+ """Open an existing Local Library without resolving indexing credentials."""+ _, local_type = _sdk_types()+ return cls(local_type(storage_path=str(storage_path)))++ async def submit_document(self, file_path: str | Path, *, mode: str | None = None) -> str:+ result = await asyncio.to_thread(+ self.sdk_client.submit_document,+ str(file_path),+ mode=mode,+ wait=True,+ )+ doc_id = result.get("doc_id") if isinstance(result, dict) else Noneif not doc_id:- raise PageIndexAPIError(f"submit_document returned no doc_id: {data!r}")+ raise RuntimeError(f"PageIndex submit_document returned no doc_id: {result!r}")return str(doc_id)- async def get_document(self, doc_id: str, *, summary: bool = False) -> dict[str, Any]:- """GET /doc/{id}/ — status plus the document tree in ``result``.-- ``summary=True`` asks the API to include per-node summaries.- """- params = {"summary": "true"} if summary else None- async with self._open() as client:- resp = await client.get(f"/doc/{doc_id}/", params=params)- return self._json(resp)-- async def wait_until_ready(- self,- doc_id: str,- *,- poll_interval: float = 3.0,- max_attempts: int = 200,- ) -> dict[str, Any]:- """Poll ``get_document`` until processing reaches a terminal state."""- for _ in range(max_attempts):- data = await self.get_document(doc_id)- status = str(data.get("status") or "").strip().lower()- ready = bool(data.get("retrieval_ready"))- if status in _TERMINAL_FAIL:- raise PageIndexAPIError(f"PageIndex processing failed for {doc_id}: {data!r}")- if ready or status in _TERMINAL_OK:- return data- await asyncio.sleep(poll_interval)- raise PageIndexAPIError(- f"PageIndex processing timed out for {doc_id} after {max_attempts} polls"- )-async def delete_document(self, doc_id: str) -> bool:- try:- async with self._open() as client:- resp = await client.delete(f"/doc/{doc_id}/")- return resp.status_code < 400- except Exception as exc: # pragma: no cover - best-effort- logger.warning("PageIndex delete_document(%s) failed: %s", doc_id, exc)- return False+ await asyncio.to_thread(self.sdk_client.delete_document, doc_id)+ return True-__all__ = ["PageIndexClient", "PageIndexAPIError"]+__all__ = [+ "PageIndexClient",+ "resolve_oss_sdk_config",+]diff --git a/deeptutor/services/rag/pipelines/pageindex/config.py b/deeptutor/services/rag/pipelines/pageindex/config.pyindex d4c6a0089..068804777 100644--- a/deeptutor/services/rag/pipelines/pageindex/config.py+++ b/deeptutor/services/rag/pipelines/pageindex/config.py@@ -1,45 +1,37 @@-"""Resolve the PageIndex credential from runtime settings.+"""Resolve PageIndex Cloud credentials and OSS readiness.-The key + base URL live in ``data/.../settings/pageindex.json`` (managed by+The Cloud key lives in ``data/.../settings/pageindex.json`` (managed by``RuntimeSettingsService``), surfaced to users under Knowledge → RAG pipeline-settings. A single account key is shared by every ``pageindex`` KB.+settings. A single deployment credential is shared by every ``pageindex`` KB;+the SDK owns the official Cloud endpoint."""from __future__ import annotationsfrom dataclasses import dataclass-DEFAULT_API_BASE_URL = "https://api.pageindex.ai"-@dataclass(frozen=True)class PageIndexConfig:api_key: str- api_base_url: str---class PageIndexNotConfiguredError(RuntimeError):- """Raised when no PageIndex API key has been configured."""def get_pageindex_config(*, require_key: bool = True) -> PageIndexConfig:"""Load the active PageIndex credential.- Raises :class:`PageIndexNotConfiguredError` when ``require_key`` and the key- is empty, so callers (indexing / retrieval) fail with a clear, actionable- message instead of an opaque 401 from the API.+ Raises when ``require_key`` and the key is empty, so callers fail with a+ clear, actionable message instead of an opaque 401 from the API."""from deeptutor.services.config import get_runtime_settings_servicesettings = get_runtime_settings_service().load_pageindex()api_key = str(settings.get("api_key") or "").strip()- base_url = str(settings.get("api_base_url") or DEFAULT_API_BASE_URL).strip().rstrip("/")if require_key and not api_key:- raise PageIndexNotConfiguredError(+ raise RuntimeError("PageIndex API key is not configured. Add it under ""Knowledge → RAG pipeline settings before using a PageIndex knowledge base.")- return PageIndexConfig(api_key=api_key, api_base_url=base_url or DEFAULT_API_BASE_URL)+ return PageIndexConfig(api_key=api_key)def is_pageindex_configured() -> bool:@@ -52,8 +44,6 @@ def is_pageindex_configured() -> bool:__all__ = ["PageIndexConfig",- "PageIndexNotConfiguredError","get_pageindex_config","is_pageindex_configured",- "DEFAULT_API_BASE_URL",]diff --git a/deeptutor/services/rag/pipelines/pageindex/pipeline.py b/deeptutor/services/rag/pipelines/pageindex/pipeline.pyindex 64026f2bb..b2c92e720 100644--- a/deeptutor/services/rag/pipelines/pageindex/pipeline.py+++ b/deeptutor/services/rag/pipelines/pageindex/pipeline.py@@ -1,17 +1,13 @@-"""PageIndex cloud-backed RAG pipeline orchestration.+"""PageIndex Cloud and OSS knowledge-base lifecycle orchestration.Implements the same contract as :class:`LlamaIndexPipeline` (see-``..base.RAGPipeline``) but delegates indexing to the hosted PageIndex-service (tree building, no embeddings). PageIndex's REST retrieval endpoint-is deprecated: deep retrieval is agentic — the chat agent reads documents-through the PageIndex MCP server — while ``search()`` serves programmatic-callers with each document's real tree outline (titles / pages / summaries)-fetched over REST.+``..base.RAGPipeline``) but delegates document lifecycle to the PageIndex SDK.+Answering is intentionally unavailable through ``search()``: PageIndex+knowledge bases are read inside an agent loop with their provider tools."""from __future__ import annotations-import asyncioimport loggingfrom pathlib import Pathimport traceback@@ -26,7 +22,7 @@ from deeptutor.services.rag.kb_paths import resolve_kb_dirfrom . import storagefrom .client import PageIndexClient-from .config import PageIndexNotConfiguredError, get_pageindex_config+from .config import get_pageindex_configlogger = logging.getLogger(__name__)@@ -48,14 +44,18 @@ SUPPORTED_EXTENSIONS = {".xls",".csv",}+OSS_SUPPORTED_EXTENSIONS = {".pdf"}-def is_supported_file(path: str | Path) -> bool:- return Path(path).suffix.lower() in SUPPORTED_EXTENSIONS+def is_supported_file(path: str | Path, provider: str = storage.CLOUD_PROVIDER) -> bool:+ extensions = (+ OSS_SUPPORTED_EXTENSIONS if provider == storage.OSS_PROVIDER else SUPPORTED_EXTENSIONS+ )+ return Path(path).suffix.lower() in extensionsclass PageIndexPipeline:- """Index/retrieve KB content via the hosted PageIndex service."""+ """Manage one PageIndex provider while preserving DeepTutor's RAG contract."""def __init__(self,@@ -63,16 +63,46 @@ class PageIndexPipeline:*,client: Optional[PageIndexClient] = None,config_provider=None,+ provider: str = storage.CLOUD_PROVIDER,) -> None:self.logger = logging.getLogger(__name__)self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIRself._client = clientself._config_provider = config_provider or get_pageindex_config+ self.provider = (+ storage.OSS_PROVIDER if provider == storage.OSS_PROVIDER else storage.CLOUD_PROVIDER+ )- def _get_client(self) -> PageIndexClient:+ def _get_client(self, storage_dir: Path | None = None) -> PageIndexClient:if self._client is not None:return self._client- return PageIndexClient(self._config_provider())+ if self.provider == storage.OSS_PROVIDER:+ if storage_dir is None:+ raise RuntimeError("PageIndex OSS requires a resolved Local Library path")+ return PageIndexClient.local(storage.sdk_storage_path(storage_dir))+ return PageIndexClient.cloud(self._config_provider())++ def _processing_mode(self, kb_name: str) -> str | None:+ if self.provider != storage.OSS_PROVIDER:+ return None+ try:+ from deeptutor.services.config.knowledge_base_config import KnowledgeBaseConfigService++ mode = (+ str(+ KnowledgeBaseConfigService.get_instance(+ Path(self.kb_base_dir) / "kb_config.json"+ )+ .get_kb_config(kb_name)+ .get("pageindex_mode")+ or ""+ )+ .strip()+ .lower()+ )+ except Exception:+ mode = ""+ return mode if mode in {"flash", "standard"} else None# ----- indexing -------------------------------------------------------@@ -84,14 +114,20 @@ class PageIndexPipeline:"Initializing KB '%s' with %d file(s) using PageIndex", kb_name, len(file_paths))try:- manifest = storage._empty_manifest()- count = await self._ingest(file_paths, manifest, progress_callback)+ manifest = storage._empty_manifest(self.provider)+ count = await self._ingest(+ file_paths,+ manifest,+ progress_callback,+ storage_dir=storage_dir,+ mode=self._processing_mode(kb_name),+ )if count == 0:self.logger.error("PageIndex: no supported documents to index for '%s'", kb_name)self._cleanup_failed_version_dir(storage_dir)return Falsestorage.write_manifest(storage_dir, manifest)- storage.write_meta(storage_dir)+ storage.write_meta(storage_dir, provider=self.provider)self.logger.info("KB '%s' initialized with PageIndex (%d docs)", kb_name, count)return Trueexcept Exception as exc:@@ -106,20 +142,26 @@ class PageIndexPipeline:existing = resolve_storage_dir_for_read(kb_dir, None)if existing is not None:storage_dir = existing- manifest = storage.read_manifest(existing)+ manifest = storage.read_manifest(existing, provider=self.provider)else:storage_dir = resolve_storage_dir_for_rebuild(kb_dir, None)- manifest = storage._empty_manifest()+ manifest = storage._empty_manifest(self.provider)self.logger.info("Adding %d document(s) to PageIndex KB '%s'", len(file_paths), kb_name)try:- count = await self._ingest(file_paths, manifest, progress_callback)+ count = await self._ingest(+ file_paths,+ manifest,+ progress_callback,+ storage_dir=storage_dir,+ mode=self._processing_mode(kb_name),+ )if count == 0:self.logger.warning("PageIndex: no supported documents to add for '%s'", kb_name)return Falsestorage_dir.mkdir(parents=True, exist_ok=True)storage.write_manifest(storage_dir, manifest)- storage.write_meta(storage_dir)+ storage.write_meta(storage_dir, provider=self.provider)self.logger.info("Added %d doc(s) to PageIndex KB '%s'", count, kb_name)return Trueexcept Exception as exc:@@ -132,21 +174,23 @@ class PageIndexPipeline:file_paths: List[str],manifest: dict[str, Any],progress_callback,+ *,+ storage_dir: Path,+ mode: str | None,) -> int:- supported = [fp for fp in file_paths if is_supported_file(fp)]- skipped = [fp for fp in file_paths if not is_supported_file(fp)]+ supported = [fp for fp in file_paths if is_supported_file(fp, self.provider)]+ skipped = [fp for fp in file_paths if not is_supported_file(fp, self.provider)]for fp in skipped:self.logger.warning("PageIndex skips unsupported file type: %s", Path(fp).name)if not supported:return 0- client = self._get_client()+ client = self._get_client(storage_dir)total = len(supported)for idx, fp in enumerate(supported, 1):path = Path(fp)self.logger.info("PageIndex: submitting %s (%d/%d)", path.name, idx, total)- doc_id = await client.submit_document(path)- await client.wait_until_ready(doc_id)+ doc_id = await client.submit_document(path, mode=mode)size = path.stat().st_size if path.exists() else Nonestorage.upsert_doc(manifest, path.name, doc_id, size=size)if progress_callback:@@ -155,132 +199,30 @@ class PageIndexPipeline:# ----- retrieval ------------------------------------------------------- # ponytail: flat per-doc cap on the formatted outline; per-consumer- # budgets if a real need shows up.- TREE_CHARS_PER_DOC = 6000-async def search(self, query: str, kb_name: str, **_kwargs) -> Dict[str, Any]:- """Return each document's tree outline (titles / pages / summaries).-- The deprecated REST retrieval endpoint is gone; deep, query-driven- retrieval is agentic via the PageIndex MCP tools in chat. For- programmatic callers this returns the documents' real structure as- context — shallow but honest grounding.- """- docs = self.document_map(kb_name)-- if not docs:- return {- "query": query,- "answer": (- "This PageIndex knowledge base has no indexed documents yet. "- "Add documents before querying."- ),- "content": "",- "sources": [],- "provider": storage.PROVIDER,- "needs_reindex": True,- }-- try:- client = self._get_client()- results = await asyncio.gather(- *(client.get_document(doc_id, summary=True) for doc_id in docs.values()),- return_exceptions=True,- )- except PageIndexNotConfiguredError as exc:- return {- "query": query,- "answer": str(exc),- "content": "",- "sources": [],- "provider": storage.PROVIDER,- "error_type": "not_configured",- }-- parts: list[str] = []- sources: list[dict[str, Any]] = []- errors: list[str] = []- for (file_name, doc_id), result in zip(docs.items(), results):- if isinstance(result, BaseException):- errors.append(str(result))- self.logger.warning("PageIndex tree fetch failed for %s: %s", doc_id, result)- continue- outline, doc_sources = self._format_tree(file_name, doc_id, result.get("result"))- if outline:- parts.append(f"## {file_name}\n{outline}")- sources.extend(doc_sources)-- if not parts and errors:- return {- "query": query,- "answer": "; ".join(errors[:3]),- "content": "",- "sources": [],- "provider": storage.PROVIDER,- "error_type": "retrieval_error",- }-- content = "\n\n".join(parts)+ """Fail closed: PageIndex answering must happen inside an agent loop."""+ message = (+ "PageIndex uses Reasoning as Retrieval. Read this knowledge base with "+ "its PageIndex tools inside an agent loop instead of calling rag search."+ )return {"query": query,- "answer": content,- "content": content,- "sources": sources,- "provider": storage.PROVIDER,+ "answer": message,+ "content": "",+ "sources": [],+ "provider": self.provider,+ "error_type": "reasoning_as_retrieval_required",}- @classmethod- def _format_tree(- cls, file_name: str, doc_id: str, tree: Any- ) -> tuple[str, list[dict[str, Any]]]:- """Render a PageIndex tree as an indented outline + per-section sources."""- lines: list[str] = []- sources: list[dict[str, Any]] = []-- def walk(node: Any, depth: int) -> None:- if isinstance(node, list):- for item in node:- walk(item, depth)- return- if not isinstance(node, dict):- return- title = str(node.get("title") or "").strip()- page = node.get("page_index")- summary = str(node.get("summary") or node.get("prefix_summary") or "").strip()- if title:- line = f"{' ' * depth}- {title}"- if page not in (None, ""):- line += f" (p.{page})"- if summary:- line += f": {summary}"- lines.append(line)- if depth == 0:- sources.append(- {- "title": title,- "content": summary[:200],- "source": file_name,- "page": page if page is not None else "",- "chunk_id": node.get("node_id") or doc_id,- "score": "",- }- )- walk(node.get("nodes") or [], depth + 1)-- walk(tree, 0)- text = "\n".join(lines)- if len(text) > cls.TREE_CHARS_PER_DOC:- text = text[: cls.TREE_CHARS_PER_DOC] + "\n… (outline truncated)"- return text, sources-def document_map(self, kb_name: str) -> dict[str, str]:"""file name -> cloud doc_id for the KB's current manifest.Used by the chat layer to inject the doc list into the system prompt."""kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- manifest = storage.read_manifest(resolve_storage_dir_for_read(kb_dir, None))+ manifest = storage.read_manifest(+ resolve_storage_dir_for_read(kb_dir, None), provider=self.provider+ )return {name: str(entry["doc_id"])for name, entry in storage.doc_entries(manifest).items()@@ -293,18 +235,17 @@ class PageIndexPipeline:import shutilkb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- # Best-effort: drop hosted documents so they don't linger on the account.- try:- storage_dir = resolve_storage_dir_for_read(kb_dir, None)- ids = storage.doc_ids(storage.read_manifest(storage_dir))- if ids:- client = self._get_client()- await asyncio.gather(- *(client.delete_document(doc_id) for doc_id in ids),- return_exceptions=True,- )- except Exception as exc: # pragma: no cover - best-effort- self.logger.warning("PageIndex cloud cleanup skipped for '%s': %s", kb_name, exc)+ # Preserve the existing Cloud behavior. OSS data is already inside kb_dir.+ if self.provider == storage.CLOUD_PROVIDER:+ try:+ storage_dir = resolve_storage_dir_for_read(kb_dir, None)+ ids = storage.doc_ids(storage.read_manifest(storage_dir, provider=self.provider))+ if ids:+ client = self._get_client(storage_dir)+ for doc_id in ids:+ await client.delete_document(doc_id)+ except Exception as exc: # pragma: no cover - best-effort+ self.logger.warning("PageIndex cloud cleanup skipped for '%s': %s", kb_name, exc)if kb_dir.exists():shutil.rmtree(kb_dir)@@ -312,11 +253,42 @@ class PageIndexPipeline:return Truereturn False+ async def remove_document(self, kb_name: str, file_name: str) -> bool:+ """Delete one indexed document and update the active manifest."""+ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ storage_dir = resolve_storage_dir_for_read(kb_dir, None)+ if storage_dir is None:+ return False+ manifest = storage.read_manifest(storage_dir, provider=self.provider)+ docs = storage.doc_entries(manifest)+ key = file_name if file_name in docs else Path(file_name).name+ entry = docs.get(key)+ if not isinstance(entry, dict) or not entry.get("doc_id"):+ return False+ client = (+ PageIndexClient.local_read(storage.sdk_storage_path(storage_dir))+ if self.provider == storage.OSS_PROVIDER and self._client is None+ else self._get_client(storage_dir)+ )+ await client.delete_document(str(entry["doc_id"]))+ storage.remove_doc(manifest, key)+ storage.write_manifest(storage_dir, manifest)+ storage.write_meta(storage_dir, provider=self.provider)+ return True++ def sdk_client_for_read(self, kb_name: str) -> Any:+ """Return the SDK client bound to this KB's active Local Library."""+ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ storage_dir = resolve_storage_dir_for_read(kb_dir, None)+ if storage_dir is None:+ raise RuntimeError(f"PageIndex knowledge base '{kb_name}' has no ready index")+ if self.provider == storage.OSS_PROVIDER and self._client is None:+ return PageIndexClient.local_read(storage.sdk_storage_path(storage_dir)).sdk_client+ return self._get_client(storage_dir).sdk_client+def _cleanup_failed_version_dir(self, storage_dir: Path) -> None:try:- if storage_dir.is_dir() and not any(- child.name != storage.META_FILENAME for child in storage_dir.iterdir()- ):+ if storage_dir.is_dir() and not (storage_dir / storage.META_FILENAME).exists():import shutilshutil.rmtree(storage_dir)@@ -324,4 +296,9 @@ class PageIndexPipeline:self.logger.warning("Could not clean up failed version dir %s: %s", storage_dir, exc)-__all__ = ["PageIndexPipeline", "is_supported_file", "SUPPORTED_EXTENSIONS"]+__all__ = [+ "OSS_SUPPORTED_EXTENSIONS",+ "PageIndexPipeline",+ "SUPPORTED_EXTENSIONS",+ "is_supported_file",+]diff --git a/deeptutor/services/rag/pipelines/pageindex/reasoning.py b/deeptutor/services/rag/pipelines/pageindex/reasoning.pynew file mode 100644index 000000000..57dbc1f81--- /dev/null+++ b/deeptutor/services/rag/pipelines/pageindex/reasoning.py@@ -0,0 +1,261 @@+"""A small DeepTutor agent loop for workflow-owned PageIndex reading."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from deeptutor.core.agentic import (+ DispatchOutcome,+ LabelProtocol,+ LLMClientConfig,+ UsageTracker,+ build_completion_kwargs,+ build_openai_client,+ can_use_native_tool_calling,+ dispatch_tool_calls,+ run_agentic_loop,+)+from deeptutor.core.agentic.labeled_step import run_labeled_step+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.llm import get_llm_config++from .tools import PageIndexToolContext, build_pageindex_tool_context++_PROTOCOL = LabelProtocol(+ allowed=("THINK", "TOOL", "FINISH"),+ terminal=frozenset({"FINISH"}),+ intermediate=frozenset({"THINK"}),+ final=frozenset({"FINISH"}),+ tool_label="TOOL",+)+++@dataclass(frozen=True)+class PageIndexReadingResult:+ text: str+ sources: list[dict[str, Any]]+ tool_context: PageIndexToolContext+++class _ReadingHost:+ def __init__(+ self,+ *,+ tool_context: PageIndexToolContext,+ context: UnifiedContext,+ stream: StreamBus,+ client: Any,+ model: str | None,+ binding: str,+ reasoning_effort: str | None,+ source: str,+ stage: str,+ ) -> None:+ self.tool_context = tool_context+ self.context = context+ self.stream = stream+ self.client = client+ self.model = model+ self.binding = binding+ self.reasoning_effort = reasoning_effort+ self.source = source+ self.stage = stage++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ return++ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:+ call_id = new_call_id(f"{self.source}-pageindex-{iteration}")+ meta = build_trace_metadata(+ call_id=call_id,+ phase=self.stage,+ label="PageIndex reading",+ call_kind="llm_reasoning",+ trace_id=call_id,+ trace_role="thought",+ trace_group="stage",+ )+ return meta, meta++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ return await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=self.context,+ stream=self.stream,+ source=self.source,+ stage=self.stage,+ iteration_index=iteration,+ registry=self.tool_context.registry,+ tool_call_label="PageIndex tool",+ retrieve_label="Read document",+ empty_tool_result_message="PageIndex returned no content.",+ start_retrieval_message="Reading PageIndex documents",+ too_many_tool_calls_message="Too many tool calls in one round.",+ unknown_error_message_factory=lambda name: f"Error executing {name}.",+ trace_id_prefix=f"{self.source}-pageindex",+ )++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ return False++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ return++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ return++ def protocol_retry_notice(self) -> str:+ return "The PageIndex reading loop used an invalid action label; retrying."++ def protocol_repair_message(self, violation: str) -> str:+ return (+ f"Protocol violation: {violation}. Start with exactly THINK, TOOL, or FINISH. "+ "Use TOOL only with tool calls; FINISH must contain the requested result."+ )++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ messages.append(+ {+ "role": "user",+ "content": "Tool budget exhausted. Return FINISH followed by the best grounded result now.",+ }+ )+ step = await run_labeled_step(+ client=self.client,+ model=self.model,+ messages=messages,+ completion_kwargs=build_completion_kwargs(+ temperature=0.2,+ model=self.model,+ max_tokens=5000,+ binding=self.binding,+ reasoning_effort=self.reasoning_effort,+ ),+ tool_schemas=None,+ allowed_labels=("FINISH",),+ final_labels=frozenset({"FINISH"}),+ tool_label=None,+ stream=self.stream,+ source=self.source,+ stage=self.stage,+ iter_meta=self.build_iteration_trace_meta(start_iteration)[0],+ binding=self.binding,+ )+ return step.text, step.label == "FINISH", 1+++async def read_pageindex_with_agent(+ *,+ kb_name: str,+ system_prompt: str,+ user_prompt: str,+ context: UnifiedContext | None = None,+ stream: StreamBus | None = None,+ source: str,+ stage: str,+ max_iterations: int = 8,+) -> PageIndexReadingResult:+ """Run the caller's reasoning stage with the selected PageIndex tools."""+ llm = get_llm_config()+ binding = str(getattr(llm, "binding", None) or "openai")+ model = getattr(llm, "model", None)+ if not can_use_native_tool_calling(binding=binding, model=model):+ raise RuntimeError("The active LLM must support tool calling to read a PageIndex KB.")++ tool_context = await build_pageindex_tool_context(+ kb_name,+ base_registry=get_tool_registry(),+ )+ if tool_context is None:+ raise ValueError(f"Knowledge base '{kb_name}' is not a PageIndex knowledge base")++ bus = stream or StreamBus(max_history=0)+ turn_context = context or UnifiedContext(user_message=user_prompt, knowledge_bases=[kb_name])+ client = build_openai_client(+ LLMClientConfig(+ binding=binding,+ model=model,+ api_key=getattr(llm, "api_key", None),+ base_url=getattr(llm, "base_url", None),+ api_version=getattr(llm, "api_version", None),+ extra_headers=getattr(llm, "extra_headers", None) or None,+ reasoning_effort=getattr(llm, "reasoning_effort", None),+ )+ )+ docs = (+ "; ".join(+ f"{name} (doc_id: {doc_id})" for name, doc_id in sorted(tool_context.documents.items())+ )+ or "(no indexed documents)"+ )+ tool_names = ", ".join(tool.name for tool in tool_context.tools)+ managed = (+ "You are reading a PageIndex knowledge base inside the caller's existing workflow.\n"+ "Use Reasoning as Retrieval: inspect document structure and then read only relevant pages.\n"+ "Never call a generic RAG search and never answer document claims from general knowledge.\n"+ "Each response must start with exactly one label on its own first line: THINK, TOOL, or "+ "FINISH. TOOL must include native tool calls. FINISH must contain the caller's requested "+ "grounded result.\n"+ f"Available tools: {tool_names}\nDocuments: {docs}\n"+ f"{tool_context.instructions}\n\n{system_prompt}"+ )+ host = _ReadingHost(+ tool_context=tool_context,+ context=turn_context,+ stream=bus,+ client=client,+ model=model,+ binding=binding,+ reasoning_effort=getattr(llm, "reasoning_effort", None),+ source=source,+ stage=stage,+ )+ outcome = await run_agentic_loop(+ initial_messages=[+ {"role": "system", "content": managed},+ {"role": "user", "content": user_prompt},+ ],+ protocol=_PROTOCOL,+ client=client,+ model=model,+ completion_kwargs=build_completion_kwargs(+ temperature=0.2,+ model=model,+ max_tokens=5000,+ binding=binding,+ reasoning_effort=getattr(llm, "reasoning_effort", None),+ ),+ binding=binding,+ tool_schemas=[tool.get_definition().to_openai_schema() for tool in tool_context.tools],+ stream=bus,+ source=source,+ stage=stage,+ max_iterations=max_iterations,+ host=host,+ usage=UsageTracker(model=model),+ eager_sub_trace=True,+ )+ if outcome.sources:+ await bus.sources(outcome.sources, source=source, stage=stage)+ return PageIndexReadingResult(+ text=(outcome.final_text or "").strip(),+ sources=list(outcome.sources),+ tool_context=tool_context,+ )+++__all__ = ["PageIndexReadingResult", "read_pageindex_with_agent"]diff --git a/deeptutor/services/rag/pipelines/pageindex/storage.py b/deeptutor/services/rag/pipelines/pageindex/storage.pyindex 2eeb83566..70377f57d 100644--- a/deeptutor/services/rag/pipelines/pageindex/storage.py+++ b/deeptutor/services/rag/pipelines/pageindex/storage.py@@ -22,31 +22,37 @@ logger = logging.getLogger(__name__)MANIFEST_FILENAME = "pageindex_docs.json"META_FILENAME = "meta.json"-PROVIDER = "pageindex"+SDK_STORAGE_DIRNAME = "pageindex"+CLOUD_PROVIDER = "pageindex"+OSS_PROVIDER = "pageindex-oss"-def _empty_manifest() -> dict[str, Any]:- return {"provider": PROVIDER, "docs": {}}+def _empty_manifest(provider: str = CLOUD_PROVIDER) -> dict[str, Any]:+ return {"provider": provider, "docs": {}}def manifest_path(storage_dir: Path) -> Path:return Path(storage_dir) / MANIFEST_FILENAME-def read_manifest(storage_dir: Path | None) -> dict[str, Any]:+def read_manifest(+ storage_dir: Path | None,+ *,+ provider: str = CLOUD_PROVIDER,+) -> dict[str, Any]:if storage_dir is None:- return _empty_manifest()+ return _empty_manifest(provider)path = manifest_path(storage_dir)if not path.exists():- return _empty_manifest()+ return _empty_manifest(provider)try:data = json.loads(path.read_text(encoding="utf-8"))except Exception as exc:logger.warning("Failed to read PageIndex manifest %s: %s", path, exc)- return _empty_manifest()+ return _empty_manifest(provider)if not isinstance(data, dict):- return _empty_manifest()- data.setdefault("provider", PROVIDER)+ return _empty_manifest(provider)+ data.setdefault("provider", provider)if not isinstance(data.get("docs"), dict):data["docs"] = {}return data@@ -56,7 +62,7 @@ def write_manifest(storage_dir: Path, manifest: dict[str, Any]) -> None:atomic_write_json(manifest_path(storage_dir), manifest)-def write_meta(storage_dir: Path) -> None:+def write_meta(storage_dir: Path, *, provider: str = CLOUD_PROVIDER) -> None:"""Write a flat-layout ``meta.json`` so the version is listed as ready.Mirrors ``index_versioning.write_version_meta`` but carries a synthetic@@ -65,8 +71,8 @@ def write_meta(storage_dir: Path) -> None:target = Path(storage_dir)payload = {"version": target.name,- "signature": PROVIDER,- "provider": PROVIDER,+ "signature": provider,+ "provider": provider,"layout": "flat","created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",}@@ -101,9 +107,20 @@ def upsert_doc(}+def remove_doc(manifest: dict[str, Any], file_name: str) -> dict[str, Any] | None:+ entry = doc_entries(manifest).pop(file_name, None)+ return entry if isinstance(entry, dict) else None+++def sdk_storage_path(storage_dir: Path) -> Path:+ return Path(storage_dir) / SDK_STORAGE_DIRNAME++__all__ = ["MANIFEST_FILENAME",- "PROVIDER",+ "CLOUD_PROVIDER",+ "OSS_PROVIDER",+ "SDK_STORAGE_DIRNAME","manifest_path","read_manifest","write_manifest",@@ -111,4 +128,6 @@ __all__ = ["doc_entries","doc_ids","upsert_doc",+ "remove_doc",+ "sdk_storage_path",]diff --git a/deeptutor/services/rag/pipelines/pageindex/tools.py b/deeptutor/services/rag/pipelines/pageindex/tools.pynew file mode 100644index 000000000..4b676db18--- /dev/null+++ b/deeptutor/services/rag/pipelines/pageindex/tools.py@@ -0,0 +1,221 @@+"""Turn-scoped DeepTutor wrappers for PageIndex Cloud and OSS SDK tools."""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from functools import lru_cache+import json+from typing import Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolLookup, ToolResult+from deeptutor.runtime.registry.scoped_registry import ScopedToolRegistry++from .pipeline import PageIndexPipeline+from .storage import CLOUD_PROVIDER, OSS_PROVIDER++TOOL_PREFIXES = {+ CLOUD_PROVIDER: "pageindex_cloud_",+ OSS_PROVIDER: "pageindex_oss_",+}+++def pageindex_sources_from_text(+ text: str,+ *,+ provider: str,+ kb_name: str = "",+ doc_ids: dict[str, str] | None = None,+) -> list[dict[str, Any]]:+ """Normalize real PageIndex page reads into DeepTutor source rows."""+ try:+ payload = json.loads(text)+ except (TypeError, ValueError):+ return []+ if not isinstance(payload, dict) or payload.get("success") is False or payload.get("errorCode"):+ return []+ document_name = str(payload.get("doc_name") or "").strip()+ content = payload.get("content")+ if not document_name or not isinstance(content, list):+ return []++ rows: list[dict[str, Any]] = []+ seen: set[tuple[str, str]] = set()+ for item in content:+ if not isinstance(item, dict) or item.get("page") in (None, ""):+ continue+ page = item["page"]+ block_id = str(item.get("block_id") or "").strip()+ key = (str(page), block_id)+ if key in seen:+ continue+ seen.add(key)+ row: dict[str, Any] = {+ "type": "pageindex",+ "provider": provider,+ "document_name": document_name,+ "source": document_name,+ "page": page,+ }+ if kb_name:+ row["kb_name"] = kb_name+ if doc_ids and document_name in doc_ids:+ row["doc_id"] = doc_ids[document_name]+ if block_id:+ row["block_id"] = block_id+ rows.append(row)+ return rows+++class PageIndexSDKTool(BaseTool):+ deferred = True+ provider_kind = "pageindex"++ def __init__(+ self,+ sdk_tool: Any,+ *,+ provider: str,+ kb_name: str,+ doc_ids: dict[str, str],+ ) -> None:+ self._sdk_tool = sdk_tool+ self.provider_id = provider+ self._kb_name = kb_name+ self._doc_ids = doc_ids++ def get_definition(self) -> ToolDefinition:+ label = "Cloud" if self.provider_id == CLOUD_PROVIDER else "OSS"+ return ToolDefinition(+ name=f"{TOOL_PREFIXES[self.provider_id]}{self._sdk_tool.name}",+ description=f"[PageIndex {label}: {self._kb_name}] {self._sdk_tool.description}",+ raw_parameters=dict(self._sdk_tool.params_json_schema),+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ kwargs.pop("event_sink", None)+ text = await self._sdk_tool.on_invoke_tool(+ None,+ json.dumps(kwargs, ensure_ascii=False),+ )+ try:+ payload = json.loads(text)+ except (TypeError, ValueError):+ payload = {}+ success = not (+ isinstance(payload, dict)+ and (payload.get("success") is False or payload.get("errorCode"))+ )+ sources = pageindex_sources_from_text(+ str(text),+ provider=self.provider_id,+ kb_name=self._kb_name,+ doc_ids=self._doc_ids,+ )+ return ToolResult(+ content=str(text),+ sources=sources,+ metadata={+ "pageindex_provider": self.provider_id,+ "kb_name": self._kb_name,+ "sources": sources,+ },+ success=success,+ )+++@dataclass(frozen=True)+class PageIndexSDKToolBundle:+ provider: str+ tools: tuple[PageIndexSDKTool, ...]+ instructions: str+ documents: dict[str, str]+++@dataclass(frozen=True)+class PageIndexToolContext:+ provider: str+ registry: ToolLookup+ tools: tuple[BaseTool, ...]+ instructions: str+ documents: dict[str, str]+++@lru_cache(maxsize=1)+def _cloud_read_tools(client: Any) -> tuple[Any, ...]:+ """Cache live Cloud schemas on the SDK client that owns their MCP session."""+ return tuple(client.as_openai_tools(include_management=False))+++async def build_sdk_tool_bundle(+ kb_name: str,+ kb_base_dir: str,+ *,+ provider: str,+) -> PageIndexSDKToolBundle:+ """Build one KB's read-only SDK tools without exposing their transport."""++ def build() -> PageIndexSDKToolBundle:+ pipeline = PageIndexPipeline(kb_base_dir=kb_base_dir, provider=provider)+ documents = pipeline.document_map(kb_name)+ client = pipeline.sdk_client_for_read(kb_name)+ sdk_tools = (+ client.as_openai_tools(include_management=False)+ if provider == OSS_PROVIDER+ else _cloud_read_tools(client)+ )+ instructions = client.agent_instructions()+ return PageIndexSDKToolBundle(+ provider=provider,+ tools=tuple(+ PageIndexSDKTool(+ tool,+ provider=provider,+ kb_name=kb_name,+ doc_ids=documents,+ )+ for tool in sdk_tools+ ),+ instructions=str(instructions or ""),+ documents=documents,+ )++ return await asyncio.to_thread(build)+++async def build_pageindex_tool_context(+ kb_name: str | None,+ *,+ base_registry: ToolLookup,+) -> PageIndexToolContext | None:+ """Resolve one PageIndex KB into tools for an existing workflow loop."""+ if not kb_name:+ return None+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ resource = resolve_kb(kb_name, require_write=False)+ base_dir = str(resource.base_dir)+ provider = resolve_bound_provider(base_dir, resource.name)+ if provider in {CLOUD_PROVIDER, OSS_PROVIDER}:+ bundle = await build_sdk_tool_bundle(resource.name, base_dir, provider=provider)+ registry = ScopedToolRegistry(base=base_registry, overlay=bundle.tools)+ return PageIndexToolContext(+ provider=provider,+ registry=registry,+ tools=bundle.tools,+ instructions=bundle.instructions,+ documents=bundle.documents,+ )+ return None+++__all__ = [+ "PageIndexSDKTool",+ "PageIndexSDKToolBundle",+ "PageIndexToolContext",+ "TOOL_PREFIXES",+ "build_sdk_tool_bundle",+ "build_pageindex_tool_context",+ "pageindex_sources_from_text",+]diff --git a/deeptutor/services/rag/preflight.py b/deeptutor/services/rag/preflight.pyindex 1c3ecc8ad..4d1c87419 100644--- a/deeptutor/services/rag/preflight.py+++ b/deeptutor/services/rag/preflight.py@@ -17,6 +17,7 @@ from .factory import (GRAPHRAG_PROVIDER,IMA_PROVIDER,LIGHTRAG_PROVIDER,+ PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,normalize_provider_name,)@@ -78,25 +79,40 @@ def _llamaindex_preflight() -> dict:def _pageindex_preflight() -> dict:try:- from .pipelines.pageindex.config import DEFAULT_API_BASE_URL, get_pageindex_config+ from .pipelines.pageindex.config import get_pageindex_configcfg = get_pageindex_config(require_key=False)configured = bool(cfg.api_key)- base = cfg.api_base_url or DEFAULT_API_BASE_URLexcept Exception:- configured, base = False, ""+ configured = Falsereturn _finalize([_check("api_key","API key configured",configured,- base if configured else "Add a PageIndex API key under Credentials.",+ "PageIndex Cloud" if configured else "Add a PageIndex API key under Credentials.",)])+def _pageindex_oss_preflight() -> dict:+ try:+ from .pipelines.pageindex.client import resolve_oss_sdk_config++ model, _backend = resolve_oss_sdk_config()+ llm_ok, detail = bool(model), model+ except Exception as exc:+ llm_ok = False+ detail = str(exc)+ return _finalize(+ [+ _check("chat", "Active LLM for indexing", llm_ok, detail),+ ]+ )++def _graphrag_preflight() -> dict:try:from .pipelines.graphrag.config import is_graphrag_available@@ -212,6 +228,7 @@ def _finalize(checks: list[dict]) -> dict:_PREFLIGHTS = {DEFAULT_PROVIDER: _llamaindex_preflight,PAGEINDEX_PROVIDER: _pageindex_preflight,+ PAGEINDEX_OSS_PROVIDER: _pageindex_oss_preflight,GRAPHRAG_PROVIDER: _graphrag_preflight,LIGHTRAG_PROVIDER: _lightrag_preflight,IMA_PROVIDER: _ima_preflight,diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.pyindex 2f5602089..97f01a6f7 100644--- a/deeptutor/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -89,6 +89,21 @@ class RAGService:**kwargs,) -> Dict[str, Any]:provider = self._resolve_provider(kb_name)+ from .factory import PAGEINDEX_OSS_PROVIDER, PAGEINDEX_PROVIDER++ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ message = (+ "PageIndex uses Reasoning as Retrieval. Read this knowledge base with "+ "its PageIndex tools inside an agent loop instead of RAGService.search()."+ )+ return {+ "query": query,+ "answer": message,+ "content": "",+ "sources": [],+ "provider": provider,+ "error_type": "reasoning_as_retrieval_required",+ }with self._capture_raw_logs(event_sink):await self._emit_tool_event(event_sink,diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.pyindex bf90fc001..4d1c680ed 100644--- a/deeptutor_cli/kb.py+++ b/deeptutor_cli/kb.py@@ -264,14 +264,43 @@ def register(app: typer.Typer) -> None:raise typer.Exit(code=1)try:- result = asyncio.run(- rag_search(- query=query,- kb_name=name,- mode=mode,- kb_base_dir=str(mgr.base_dir),+ from deeptutor.services.rag.factory import PAGEINDEX_OSS_PROVIDER, PAGEINDEX_PROVIDER+ from deeptutor.services.rag.provider_binding import resolve_bound_provider++ provider = resolve_bound_provider(str(mgr.base_dir), name)+ if provider in {PAGEINDEX_PROVIDER, PAGEINDEX_OSS_PROVIDER}:+ from deeptutor.services.rag.pipelines.pageindex.reasoning import (+ read_pageindex_with_agent,+ )++ reading = asyncio.run(+ read_pageindex_with_agent(+ kb_name=name,+ system_prompt=(+ "Answer the CLI user's question from the selected PageIndex "+ "knowledge base. Include page references from tool results."+ ),+ user_prompt=query,+ source="cli_kb_search",+ stage="search",+ )+ )+ result = {+ "query": query,+ "answer": reading.text,+ "content": reading.text,+ "sources": reading.sources,+ "provider": reading.tool_context.provider,+ }+ else:+ result = asyncio.run(+ rag_search(+ query=query,+ kb_name=name,+ mode=mode,+ kb_base_dir=str(mgr.base_dir),+ ))- )except Exception as exc:console.print(f"[red]Search failed: {exc}[/]")raise typer.Exit(code=1) from excdiff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.tomlindex a82dd6215..f9323d356 100644--- a/packaging/deeptutor-cli/pyproject.toml+++ b/packaging/deeptutor-cli/pyproject.toml@@ -29,10 +29,10 @@ dependencies = ["typer>=0.9.0","rich>=13.0.0","prompt_toolkit>=3.0.36",- # MCP client. This distribution ships `deeptutor.services.mcp`, including the- # built-in PageIndex MCP server that is injected whenever a PageIndex API key- # is configured, so it needs the client too (issue #792).+ # MCP client. This distribution ships the configurable MCP tool surface, so+ # it needs the client without an optional extra (issue #792)."mcp>=1.26.0,<2.0.0",+ "pageindex>=0.2.10,<0.3.0","anthropic>=0.30.0","dashscope>=1.14.0","perplexityai>=0.1.0",diff --git a/pyproject.toml b/pyproject.tomlindex a99699742..fe5a1a097 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,12 +38,10 @@ dependencies = ["prompt_toolkit>=3.0.36","pyte>=0.8.1", # in-memory terminal emulator: scrape Claude Code's /model TUI on sync# MCP client. Core rather than a `partners`-only extra (issue #792): the- # connection manager and the built-in PageIndex MCP server are injected on- # any turn where a PageIndex API key is configured, so a plain- # `pip install deeptutor` has to be able to import `mcp` — otherwise the- # connection task dies with ModuleNotFoundError and every turn stalls for- # the full connect timeout.+ # default chat/tool surface includes configurable MCP servers, so a plain+ # install must be able to connect them without an optional extra."mcp>=1.26.0,<2.0.0",+ "pageindex>=0.2.10,<0.3.0",# Full app dependencies included by default for `pip install deeptutor`."anthropic>=0.30.0","dashscope>=1.14.0",@@ -94,6 +92,7 @@ cli = ["dashscope>=1.14.0","perplexityai>=0.1.0","oauth-cli-kit>=0.1.1",+ "pageindex>=0.2.10,<0.3.0",# RAG (LlamaIndex)"llama-index>=0.14.12","llama-index-retrievers-bm25>=0.7.1,<0.8.0",diff --git a/requirements/cli.txt b/requirements/cli.txtindex 5688b6058..f733f3463 100644--- a/requirements/cli.txt+++ b/requirements/cli.txt@@ -64,7 +64,6 @@ typer>=0.9.0rich>=13.0.0prompt_toolkit>=3.0.36-# --- MCP client (deferred tools; built-in PageIndex MCP server) ----# Core, not partners-only: the connection manager injects the built-in-# pageindex server whenever a PageIndex API key is configured (issue #792).+# --- MCP client (configurable deferred tools; core, not partners-only) ---mcp>=1.26.0,<2.0.0+pageindex>=0.2.10,<0.3.0diff --git a/tests/agents/chat/test_kb_manifest_note.py b/tests/agents/chat/test_kb_manifest_note.pyindex 32aa9c6d5..b14c70acf 100644--- a/tests/agents/chat/test_kb_manifest_note.py+++ b/tests/agents/chat/test_kb_manifest_note.py@@ -110,9 +110,12 @@ async def test_every_attached_kb_is_described(monkeypatch: pytest.MonkeyPatch) -@pytest.mark.asyncioasync def test_pageindex_kbs_are_not_described_twice(monkeypatch: pytest.MonkeyPatch) -> None:- """PageIndex's own note already lists its documents, with their doc_ids."""+ """PageIndex discovery belongs to its tools, not the generic inventory."""pipeline = _pipeline(monkeypatch)- pipeline._pageindex_docs = {"hosted": {"paper.pdf": "doc-1"}}+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.pageindex.is_pageindex_kb",+ lambda name: name == "hosted",+ )asked = _stub_resolver(monkeypatch, {"course": _manifest("course", "a.pdf")})context = UnifiedContext(session_id="s1", user_message="how many?", knowledge_bases=["course", "hosted"]diff --git a/tests/agents/chat/test_pageindex_mcp.py b/tests/agents/chat/test_pageindex_mcp.pydeleted file mode 100644index 7b792e9f6..000000000--- a/tests/agents/chat/test_pageindex_mcp.py+++ /dev/null@@ -1,103 +0,0 @@-"""Chat-side PageIndex MCP wiring.--Attaching a PageIndex KB grants the turn the built-in pageindex MCP server's-tools (narrowed implicit grant), preloads them (no load_tools round-trip),-and injects the KB's document list into the system prompt.-"""--from __future__ import annotations--import asyncio--from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline-from deeptutor.core.context import UnifiedContext-from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolResult---class FakeMCPTool(BaseTool):- deferred = True-- def __init__(self, server: str, name: str) -> None:- self.server_name = server- self._name = f"mcp_{server}_{name}"-- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name=self._name,- description="fake",- raw_parameters={"type": "object", "properties": {}},- )-- async def execute(self, **kwargs) -> ToolResult: # pragma: no cover - unused- return ToolResult(content="")---class FakeRegistry:- def __init__(self, tools: list[BaseTool]) -> None:- self._tools = {t.get_definition().name: t for t in tools}-- def deferred_tools(self) -> list[BaseTool]:- return list(self._tools.values())-- def get(self, name: str) -> BaseTool | None:- return self._tools.get(name)---class FakeManager:- async def ensure_started(self) -> None:- return None---def _prepare(monkeypatch, docs: dict[str, dict[str, str]]) -> AgenticChatPipeline:- pipe = AgenticChatPipeline(language="en")- pageindex_tool = FakeMCPTool("pageindex", "get_page_content")- other_tool = FakeMCPTool("other", "do_thing")- pipe.registry = FakeRegistry([pageindex_tool, other_tool])-- monkeypatch.setattr("deeptutor.services.mcp.get_mcp_manager", lambda: FakeManager())- monkeypatch.setattr("deeptutor.services.mcp.load_loaded_tools", lambda _sid: set())- # Non-admin user without an MCP grant: fail-closed empty whitelist.- monkeypatch.setattr("deeptutor.multi_user.tool_access.allowed_mcp_tools", lambda: set())- monkeypatch.setattr(pipe, "_pageindex_doc_maps", lambda _ctx: docs)-- ctx = UnifiedContext(knowledge_bases=list(docs))- asyncio.run(pipe._prepare_deferred_tools(ctx))- return pipe---def test_pageindex_kb_grants_and_preloads_server_tools(monkeypatch) -> None:- pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})-- pool_names = {t.get_definition().name for t in pipe._deferred_pool}- # Implicit grant covers exactly the pageindex server, not other MCP tools.- assert pool_names == {"mcp_pageindex_get_page_content"}- # Preloaded: schema present without a load_tools round-trip.- assert pipe._deferred_loader is not None- preloaded = {s["function"]["name"] for s in pipe._deferred_loader.initial_schemas()}- assert "mcp_pageindex_get_page_content" in preloaded---def test_no_pageindex_kb_keeps_fail_closed(monkeypatch) -> None:- pipe = _prepare(monkeypatch, {})- assert pipe._deferred_pool == []- assert pipe._deferred_loader is None---def test_system_note_lists_documents(monkeypatch) -> None:- pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1", "b.docx": "pi-2"}})- note = pipe._kb_system_note(UnifiedContext(knowledge_bases=["kb1"]))- assert "mcp_pageindex_get_document_structure" in note- assert "a.pdf (doc_id: pi-1)" in note- assert "b.docx (doc_id: pi-2)" in note- # Pure-pageindex conversation: rag isn't mounted, so no rag wording at all.- assert "calling rag" not in note---def test_rag_kbs_excludes_pageindex(monkeypatch) -> None:- pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})- ctx = UnifiedContext(knowledge_bases=["kb1", "kb2"])- # kb1 is pageindex → excluded from the rag tool surface; kb2 stays.- assert pipe._rag_kbs(ctx) == ["kb2"]- note = pipe._kb_system_note(ctx)- assert "Attached knowledge bases: kb2." in note- assert "kb1" in note # listed in the PageIndex MCP block insteaddiff --git a/tests/agents/chat/test_pageindex_sdk_tools.py b/tests/agents/chat/test_pageindex_sdk_tools.pynew file mode 100644index 000000000..a76f12e49--- /dev/null+++ b/tests/agents/chat/test_pageindex_sdk_tools.py@@ -0,0 +1,223 @@+"""Chat-side PageIndex SDK tool wiring.++Attaching a PageIndex KB overlays the SDK's tools for that turn, preloads them+(no load_tools round-trip), and injects the SDK's reading instructions without+publishing PageIndex into the global MCP registry.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolResult+from deeptutor.runtime.registry.deferred_tools import render_deferred_tools_manifest+++class FakeMCPTool(BaseTool):+ deferred = True++ def __init__(self, server: str, name: str) -> None:+ self.server_name = server+ self._name = f"mcp_{server}_{name}"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name=self._name,+ description="fake",+ raw_parameters={"type": "object", "properties": {}},+ )++ async def execute(self, **kwargs) -> ToolResult: # pragma: no cover - unused+ return ToolResult(content="")+++class FakeRegistry:+ def __init__(self, tools: list[BaseTool]) -> None:+ self._tools = {t.get_definition().name: t for t in tools}++ def deferred_tools(self) -> list[BaseTool]:+ return list(self._tools.values())++ def get(self, name: str) -> BaseTool | None:+ return self._tools.get(name)+++class FakeManager:+ async def ensure_started(self) -> None:+ return None++ async def ensure_scope(self, _owner: str) -> list[BaseTool]:+ return []+++def _prepare(monkeypatch, docs: dict[str, dict[str, str]]) -> AgenticChatPipeline:+ monkeypatch.setattr(+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",+ lambda: SimpleNamespace(+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None+ ),+ )+ pipe = AgenticChatPipeline(language="en")+ other_tool = FakeMCPTool("other", "do_thing")+ pipe.registry = FakeRegistry([other_tool])++ pageindex_tool = FakeMCPTool("unused", "get_page_content")+ pageindex_tool._name = "pageindex_cloud_get_page_content"+ pageindex_tool.server_name = ""+ pageindex_tool.provider_kind = "pageindex"+ pageindex_tool.provider_id = "pageindex"++ monkeypatch.setattr("deeptutor.services.mcp.get_mcp_manager", lambda: FakeManager())+ monkeypatch.setattr("deeptutor.services.mcp.load_loaded_tools", lambda _sid: set())+ # Non-admin user without an MCP grant: fail-closed empty whitelist.+ monkeypatch.setattr("deeptutor.multi_user.tool_access.allowed_mcp_tools", lambda: set())+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.pageindex.is_pageindex_kb",+ lambda name: name in docs,+ )++ async def bundles(_ctx):+ if not docs:+ return []+ kb, documents = next(iter(docs.items()))+ return [+ (+ kb,+ SimpleNamespace(+ provider="pageindex",+ tools=(pageindex_tool,),+ documents=documents,+ instructions="Use structure, then pages.",+ ),+ )+ ]++ monkeypatch.setattr(pipe, "_pageindex_sdk_tool_bundles", bundles)++ ctx = UnifiedContext(knowledge_bases=list(docs))+ asyncio.run(pipe._prepare_deferred_tools(ctx))+ return pipe+++def test_pageindex_kb_preloads_turn_scoped_sdk_tools(monkeypatch) -> None:+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})++ pool_names = {t.get_definition().name for t in pipe._deferred_pool}+ assert pool_names == {"pageindex_cloud_get_page_content"}+ # Preloaded: schema present without a load_tools round-trip.+ assert pipe._deferred_loader is not None+ preloaded = {s["function"]["name"] for s in pipe._deferred_loader.initial_schemas()}+ assert "pageindex_cloud_get_page_content" in preloaded+++def test_no_pageindex_kb_keeps_fail_closed(monkeypatch) -> None:+ pipe = _prepare(monkeypatch, {})+ assert pipe._deferred_pool == []+ assert pipe._deferred_loader is None+++def test_system_note_omits_document_metadata(monkeypatch) -> None:+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1", "b.docx": "pi-2"}})+ note = pipe._kb_system_note(UnifiedContext(knowledge_bases=["kb1"]))+ assert "pageindex_cloud_*" in note+ assert "Do not use rag to read these PageIndex knowledge bases" in note+ assert "Use structure, then pages." in note+ assert "a.pdf" not in note+ assert "b.docx" not in note+ assert "doc_id" not in note+ # Pure-pageindex conversation: rag isn't mounted, so no rag wording at all.+ assert "calling rag" not in note+++def test_rag_kbs_excludes_pageindex(monkeypatch) -> None:+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})+ ctx = UnifiedContext(knowledge_bases=["kb1", "kb2"])+ # kb1 is pageindex → excluded from the rag tool surface; kb2 stays.+ assert pipe._rag_kbs(ctx) == ["kb2"]+ note = pipe._kb_system_note(ctx)+ assert "Attached knowledge bases: kb2." in note+ assert "kb1" not in note+++def test_pageindex_kb_is_never_preseeded(monkeypatch) -> None:+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})+ called: list[str] = []++ async def seed(kb, _query, _stream):+ called.append(kb)+ return "context", []++ monkeypatch.setattr(pipe, "_seed_search_one_kb", seed)+ context = UnifiedContext(user_message="question", knowledge_bases=["kb1", "kb2"])+ asyncio.run(pipe._retrieve_kb_seed_block(context, StreamBus()))+ assert called == ["kb2"]+++def test_oss_tools_are_turn_scoped_preloaded_and_excluded_from_rag(monkeypatch) -> None:+ monkeypatch.setattr(+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",+ lambda: SimpleNamespace(+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None+ ),+ )+ pipe = AgenticChatPipeline(language="en")+ pipe.registry = FakeRegistry([])+ oss_tool = FakeMCPTool("pageindex_oss", "get_page_content")+ oss_tool._name = "pageindex_oss_get_page_content"+ oss_tool.server_name = ""++ monkeypatch.setattr("deeptutor.services.mcp.get_mcp_manager", lambda: FakeManager())+ monkeypatch.setattr("deeptutor.services.mcp.load_loaded_tools", lambda _sid: set())+ monkeypatch.setattr("deeptutor.multi_user.tool_access.allowed_mcp_tools", lambda: set())+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.pageindex.is_pageindex_kb",+ lambda name: name == "oss-kb",+ )++ async def bundles(_ctx):+ return [+ (+ "oss-kb",+ SimpleNamespace(+ provider="pageindex-oss",+ tools=(oss_tool,),+ documents={"manual.pdf": "pi-local"},+ instructions="Read structure, then pages.",+ ),+ )+ ]++ monkeypatch.setattr(pipe, "_pageindex_sdk_tool_bundles", bundles)+ ctx = UnifiedContext(knowledge_bases=["oss-kb", "vectors"])+ asyncio.run(pipe._prepare_deferred_tools(ctx))++ assert pipe.tool_lookup.get("pageindex_oss_get_page_content") is oss_tool+ assert pipe._rag_kbs(ctx) == ["vectors"]+ assert "pageindex_oss_get_page_content" in {+ schema["function"]["name"] for schema in pipe._deferred_loader.initial_schemas()+ }+ note = pipe._pageindex_system_note()+ assert "manual.pdf" not in note+ assert "doc_id" not in note+ assert "Read structure, then pages." in note+ assert "Do not use rag to read these PageIndex knowledge bases" in note+++def test_pageindex_tools_keep_cloud_and_oss_manifest_groups() -> None:+ cloud = FakeMCPTool("unused", "get_page_content")+ cloud._name = "pageindex_cloud_get_page_content"+ cloud.provider_kind = "pageindex"+ cloud.provider_id = "pageindex"+ oss = FakeMCPTool("unused", "get_page_content")+ oss._name = "pageindex_oss_get_page_content"+ oss.provider_kind = "pageindex"+ oss.provider_id = "pageindex-oss"++ manifest = render_deferred_tools_manifest([cloud, oss])++ assert "### PageIndex Cloud" in manifest+ assert "### PageIndex OSS" in manifestdiff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 29b1ee4a6..a6cb26905 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -147,6 +147,7 @@ def test_rag_providers_lists_llamaindex_and_pageindex(monkeypatch) -> None:assert set(by_id) == {"llamaindex","pageindex",+ "pageindex-oss","graphrag","lightrag","lightrag-server",@@ -156,6 +157,7 @@ def test_rag_providers_lists_llamaindex_and_pageindex(monkeypatch) -> None:# LightRAG are optional local engines (no API key, configured = installed).assert by_id["llamaindex"]["requires_api_key"] is Falseassert by_id["pageindex"]["requires_api_key"] is True+ assert by_id["pageindex-oss"]["requires_api_key"] is Falseassert by_id["graphrag"]["requires_api_key"] is Falseassert by_id["lightrag"]["requires_api_key"] is False# LightRAG Server is a thin HTTP client: always available, no API key gate@@ -1663,3 +1665,136 @@ def test_assert_not_connected_kb_blocks_connected_writes() -> None:assert excinfo.value.status_code == 409# An ordinary KB is writable — the guard is a no-op.guard("kb", {"path": "kb", "status": "ready"})+++def _write_upload_task_kb(tmp_path: Path) -> Path:+ base_dir = tmp_path / "knowledge_bases"+ kb_dir = base_dir / "kb"+ (kb_dir / "raw").mkdir(parents=True)+ _write_ready_llamaindex_version(kb_dir)+ (base_dir / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "rag_provider": "llamaindex",+ "status": "ready",+ }+ }+ }+ ),+ encoding="utf-8",+ )+ return base_dir+++def test_create_pageindex_oss_persists_optional_mode(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases")+ preflight = importlib.import_module("deeptutor.services.rag.preflight")+ monkeypatch.setattr(preflight, "engine_preflight", lambda _provider: {"ok": True, "checks": []})++ async def _noop_init_task(*_args, **_kwargs):+ return None++ monkeypatch.setattr(knowledge_router_module, "run_initialization_task", _noop_init_task)+ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/create",+ data={+ "name": "kb-oss",+ "rag_provider": "pageindex-oss",+ "pageindex_mode": "standard",+ },+ files=[("files", ("demo.pdf", b"%PDF-1.4\n", "application/pdf"))],+ )++ assert response.status_code == 200+ entry = manager.config["knowledge_bases"]["kb-oss"]+ assert entry["rag_provider"] == "pageindex-oss"+ assert entry["pageindex_mode"] == "standard"+++def test_create_pageindex_oss_rejects_non_pdf(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases")+ preflight = importlib.import_module("deeptutor.services.rag.preflight")+ monkeypatch.setattr(preflight, "engine_preflight", lambda _provider: {"ok": True, "checks": []})++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/create",+ data={"name": "kb-oss-docx", "rag_provider": "pageindex-oss"},+ files=[+ (+ "files",+ (+ "demo.docx",+ b"placeholder",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ ),+ )+ ],+ )++ assert response.status_code == 400+ assert "accept: .pdf" in response.json()["detail"]+ assert "kb-oss-docx" not in manager.config["knowledge_bases"]+++def test_upload_progress_counts_completed_files_and_reports_reliable_stages(+ monkeypatch, tmp_path: Path+) -> None:+ base_dir = _write_upload_task_kb(tmp_path)+ source = tmp_path / "ok.txt"+ source.write_text("ok", encoding="utf-8")++ class _SuccessfulRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def add_documents(self, *_args, **_kwargs) -> bool:+ return True++ monkeypatch.setattr(+ "deeptutor.knowledge.add_documents.RAGService",+ _SuccessfulRagService,+ )+ updates: list[tuple[str, int, int]] = []+ original_update = knowledge_router_module.ProgressTracker.update++ def _record_update(self, stage, message="", current=0, total=0, **kwargs):+ updates.append((message, current, total))+ return original_update(+ self,+ stage,+ message,+ current=current,+ total=total,+ **kwargs,+ )++ monkeypatch.setattr(knowledge_router_module.ProgressTracker, "update", _record_update)++ asyncio.run(+ knowledge_router_module.run_upload_processing_task(+ kb_name="kb",+ base_dir=str(base_dir),+ uploaded_file_paths=[str(source)],+ task_id="upload-progress-test",+ rag_provider="llamaindex",+ )+ )++ assert updates == [+ ("Validating 1 file(s)...", 0, 1),+ ("Staged 1 new file(s)", 0, 1),+ ("Indexing ok.txt", 0, 1),+ ("Indexed ok.txt", 1, 1),+ ("Saving metadata...", 1, 1),+ ("Successfully processed 1 files!", 1, 1),+ ]diff --git a/tests/book/test_source_partitioning.py b/tests/book/test_source_partitioning.pyindex 4c5b44c12..d6a179402 100644--- a/tests/book/test_source_partitioning.py+++ b/tests/book/test_source_partitioning.py@@ -12,6 +12,8 @@ over HTTP. Excluding every "connected" KB silently dropped those sources.from __future__ import annotations+from types import SimpleNamespace+import pytestfrom deeptutor.book.agents.source_explorer import SourceExplorer, _balanced_slice@@ -109,3 +111,39 @@ def test_within_a_source_the_best_chunks_still_win() -> None:def test_a_small_sweep_is_returned_whole() -> None:chunks = [_chunk("kb", "a", 1.0), _chunk("kb", "b", 2.0)]assert len(_balanced_slice(chunks, limit=24)) == 2+++async def test_pageindex_is_read_by_source_explorer_agent_not_rag(monkeypatch) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb",+ lambda name, **_kwargs: SimpleNamespace(base_dir="/kb", name=name),+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.provider_binding.resolve_bound_provider",+ lambda _base, _name: "pageindex-oss",+ )++ async def read(**_kwargs):+ return SimpleNamespace(+ text="Evidence from pages 3 and 7.",+ sources=[{"type": "pageindex", "page": 3}],+ tool_context=SimpleNamespace(provider="pageindex-oss"),+ )++ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.pageindex.reasoning.read_pageindex_with_agent",+ read,+ )++ async def no_rag(**_kwargs):+ pytest.fail("PageIndex SourceExplorer called rag_search")++ monkeypatch.setattr("deeptutor.tools.rag_tool.rag_search", no_rag)+ explorer = SourceExplorer(language="en")+ chunks = await explorer._retrieve_kb_chunks(["revenue"], ["reports"])++ assert len(chunks) == 1+ assert chunks[0].kb_name == "reports"+ assert chunks[0].text == "Evidence from pages 3 and 7."+ assert chunks[0].metadata["sources"][0]["page"] == 3diff --git a/tests/logging/test_task_log_stream.py b/tests/logging/test_task_log_stream.pyindex d1c82d990..fa3640f03 100644--- a/tests/logging/test_task_log_stream.py+++ b/tests/logging/test_task_log_stream.py@@ -1,3 +1,4 @@+import asyncioimport jsonimport logging@@ -32,6 +33,25 @@ async def test_knowledge_task_stream_emits_process_log_sse_event():assert payload["context"]["task_id"] == "task-1"+async def test_knowledge_task_stream_keeps_idle_sse_connection_alive():+ manager = KnowledgeTaskStreamManager()+ manager._HEARTBEAT_SECONDS = 0.01+ manager.ensure_task("task-idle")++ stream = manager.stream("task-idle")+ try:+ heartbeat = await asyncio.wait_for(anext(stream), timeout=0.2)+ assert heartbeat == ": keep-alive\n\n"++ manager.emit_log("task-idle", "Indexing resumed")+ event = await asyncio.wait_for(anext(stream), timeout=0.2)+ assert "event: process_log" in event+ assert "Indexing resumed" in event+ finally:+ await stream.aclose()++def test_knowledge_task_stream_emits_structured_failure_metadata():manager = KnowledgeTaskStreamManager()manager.ensure_task("task-failed")@@ -147,6 +167,39 @@ def test_capture_task_logs_excludes_private_non_propagating_library_diagnostics(assert events == []+def test_capture_task_logs_keeps_user_stages_and_drops_runtime_noise():+ original_instance = KnowledgeTaskStreamManager._instance+ loggers = {+ name: logging.getLogger(name)+ for name in (+ "root",+ "asyncio",+ "deeptutor.knowledge.progress_tracker",+ "deeptutor.services.rag.pipelines.pageindex.pipeline",+ )+ }+ original_levels = {name: logger.level for name, logger in loggers.items()}+ try:+ KnowledgeTaskStreamManager._instance = KnowledgeTaskStreamManager()+ for logger in loggers.values():+ logger.setLevel(logging.INFO)+ with capture_task_logs("task-curated"):+ loggers["root"].error("Request timed out")+ loggers["asyncio"].error("Event loop is closed")+ loggers["deeptutor.knowledge.progress_tracker"].info("duplicate progress")+ loggers["deeptutor.services.rag.pipelines.pageindex.pipeline"].info(+ "PageIndex: submitting manual.pdf"+ )+ events = list(get_task_stream_manager()._buffers["task-curated"])+ finally:+ KnowledgeTaskStreamManager._instance = original_instance+ for name, logger in loggers.items():+ logger.setLevel(original_levels[name])++ messages = [event["payload"]["message"] for event in events]+ assert messages == ["PageIndex: submitting manual.pdf"]++def test_completed_task_buffers_are_bounded_and_restore_terminal_event():manager = KnowledgeTaskStreamManager()manager._MAX_RETAINED_TASKS = 3diff --git a/tests/runtime/providers/test_authorize.py b/tests/runtime/providers/test_authorize.pyindex 7dfeac409..1fcef5a4f 100644--- a/tests/runtime/providers/test_authorize.py+++ b/tests/runtime/providers/test_authorize.py@@ -1,10 +1,9 @@"""MCP authorisation across caller kind × grant source.-The matrix matters because the four callers fail in different directions:-an administrator must not be narrowed by a resource-derived grant, an-ungranted user must not be widened by one beyond that resource, a partner is-governed by its own configured filter rather than a (nonexistent) grant, and-an exclusive knowledge capability must suppress everything it does not own.+The matrix matters because the callers fail in different directions: an+administrator must stay unrestricted, an ungranted user must fail closed, a+partner is governed by its own configured filter rather than a (nonexistent)+grant, and an exclusive knowledge capability suppresses generic MCP tools."""from __future__ import annotations@@ -18,11 +17,10 @@ GRANTED = Allowlist.of(["mcp_gh_search"])UNGRANTED = Allowlist.of([]) # what allowed_mcp_tools() returns for a plain user-def test_admin_stays_unrestricted_even_with_an_implicit_grant() -> None:+def test_admin_stays_unrestricted() -> None:allowed = authorize_mcp_tools(scope=ToolScope(owner_id="admin"),user_grant=ADMIN_GRANT,- implicit_names=["mcp_pageindex_search"],)assert allowed.is_unrestrictedassert allowed.allows("mcp_anything_else")@@ -33,24 +31,6 @@ def test_ungranted_user_fails_closed() -> None:assert allowed.names == frozenset()-def test_ungranted_user_gets_only_the_resource_they_hold() -> None:- allowed = authorize_mcp_tools(- scope=ToolScope(owner_id="u1"),- user_grant=UNGRANTED,- implicit_names=["mcp_pageindex_search"],- )- assert allowed.names == frozenset({"mcp_pageindex_search"})---def test_granted_user_keeps_grant_plus_resource() -> None:- allowed = authorize_mcp_tools(- scope=ToolScope(owner_id="u1"),- user_grant=GRANTED,- implicit_names=["mcp_pageindex_search"],- )- assert allowed.names == frozenset({"mcp_gh_search", "mcp_pageindex_search"})--def test_owned_servers_are_authorised_by_ownership_not_by_grant() -> None:"""A user's self-configured server is their own property.@@ -94,15 +74,14 @@ def test_partner_with_explicit_none_filter_is_unrestricted() -> None:assert allowed.is_unrestricted-def test_exclusive_capability_suppresses_everything_but_the_resource() -> None:+def test_exclusive_capability_suppresses_every_configured_mcp_tool() -> None:for grant in (ADMIN_GRANT, GRANTED, UNGRANTED):allowed = authorize_mcp_tools(scope=ToolScope(owner_id="u1", exclusive_capability=True),user_grant=grant,- implicit_names=["mcp_pageindex_search"],owned_names=["mcp_mynotion_search"],)- assert allowed.names == frozenset({"mcp_pageindex_search"})+ assert allowed.names == frozenset()assert not allowed.allows("mcp_mynotion_search")diff --git a/tests/runtime/providers/test_view.py b/tests/runtime/providers/test_view.pyindex c5cb322f1..ffc177af5 100644--- a/tests/runtime/providers/test_view.py+++ b/tests/runtime/providers/test_view.py@@ -82,7 +82,7 @@ async def test_empty_pool_yields_an_empty_view() -> None:@pytest.mark.asyncio-async def test_admin_sees_every_provider_tool(registry, monkeypatch) -> None:+async def test_admin_sees_every_configured_mcp_provider(registry, monkeypatch) -> None:_grant(monkeypatch, None)view = await build_tool_view(base_registry=registry, scope=ToolScope(session_id="s"))assert {t.name for t in view.pool} == {"mcp_gh_search", "mcp_pageindex_search"}@@ -104,53 +104,45 @@ async def test_ungranted_user_gets_no_tools_but_keeps_the_gate(registry, monkeyp@pytest.mark.asyncio-async def test_attached_pageindex_kb_authorises_and_preloads_that_server(- registry, monkeypatch-) -> None:- _grant(monkeypatch, set())+async def test_exclusive_capability_suppresses_configured_mcp_tools(registry, monkeypatch) -> None:+ _grant(monkeypatch, None)view = await build_tool_view(base_registry=registry,- scope=ToolScope(session_id="s", implicit_provider_ids=frozenset({PAGEINDEX})),+ scope=ToolScope(session_id="s", exclusive_capability=True),)- assert {t.name for t in view.pool} == {"mcp_pageindex_search"}- assert view.loader is not None- # Preloaded: holding the KB is the permission, so no load_tools round-trip.- assert view.loader.loaded_names == {"mcp_pageindex_search"}+ assert view.manifest == ""+ assert view.pool == ()+ assert view.loader is None@pytest.mark.asyncio-async def test_exclusive_capability_suppresses_the_manifest_but_keeps_preloads(- registry, monkeypatch-) -> None:- _grant(monkeypatch, None)+async def test_partner_uses_its_own_filter(registry, monkeypatch) -> None:+ _grant(monkeypatch, set()) # would deny everything if it were consultedview = await build_tool_view(base_registry=registry,scope=ToolScope(session_id="s",- implicit_provider_ids=frozenset({PAGEINDEX}),- exclusive_capability=True,+ is_partner=True,+ caller_whitelist=frozenset({"mcp_gh_search"}),),)- # Nothing is advertised (load_tools is not even mounted on such a turn) …- assert view.manifest == ""- # … but the resource-authorised tool is still usable.- assert {t.name for t in view.pool} == {"mcp_pageindex_search"}- assert view.loader is not None- assert view.loader.loaded_names == {"mcp_pageindex_search"}+ assert {t.name for t in view.pool} == {"mcp_gh_search"}@pytest.mark.asyncio-async def test_partner_uses_its_own_filter(registry, monkeypatch) -> None:- _grant(monkeypatch, set()) # would deny everything if it were consulted+async def test_partner_can_select_an_ordinarily_configured_pageindex_mcp(+ registry, monkeypatch+) -> None:+ _grant(monkeypatch, set())view = await build_tool_view(base_registry=registry,scope=ToolScope(session_id="s",is_partner=True,- caller_whitelist=frozenset({"mcp_gh_search"}),+ caller_whitelist=frozenset({"mcp_pageindex_search"}),),)- assert {t.name for t in view.pool} == {"mcp_gh_search"}+ assert {tool.name for tool in view.pool} == {"mcp_pageindex_search"}@pytest.mark.asyncio@@ -181,7 +173,10 @@ async def test_attach_adds_loaded_schemas_and_binds_the_live_list(registry, monk# Bound: a later load_tools call reaches the same list the loop re-reads.assert view.loader is not Noneview.loader.load(["mcp_pageindex_search"])- assert [s["function"]["name"] for s in live] == ["mcp_gh_search", "mcp_pageindex_search"]+ assert [s["function"]["name"] for s in live] == [+ "mcp_gh_search",+ "mcp_pageindex_search",+ ]@pytest.mark.asynciodiff --git a/tests/services/config/test_pageindex_settings.py b/tests/services/config/test_pageindex_settings.pyindex 0b7712fd6..1439f7881 100644--- a/tests/services/config/test_pageindex_settings.py+++ b/tests/services/config/test_pageindex_settings.py@@ -9,12 +9,11 @@ from deeptutor.services.config.runtime_settings import RuntimeSettingsServicedef test_pageindex_settings_roundtrip(tmp_path: Path) -> None:svc = RuntimeSettingsService(tmp_path, process_env={})- svc.save_pageindex({"api_key": "sk-abc123", "api_base_url": "https://api.pageindex.ai/"})+ svc.save_pageindex({"api_key": "sk-abc123"})loaded = svc.load_pageindex(include_process_overrides=False)assert loaded["api_key"] == "sk-abc123"- # Trailing slash normalised away.- assert loaded["api_base_url"] == "https://api.pageindex.ai"+ assert set(loaded) == {"version", "api_key"}# Persisted to its own file beside other per-feature settings.assert (tmp_path / "pageindex.json").exists()@@ -24,7 +23,7 @@ def test_pageindex_defaults_when_absent(tmp_path: Path) -> None:svc = RuntimeSettingsService(tmp_path, process_env={})loaded = svc.load_pageindex(include_process_overrides=False)assert loaded["api_key"] == ""- assert loaded["api_base_url"] == "https://api.pageindex.ai"+ assert set(loaded) == {"version", "api_key"}def test_pageindex_env_override(tmp_path: Path) -> None:@@ -34,4 +33,4 @@ def test_pageindex_env_override(tmp_path: Path) -> None:)loaded = svc.load_pageindex(include_process_overrides=True)assert loaded["api_key"] == "from-env"- assert loaded["api_base_url"] == "https://x.test"+ assert "api_base_url" not in loadeddiff --git a/tests/services/mcp/test_pageindex_server.py b/tests/services/mcp/test_pageindex_server.pydeleted file mode 100644index 4f2f93e8c..000000000--- a/tests/services/mcp/test_pageindex_server.py+++ /dev/null@@ -1,68 +0,0 @@-"""Built-in pageindex MCP server injection."""--from __future__ import annotations--from deeptutor.services.mcp import pageindex_server-from deeptutor.services.mcp.config import MCPConfig, MCPServerConfig-from deeptutor.services.mcp.manager import wrapped_tool_name-from deeptutor.services.rag.pipelines.pageindex.config import (- PageIndexConfig,- PageIndexNotConfiguredError,-)---def _configured(monkeypatch, key: str = "sk-test") -> None:- monkeypatch.setattr(- "deeptutor.services.rag.pipelines.pageindex.config.get_pageindex_config",- lambda **_: PageIndexConfig(api_key=key, api_base_url="https://api.pageindex.ai"),- )---def _unconfigured(monkeypatch) -> None:- def _raise(**_):- raise PageIndexNotConfiguredError("no key")-- monkeypatch.setattr(- "deeptutor.services.rag.pipelines.pageindex.config.get_pageindex_config", _raise- )---def test_injects_builtin_server_when_configured(monkeypatch) -> None:- _configured(monkeypatch)- config = pageindex_server.with_builtin_servers(MCPConfig())- entry = config.servers["pageindex"]- assert entry.url == "https://api.pageindex.ai/mcp"- assert entry.headers["Authorization"] == "Bearer sk-test"- assert entry.resolved_type() == "streamableHttp"---def test_no_injection_without_key(monkeypatch) -> None:- _unconfigured(monkeypatch)- config = pageindex_server.with_builtin_servers(MCPConfig())- assert "pageindex" not in config.servers---def test_user_defined_entry_wins(monkeypatch) -> None:- _configured(monkeypatch)- user = MCPConfig(servers={"pageindex": MCPServerConfig(url="https://example.com/mcp")})- config = pageindex_server.with_builtin_servers(user)- assert config.servers["pageindex"].url == "https://example.com/mcp"---def test_builtin_blocks_remove_document(monkeypatch) -> None:- _configured(monkeypatch)- entry = pageindex_server.builtin_pageindex_server()- assert entry is not None- assert not entry.tool_allowed(- "remove_document", wrapped_tool_name("pageindex", "remove_document")- )- # Everything else passes through untouched.- assert entry.tool_allowed(- "get_page_content", wrapped_tool_name("pageindex", "get_page_content")- )---def test_disabled_tools_blocklist_beats_wildcard() -> None:- cfg = MCPServerConfig(url="https://x/mcp", disabled_tools=["bad_tool"])- assert not cfg.tool_allowed("bad_tool", wrapped_tool_name("x", "bad_tool"))- assert cfg.tool_allowed("good_tool", wrapped_tool_name("x", "good_tool"))diff --git a/tests/services/rag/test_index_probe.py b/tests/services/rag/test_index_probe.pyindex 6eaf53f83..7fecacef0 100644--- a/tests/services/rag/test_index_probe.py+++ b/tests/services/rag/test_index_probe.py@@ -83,6 +83,27 @@ def test_pageindex_ready_requires_doc_ids(tmp_path: Path) -> None:assert probe.doc_count == 1+def test_pageindex_oss_requires_local_sdk_artifacts(tmp_path: Path) -> None:+ version_dir = tmp_path / "version-1"+ version_dir.mkdir()+ _write_meta(version_dir, provider="pageindex-oss")+ manifest = pageindex_storage.read_manifest(version_dir, provider="pageindex-oss")+ pageindex_storage.upsert_doc(manifest, "lesson.pdf", "pi-local")+ pageindex_storage.write_manifest(version_dir, manifest)++ probe = inspect_provider_index("pageindex-oss", version_dir)+ assert probe.ready is False++ doc_dir = pageindex_storage.sdk_storage_path(version_dir) / "docs" / "pi-local"+ doc_dir.mkdir(parents=True)+ for name in ("doc.json", "tree.json", "pages.json"):+ (doc_dir / name).write_text("{}", encoding="utf-8")++ probe = inspect_provider_index("pageindex-oss", version_dir)+ assert probe.ready is True+ assert probe.doc_count == 1++def test_graphrag_ready_requires_core_output_table(tmp_path: Path) -> None:version_dir = tmp_path / "version-1"version_dir.mkdir()diff --git a/tests/services/rag/test_pageindex_pipeline.py b/tests/services/rag/test_pageindex_pipeline.pyindex 948b0f188..22f954c7b 100644--- a/tests/services/rag/test_pageindex_pipeline.py+++ b/tests/services/rag/test_pageindex_pipeline.py@@ -1,9 +1,7 @@-"""Unit tests for the PageIndex cloud RAG pipeline + provider routing.+"""Unit tests for PageIndex SDK lifecycle and provider routing.The pipeline talks to PageIndex's REST API through an injectable client, so we-exercise the orchestration (file filtering, manifest, outline search contract,-delete) against a fake client without any network calls. Deep retrieval is-agentic via the PageIndex MCP server and out of scope here.+ exercise the orchestration against a fake client without network calls."""from __future__ import annotations@@ -12,9 +10,14 @@ import asyncioimport jsonfrom pathlib import Path+import pytest+from deeptutor.services.rag.factory import get_pipeline, normalize_provider_namefrom deeptutor.services.rag.index_versioning import resolve_storage_dir_for_read+from deeptutor.services.rag.pipelines.pageindex import client as client_modfrom deeptutor.services.rag.pipelines.pageindex import storage+from deeptutor.services.rag.pipelines.pageindex.client import PageIndexClient+from deeptutor.services.rag.pipelines.pageindex.config import PageIndexConfigfrom deeptutor.services.rag.pipelines.pageindex.pipeline import (PageIndexPipeline,is_supported_file,@@ -27,23 +30,13 @@ class FakeClient:def __init__(self) -> None:self.submitted: list[str] = []self.deleted: list[str] = []- self.trees: dict[str, list[dict]] = {}+ self.modes: list[str | None] = []- async def submit_document(self, file_path) -> str:+ async def submit_document(self, file_path, *, mode=None) -> str:self.submitted.append(str(file_path))+ self.modes.append(mode)return f"pi-{Path(file_path).name}"- async def wait_until_ready(self, doc_id, **_kwargs) -> dict:- return {"status": "completed", "retrieval_ready": True}-- async def get_document(self, doc_id, **_kwargs) -> dict:- return {- "doc_id": doc_id,- "status": "completed",- "retrieval_ready": True,- "result": self.trees.get(doc_id, []),- }-async def delete_document(self, doc_id) -> bool:self.deleted.append(doc_id)return True@@ -64,6 +57,8 @@ def test_is_supported_file() -> None:assert is_supported_file(name), nameassert not is_supported_file("i.png")assert not is_supported_file("j.zip") # containers are unpacked upstream+ assert is_supported_file("a.PDF", "pageindex-oss")+ assert not is_supported_file("b.docx", "pageindex-oss")def test_initialize_submits_supported_and_skips_others(tmp_path) -> None:@@ -108,38 +103,38 @@ def test_add_documents_appends_to_manifest(tmp_path) -> None:assert set(_manifest(tmp_path, "kb")["docs"]) == {"a.pdf", "b.pdf"}-def test_search_returns_document_outline(tmp_path) -> None:+def test_oss_accepts_pdf_only_and_forwards_explicit_mode(tmp_path, monkeypatch) -> None:+ client = FakeClient()+ pipe = PageIndexPipeline(+ kb_base_dir=str(tmp_path),+ client=client,+ provider="pageindex-oss",+ )+ monkeypatch.setattr(pipe, "_processing_mode", lambda _kb: "standard")+ pdf = tmp_path / "a.pdf"+ pdf.write_text("x")+ docx = tmp_path / "b.docx"+ docx.write_text("y")++ assert asyncio.run(pipe.initialize("oss", [str(pdf), str(docx)])) is True+ assert [Path(path).name for path in client.submitted] == ["a.pdf"]+ assert client.modes == ["standard"]+ assert _manifest(tmp_path, "oss")["provider"] == "pageindex-oss"+++def test_search_requires_reasoning_as_retrieval(tmp_path) -> None:client = FakeClient()pipe = _pipe(tmp_path, client)pdf = tmp_path / "a.pdf"pdf.write_text("x")asyncio.run(pipe.initialize("kb", [str(pdf)]))- client.trees["pi-a.pdf"] = [- {- "title": "Introduction",- "node_id": "n1",- "page_index": 1,- "prefix_summary": "What this paper is about.",- "nodes": [- {"title": "Background", "node_id": "n2", "page_index": 2, "summary": "History."}- ],- }- ]-res = asyncio.run(pipe.search("what?", "kb"))assert res["provider"] == "pageindex"- assert "error_type" not in res- # Real structural context: nested outline with titles, pages, summaries.- assert "- Introduction (p.1): What this paper is about." in res["content"]- assert " - Background (p.2): History." in res["content"]- assert res["answer"] == res["content"]- # Sources come from top-level sections, anchored to the file.- assert res["sources"][0]["title"] == "Introduction"- assert res["sources"][0]["page"] == 1- assert res["sources"][0]["source"] == "a.pdf"- assert res["sources"][0]["chunk_id"] == "n1"+ assert res["error_type"] == "reasoning_as_retrieval_required"+ assert res["content"] == ""+ assert res["sources"] == []def test_document_map_exposes_manifest(tmp_path) -> None:@@ -153,9 +148,9 @@ def test_document_map_exposes_manifest(tmp_path) -> None:assert pipe.document_map("missing-kb") == {}-def test_search_without_documents_flags_reindex(tmp_path) -> None:+def test_search_without_documents_still_requires_agent_loop(tmp_path) -> None:res = asyncio.run(_pipe(tmp_path, FakeClient()).search("q", "missing-kb"))- assert res["needs_reindex"] is True+ assert res["error_type"] == "reasoning_as_retrieval_required"assert res["sources"] == []assert res["provider"] == "pageindex"@@ -174,6 +169,18 @@ def test_delete_drops_cloud_docs_and_local_dir(tmp_path) -> None:assert not (tmp_path / "kb").exists()+def test_remove_document_updates_sdk_and_manifest(tmp_path) -> None:+ client = FakeClient()+ pipe = _pipe(tmp_path, client)+ pdf = tmp_path / "a.pdf"+ pdf.write_text("x")+ asyncio.run(pipe.initialize("kb", [str(pdf)]))++ assert asyncio.run(pipe.remove_document("kb", "a.pdf")) is True+ assert client.deleted == ["pi-a.pdf"]+ assert _manifest(tmp_path, "kb")["docs"] == {}++def test_factory_dispatches_by_provider(tmp_path, monkeypatch) -> None:# Constructing a real LlamaIndexPipeline resolves the active embedding model# from the catalog; CI has none, so stub the settings hook (the same way the@@ -185,6 +192,9 @@ def test_factory_dispatches_by_provider(tmp_path, monkeypatch) -> None:assert (type(get_pipeline("pageindex", kb_base_dir=str(tmp_path))).__name__ == "PageIndexPipeline")+ oss = get_pipeline("pageindex-oss", kb_base_dir=str(tmp_path))+ assert type(oss).__name__ == "PageIndexPipeline"+ assert oss.provider == "pageindex-oss"assert (type(get_pipeline("llamaindex", kb_base_dir=str(tmp_path))).__name__ == "LlamaIndexPipeline")@@ -210,3 +220,99 @@ def test_ragservice_resolves_provider_from_metadata(tmp_path) -> None:# Explicit override wins over metadata.svc_override = RAGService(kb_base_dir=str(tmp_path), provider="llamaindex")assert svc_override._resolve_provider("kbx") == "llamaindex"+++def test_ragservice_guard_prevents_pageindex_pipeline(tmp_path, monkeypatch) -> None:+ from deeptutor.services.rag.service import RAGService++ service = RAGService(kb_base_dir=str(tmp_path), provider="pageindex-oss")+ monkeypatch.setattr(+ service,+ "_get_pipeline",+ lambda *_args, **_kwargs: pytest.fail("PageIndex reached a traditional RAG pipeline"),+ )++ result = asyncio.run(service.search(query="ground this", kb_name="page-kb"))++ assert result["error_type"] == "reasoning_as_retrieval_required"+++def test_cloud_sdk_client_is_reused_until_api_key_changes(monkeypatch) -> None:+ created: list[str] = []++ class _CloudClient:+ def __init__(self, api_key: str) -> None:+ created.append(api_key)++ monkeypatch.setattr(client_mod, "_sdk_types", lambda: (_CloudClient, object))+ client_mod._cloud_sdk_client.cache_clear()+ try:+ first = PageIndexClient.cloud(PageIndexConfig("key-a")).sdk_client+ second = PageIndexClient.cloud(PageIndexConfig("key-a")).sdk_client+ rotated = PageIndexClient.cloud(PageIndexConfig("key-b")).sdk_client+ finally:+ client_mod._cloud_sdk_client.cache_clear()++ assert first is second+ assert rotated is not first+ assert created == ["key-a", "key-b"]+++def test_submit_document_uses_sdk_wait() -> None:+ calls: list[tuple[str, str | None, bool]] = []++ class _SDKClient:+ def submit_document(self, path: str, *, mode: str | None, wait: bool):+ calls.append((path, mode, wait))+ return {"doc_id": "doc-1"}++ doc_id = asyncio.run(PageIndexClient(_SDKClient()).submit_document("a.pdf", mode="flash"))++ assert doc_id == "doc-1"+ assert calls == [("a.pdf", "flash", True)]+++def test_pageindex_ready_omits_embedding_identity(tmp_path, monkeypatch) -> None:+ import deeptutor.knowledge.manager as manager_module+ from deeptutor.knowledge.manager import KnowledgeBaseManager+ from deeptutor.services.rag import embedding_signature as signature_module++ pdf = tmp_path / "manual.pdf"+ pdf.write_text("x")+ asyncio.run(+ PageIndexPipeline(+ kb_base_dir=str(tmp_path),+ client=FakeClient(),+ provider="pageindex-oss",+ ).initialize("page-kb", [str(pdf)])+ )+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ manager.config.setdefault("knowledge_bases", {})["page-kb"] = {+ "path": "page-kb",+ "rag_provider": "pageindex-oss",+ "embedding_model": "stale-model",+ "embedding_dim": 123,+ "embedding_signature": "stale-signature",+ "embedding_mismatch": True,+ }+ manager._save_config()+ monkeypatch.setattr(manager_module, "_get_embedding_fingerprint", lambda: ("active", 456))+ monkeypatch.setattr(+ signature_module,+ "signature_from_embedding_config",+ lambda: type("Signature", (), {"hash": lambda self: "active-signature"})(),+ )++ manager.update_kb_status("page-kb", "ready")++ entry = manager._load_config()["knowledge_bases"]["page-kb"]+ assert (+ not {+ "embedding_model",+ "embedding_dim",+ "embedding_signature",+ "embedding_mismatch",+ }+ & entry.keys()+ )+ assert manager.get_info("page-kb")["statistics"]["active_signature"] is Nonediff --git a/tests/services/rag/test_pageindex_tools.py b/tests/services/rag/test_pageindex_tools.pynew file mode 100644index 000000000..aae62cb5f--- /dev/null+++ b/tests/services/rag/test_pageindex_tools.py@@ -0,0 +1,165 @@+from __future__ import annotations++import asyncio+import json+from types import SimpleNamespace++import pytest++from deeptutor.services.rag.pipelines.pageindex import tools as tools_mod+from deeptutor.services.rag.pipelines.pageindex import validate_pageindex_oss_selection+from deeptutor.services.rag.pipelines.pageindex.storage import CLOUD_PROVIDER, OSS_PROVIDER+from deeptutor.services.rag.pipelines.pageindex.tools import (+ PageIndexSDKTool,+ pageindex_sources_from_text,+)+++class _SDKTool:+ name = "get_page_content"+ description = "Read pages"+ params_json_schema = {+ "type": "object",+ "properties": {"doc_name": {"type": "string"}, "pages": {"type": "string"}},+ "required": ["doc_name", "pages"],+ }++ async def on_invoke_tool(self, _context, _args_json: str) -> str:+ return json.dumps(+ {+ "success": True,+ "doc_name": "manual.pdf",+ "content": [{"page": 3, "text": "grounded"}],+ }+ )+++def test_page_content_emits_real_structured_sources() -> None:+ tool = PageIndexSDKTool(+ _SDKTool(),+ provider=OSS_PROVIDER,+ kb_name="manuals",+ doc_ids={"manual.pdf": "pi-1"},+ )++ result = asyncio.run(tool.execute(doc_name="manual.pdf", pages="3"))++ assert tool.name == "pageindex_oss_get_page_content"+ assert result.sources == [+ {+ "type": "pageindex",+ "provider": "pageindex-oss",+ "kb_name": "manuals",+ "document_name": "manual.pdf",+ "doc_id": "pi-1",+ "source": "manual.pdf",+ "page": 3,+ }+ ]+ assert result.metadata["sources"] == result.sources+++def test_cloud_sdk_tool_uses_cloud_identity_and_sources() -> None:+ tool = PageIndexSDKTool(+ _SDKTool(),+ provider=CLOUD_PROVIDER,+ kb_name="hosted",+ doc_ids={"manual.pdf": "cloud-1"},+ )++ result = asyncio.run(tool.execute(doc_name="manual.pdf", pages="3"))++ assert tool.name == "pageindex_cloud_get_page_content"+ assert tool.provider_kind == "pageindex"+ assert tool.provider_id == CLOUD_PROVIDER+ assert result.sources[0]["provider"] == CLOUD_PROVIDER+ assert result.sources[0]["doc_id"] == "cloud-1"+++class _SDKClient:+ def __init__(self) -> None:+ self.tool_calls: list[dict] = []+ self.instruction_calls: list[object] = []++ def as_openai_tools(self, **kwargs):+ self.tool_calls.append(kwargs)+ return [_SDKTool()]++ def agent_instructions(self, doc_id=None):+ self.instruction_calls.append(doc_id)+ return "SDK instructions"++[email protected]("provider", [CLOUD_PROVIDER, OSS_PROVIDER])+def test_bundle_uses_unscoped_sdk_instructions(monkeypatch, provider: str) -> None:+ sdk_client = _SDKClient()++ class _Pipeline:+ def __init__(self, **_kwargs) -> None:+ pass++ def document_map(self, _kb_name: str) -> dict[str, str]:+ return {"manual.pdf": "cloud-1"}++ def sdk_client_for_read(self, _kb_name: str):+ return sdk_client++ monkeypatch.setattr(tools_mod, "PageIndexPipeline", _Pipeline)++ bundle = asyncio.run(tools_mod.build_sdk_tool_bundle("hosted", "/kb", provider=provider))++ assert sdk_client.tool_calls == [{"include_management": False}]+ assert sdk_client.instruction_calls == [None]+ assert bundle.provider == provider+ assert bundle.instructions == "SDK instructions"+ assert [tool.name for tool in bundle.tools] == [+ f"{'pageindex_oss' if provider == OSS_PROVIDER else 'pageindex_cloud'}_get_page_content"+ ]+++def test_structure_or_failure_does_not_invent_page_sources() -> None:+ assert (+ pageindex_sources_from_text(+ json.dumps({"success": True, "doc_name": "manual.pdf", "structure": []}),+ provider="pageindex-oss",+ )+ == []+ )+ assert (+ pageindex_sources_from_text(+ json.dumps(+ {+ "success": False,+ "doc_name": "manual.pdf",+ "content": [{"page": 9, "text": "not real"}],+ }+ ),+ provider="pageindex-oss",+ )+ == []+ )+++def _patch_selection(monkeypatch, providers: dict[str, str]) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb",+ lambda name, **_kwargs: SimpleNamespace(base_dir="/kb", name=name),+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.provider_binding.resolve_bound_provider",+ lambda _base, name: providers[name],+ )+++def test_rejects_two_oss_kbs(monkeypatch) -> None:+ _patch_selection(monkeypatch, {"one": "pageindex-oss", "two": "pageindex-oss"})+ with pytest.raises(ValueError, match="at most one"):+ validate_pageindex_oss_selection(["one", "two"])+++def test_cloud_and_oss_can_coexist(monkeypatch) -> None:+ _patch_selection(+ monkeypatch,+ {"cloud": "pageindex", "oss": "pageindex-oss", "vectors": "llamaindex"},+ )+ validate_pageindex_oss_selection(["cloud", "oss", "vectors"])diff --git a/tests/test_packaging_metadata.py b/tests/test_packaging_metadata.pyindex 19b9a3708..a57b7072f 100644--- a/tests/test_packaging_metadata.py+++ b/tests/test_packaging_metadata.py@@ -35,11 +35,9 @@ def test_typer_dependency_does_not_request_removed_all_extra(metadata_path: Pathdef test_mcp_client_is_a_core_dependency(metadata_path: Path) -> None:"""`mcp` must install by default, not only via an extra (issue #792).- Both distributions ship ``deeptutor.services.mcp``, and the connection- manager overlays the built-in PageIndex MCP server onto the config whenever- a PageIndex API key is set. That happens on a plain install, so an- extra-gated ``mcp`` leaves the connection task dying with- ``ModuleNotFoundError`` on every turn.+ Both distributions ship the configurable MCP tool surface. An extra-gated+ client would leave ordinary configured servers failing with+ ``ModuleNotFoundError`` on a plain install."""with metadata_path.open("rb") as file:dependencies = tomllib.load(file)["project"]["dependencies"]@@ -67,3 +65,18 @@ def test_requirements_mirror_the_core_mcp_client() -> None:# ...and partners.txt inherits it transitively rather than redeclaring it.assert "-r server.txt" in partners_textassert "mcp>=" not in partners_text+++def test_pageindex_sdk_range_matches_every_install_surface() -> None:+ expected = "pageindex>=0.2.10,<0.3.0"+ with (REPOSITORY_ROOT / "pyproject.toml").open("rb") as file:+ root = tomllib.load(file)["project"]+ with (REPOSITORY_ROOT / "packaging" / "deeptutor-cli" / "pyproject.toml").open("rb") as file:+ cli_package = tomllib.load(file)["project"]++ assert root["dependencies"].count(expected) == 1+ assert root["optional-dependencies"]["cli"].count(expected) == 1+ assert cli_package["dependencies"].count(expected) == 1+ assert (REPOSITORY_ROOT / "requirements" / "cli.txt").read_text(+ encoding="utf-8"+ ).splitlines().count(expected) == 1diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.pyindex 5da409a04..dc0557e63 100644--- a/tests/tools/test_rag_tool.py+++ b/tests/tools/test_rag_tool.py@@ -44,6 +44,7 @@ class TestPipelineFactory:assert {p["id"] for p in pipelines} == {DEFAULT_PROVIDER,"pageindex",+ "pageindex-oss","graphrag","lightrag","lightrag-server",@@ -80,6 +81,7 @@ class TestRAGServiceClassHelpers:assert {p["id"] for p in providers} == {DEFAULT_PROVIDER,"pageindex",+ "pageindex-oss","graphrag","lightrag","lightrag-server",diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsxindex 41b7bbcf2..ff4711794 100644--- a/web/app/(workspace)/book/components/BookChatPanel.tsx+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx@@ -145,6 +145,10 @@ export default function BookChatPanel({useEffect(() => {let cancelled = false;+ // The first turn creates its session server-side. Persisting that same id+ // back onto the book rerenders this component, but it is not a session+ // switch: resetting here would disconnect the turn before its reply arrives.+ if (initialSessionId && initialSessionId === sessionIdRef.current) return;retryTimersRef.current.forEach((timer) => clearTimeout(timer));retryTimersRef.current.clear();clientRef.current?.disconnect();diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 4de69c2f3..adedcd0b8 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -311,6 +311,10 @@ interface KnowledgeBase {type?: string;/** Backend of a connected subagent: "claude_code" | "codex" | "partner". */agent_kind?: string;+ rag_provider?: string;+ };+ statistics?: {+ rag_provider?: string;};}@@ -1799,13 +1803,23 @@ export default function ChatPage() {const handleToggleKB = useCallback((name: string) => {const current = state.knowledgeBases;+ const providerOf = (kbName: string) => {+ const kb = knowledgeBases.find((item) => item.name === kbName);+ return kb?.metadata?.rag_provider || kb?.statistics?.rag_provider || "";+ };+ const selectingOss = providerOf(name) === "pageindex-oss";setKBs(current.includes(name)? current.filter((kb) => kb !== name)- : [...current, name],+ : [+ ...(selectingOss+ ? current.filter((kb) => providerOf(kb) !== "pageindex-oss")+ : current),+ name,+ ],);},- [setKBs, state.knowledgeBases],+ [knowledgeBases, setKBs, state.knowledgeBases],);// Real knowledge bases and connected subagents render as separate composerdiff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex c08157036..1bdff05c0 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";import {AlertTriangle,Check,+ ExternalLink,FolderOpen,FolderSearch,Link2,@@ -27,24 +28,13 @@ import {IMA_PROVIDER,linkSourceEnabled,} from "@/lib/ima-connection";-import { validateFiles } from "@/lib/knowledge-helpers";+import {+ uploadPolicyForProvider,+ validateFiles,+} from "@/lib/knowledge-helpers";import FileDropZone from "./FileDropZone";import ImaConnectionFields from "./ImaConnectionFields";-// Mirrors SUPPORTED_EXTENSIONS in the backend pageindex pipeline (PageIndex POST /doc/).-const PAGEINDEX_FORMATS = [- ".pdf",- ".md",- ".markdown",- ".txt",- ".docx",- ".doc",- ".pptx",- ".ppt",- ".xlsx",- ".xls",- ".csv",-];const OBSIDIAN_SOURCE = "obsidian";const LIGHTRAG_SERVER_PROVIDER = "lightrag-server";const EXAMPLE_INDEX_PATH = "/Users/you/knowledge_bases/my-kb";@@ -62,6 +52,7 @@ interface CreateKbModalProps {name: string;provider: string;files: File[];+ pageindexMode?: "flash" | "standard";}) => Promise<void>;/** Link a pre-built engine index folder in place (no copy, no re-index). */onConnectLinkedFolder: (params: {@@ -115,6 +106,9 @@ export default function CreateKbModal({const [name, setName] = useState("");const [provider, setProvider] = useState("llamaindex");const [files, setFiles] = useState<File[]>([]);+ const [pageIndexMode, setPageIndexMode] = useState<+ "" | "flash" | "standard"+ >("");// Link mode: the source is either an engine id or the Obsidian sentinel.const [linkSource, setLinkSource] = useState(OBSIDIAN_SOURCE);const [folderPath, setFolderPath] = useState("");@@ -167,6 +161,7 @@ export default function CreateKbModal({setMode(initialMode);setName("");setFiles([]);+ setPageIndexMode("");setError(null);const initialProvider = createProviders(providers).find((item) => item.id === initialSource,@@ -200,19 +195,14 @@ export default function CreateKbModal({const providerNeedsKey =!!activeProvider?.requires_api_key && activeProvider?.configured === false;const providerUnavailable = activeProvider?.configured === false;- const isPageIndex = provider === "pageindex";+ const isPageIndexCloud = provider === "pageindex";+ const isPageIndexOSS = provider === "pageindex-oss";const isLightRagServer = provider === LIGHTRAG_SERVER_PROVIDER;const serverModeOptions = activeProvider?.modes ?? [];const effectiveServerMode =serverMode || activeProvider?.default_mode || serverModeOptions[0] || "";- const policyForProvider: KnowledgeUploadPolicy = isPageIndex- ? {- ...uploadPolicy,- extensions: PAGEINDEX_FORMATS,- accept: PAGEINDEX_FORMATS.join(","),- }- : uploadPolicy;+ const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider);const selection = validateFiles(files, policyForProvider, t);@@ -291,6 +281,8 @@ export default function CreateKbModal({name: trimmed,provider,files: selection.validFiles,+ pageindexMode:+ isPageIndexOSS && pageIndexMode ? pageIndexMode : undefined,});}} else if (linkIsIma) {@@ -397,7 +389,10 @@ export default function CreateKbModal({providerUnavailable={providerUnavailable}providerNeedsKey={providerNeedsKey}onConfigureProvider={onConfigureProvider}- isPageIndex={isPageIndex}+ isPageIndexCloud={isPageIndexCloud}+ isPageIndexOSS={isPageIndexOSS}+ pageIndexMode={pageIndexMode}+ setPageIndexMode={setPageIndexMode}files={files}setFiles={setFiles}policyForProvider={policyForProvider}@@ -531,7 +526,10 @@ function NewModeFields({providerUnavailable,providerNeedsKey,onConfigureProvider,- isPageIndex,+ isPageIndexCloud,+ isPageIndexOSS,+ pageIndexMode,+ setPageIndexMode,files,setFiles,policyForProvider,@@ -545,7 +543,10 @@ function NewModeFields({providerUnavailable: boolean;providerNeedsKey: boolean;onConfigureProvider?: () => void;- isPageIndex: boolean;+ isPageIndexCloud: boolean;+ isPageIndexOSS: boolean;+ pageIndexMode: "" | "flash" | "standard";+ setPageIndexMode: (mode: "" | "flash" | "standard") => void;files: File[];setFiles: (files: File[]) => void;policyForProvider: KnowledgeUploadPolicy;@@ -553,6 +554,8 @@ function NewModeFields({connectionForm?: ReactNode;t: TFn;}) {+ const readinessReason = providers.find((item) => item.id === provider)+ ?.readiness_reason;return (<><div>@@ -565,17 +568,17 @@ function NewModeFields({const needsKey = !!p.requires_api_key && p.configured === false;const unavailable = p.configured === false && !p.requires_api_key;return (- <button- key={p.id}- type="button"- disabled={submitting}- onClick={() => setProvider(p.id)}- className={`group flex flex-col gap-1 rounded-2xl border p-3 text-left transition-colors disabled:opacity-50 ${- selected- ? "border-[var(--primary)] bg-[var(--primary)]/5"- : "border-[var(--border)] hover:border-[var(--ring)]"- }`}- >+ <div key={p.id} className="flex flex-col gap-1">+ <button+ type="button"+ disabled={submitting}+ onClick={() => setProvider(p.id)}+ className={`group flex w-full flex-1 flex-col gap-1 rounded-2xl border p-3 text-left transition-colors disabled:opacity-50 ${+ selected+ ? "border-[var(--primary)] bg-[var(--primary)]/5"+ : "border-[var(--border)] hover:border-[var(--ring)]"+ }`}+ ><div className="flex items-center justify-between gap-2"><span className="text-[13px] font-medium text-[var(--foreground)]">{p.name}@@ -595,7 +598,19 @@ function NewModeFields({<span className="text-[11.5px] leading-snug text-[var(--muted-foreground)]">{p.description}</span>- </button>+ </button>+ {p.id === "pageindex" && (+ <a+ href="https://dash.pageindex.ai/api-keys"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 px-1 text-[10.5px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {t("PageIndex API plans")}+ <ExternalLink className="h-3 w-3" />+ </a>+ )}+ </div>);})}</div>@@ -607,8 +622,9 @@ function NewModeFields({? t("This engine needs an API key. Configure it before creating.",)- : t(- "This engine isn't installed on the server. Install it before creating.",+ : t(+ readinessReason ||+ "This engine isn't ready on the server. Check its requirements before creating.",)}</span>{providerNeedsKey && onConfigureProvider && (@@ -624,13 +640,47 @@ function NewModeFields({)}</div>+ {isPageIndexOSS && (+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Index mode")}+ <span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">+ · {t("optional")}+ </span>+ </label>+ <select+ value={pageIndexMode}+ onChange={(event) =>+ setPageIndexMode(+ event.target.value as "" | "flash" | "standard",+ )+ }+ disabled={submitting}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ >+ <option value="">+ {t("Default — Flash, summaries and full optimization")}+ </option>+ <option value="flash">{t("Flash")}</option>+ <option value="standard">{t("Standard")}</option>+ </select>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Uses the globally active LLM credential. Leaving this unset delegates to the PageIndex SDK default.",+ )}+ </p>+ </div>+ )}+{connectionForm ?? (<div><label className="mb-2 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">{t("Initial documents")}- {isPageIndex && (+ {(isPageIndexCloud || isPageIndexOSS) && (<span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">- · {t("PDF, Office, text and Markdown")}+ · {isPageIndexOSS+ ? t("PDF only — use PageIndex Cloud for Office, Markdown or CSV")+ : t("PDF, Office, text and Markdown")}</span>)}</label>diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsxindex a325ffc7e..42656690f 100644--- a/web/components/knowledge/EngineDetail.tsx+++ b/web/components/knowledge/EngineDetail.tsx@@ -32,14 +32,12 @@ import {getLightRagConfig,getImaConfig,getLlamaIndexConfig,- getPageIndexConfig,setEngineActiveModel,testGraphRagModelCompatibility,updateGraphRagConfig,updateImaConfig,updateLightRagConfig,updateLlamaIndexConfig,- updatePageIndexConfig,type EnginePreflight,type GraphRagModelCompatibility,type GraphRagConfig,@@ -47,7 +45,6 @@ import {type LightRagConfig,type LlamaIndexConfig,type ModelOptionsByKind,- type PageIndexConfig,type RagProviderSummary,} from "@/lib/knowledge-api";import { canApplyGraphRagModelCandidate } from "@/lib/graphrag-model-compatibility";@@ -59,6 +56,7 @@ import {type KnowledgeBase,type ProviderConnectionStatus,} from "@/lib/knowledge-helpers";+import { PageIndexConfigForm } from "./PageIndexSettingsModal";interface EngineDetailProps {provider: RagProviderSummary;@@ -74,6 +72,7 @@ interface EngineDetailProps {const ENGINE_ICONS: Record<string, LucideIcon> = {llamaindex: Boxes,pageindex: Cloud,+ "pageindex-oss": Database,graphrag: Network,lightrag: Workflow,"lightrag-server": Server,@@ -118,6 +117,7 @@ const MODE_DESCRIPTIONS: Record<string, string> = {const ENGINE_MODEL_KINDS: Record<string, ("llm" | "embedding")[]> = {llamaindex: ["embedding"],pageindex: [],+ "pageindex-oss": ["llm"],graphrag: ["llm", "embedding"],lightrag: ["llm", "embedding"],"lightrag-server": [],@@ -144,6 +144,8 @@ const ENGINE_PREREQUISITES: Record<string, string> = {"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.",pageindex:"Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.",+ "pageindex-oss":+ "Local chunkless and vectorless indexing. Accepts PDF files and uses the globally active chat model credential for indexing; the index remains readable after model changes.",graphrag:"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",lightrag:@@ -525,137 +527,6 @@ function LlamaIndexForm({);}-/* -------------------------- PageIndex config form ------------------------- */--const PAGEINDEX_DEFAULT_BASE_URL = "https://api.pageindex.ai";--function PageIndexForm({- onChanged,- onError,-}: {- onChanged: () => void;- onError: (message: string) => void;-}) {- const { t } = useTranslation();- const [config, setConfig] = useState<PageIndexConfig | null>(null);- const [apiKey, setApiKey] = useState("");- const [baseUrl, setBaseUrl] = useState("");- const [saving, setSaving] = useState(false);-- useEffect(() => {- let cancelled = false;- getPageIndexConfig({ force: true })- .then((cfg) => {- if (cancelled) return;- setConfig(cfg);- setBaseUrl(cfg.api_base_url || "");- })- .catch((err) =>- onError(err instanceof Error ? err.message : String(err)),- );- return () => {- cancelled = true;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const persist = async (payload: {- api_key?: string;- api_base_url?: string;- }) => {- setSaving(true);- try {- const next = await updatePageIndexConfig(payload);- setConfig(next);- setApiKey("");- onChanged();- } catch (err) {- onError(err instanceof Error ? err.message : String(err));- } finally {- setSaving(false);- }- };-- const keySet = config?.api_key_set ?? false;-- return (- <div className="space-y-4 rounded-2xl border border-[var(--border)] p-4">- <p className="text-[12px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.",- )}- </p>-- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("API key")}- </label>- <input- type="password"- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- disabled={saving}- placeholder={- keySet- ? t("•••••••• (configured — leave blank to keep)")- : t("Enter your PageIndex API key")- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- {keySet && (- <button- type="button"- onClick={() => void persist({ api_key: "" })}- disabled={saving}- className="mt-1.5 text-[11px] font-medium text-red-600 transition-colors hover:text-red-700 disabled:opacity-40 dark:text-red-400"- >- {t("Remove stored key")}- </button>- )}- </div>-- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("API base URL")}- </label>- <input- value={baseUrl}- onChange={(e) => setBaseUrl(e.target.value)}- disabled={saving}- placeholder={PAGEINDEX_DEFAULT_BASE_URL}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- </div>-- <div className="flex items-center justify-between gap-2">- <a- href="https://dash.pageindex.ai/api-keys"- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- >- {t("Get an API key")}- <ExternalLink className="h-3 w-3" />- </a>- <button- type="button"- onClick={() =>- void persist({- api_base_url: baseUrl.trim() || undefined,- ...(apiKey.trim() ? { api_key: apiKey.trim() } : {}),- })- }- disabled={saving}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"- >- {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}- {t("Save changes")}- </button>- </div>- </div>- );-}-/* ------------------------- Tencent IMA credentials ------------------------ */function ImaForm({@@ -1535,7 +1406,7 @@ export default function EngineDetail({{/* PageIndex credentials */}{provider.id === "pageindex" && (<Section label={t("Credentials")} icon={KeyRound}>- <PageIndexForm onChanged={onChanged} onError={onError} />+ <PageIndexConfigForm onChanged={onChanged} onError={onError} /></Section>)}diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsxindex 5c469521a..024d09848 100644--- a/web/components/knowledge/KbDocumentsSection.tsx+++ b/web/components/knowledge/KbDocumentsSection.tsx@@ -7,8 +7,10 @@ import type { KnowledgeUploadPolicy } from "@/lib/knowledge-api";import {kbIsUploadable,kbNeedsReindex,+ providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,+ uploadPolicyForProvider,validateFiles,type KnowledgeBase,} from "@/lib/knowledge-helpers";@@ -53,6 +55,9 @@ export default function KbDocumentsSection({const needsReindex = kbNeedsReindex(kb);const status = resolveKbStatus(kb);const isError = status === "error";+ const provider =+ kb.statistics?.rag_provider || kb.metadata?.rag_provider || "llamaindex";+ const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider);const isUploadingHere = task?.kind === "upload" && task.executing;const isIndexingHere =@@ -78,7 +83,7 @@ export default function KbDocumentsSection({): null;- const selection = validateFiles(files, uploadPolicy, t);+ const selection = validateFiles(files, policyForProvider, t);const canRetry = Boolean(onRetry) && isError && !isIndexingHere;// Unsupported files are skipped (shown in the drop zone), not blocking, so a// picked folder with mixed content still uploads its supported members.@@ -132,7 +137,9 @@ export default function KbDocumentsSection({</div><p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">{t(- "Drop files here to add them to this knowledge base. New files are indexed against the active embedding model.",+ providerUsesEmbeddingMetadata(provider)+ ? "Drop files here to add them to this knowledge base. New files are indexed against the active embedding model."+ : "Drop files here",)}</p></div>@@ -171,7 +178,7 @@ export default function KbDocumentsSection({<FileDropZonefiles={files}onChange={setFiles}- uploadPolicy={uploadPolicy}+ uploadPolicy={policyForProvider}disabled={!canUpload || isUploadingHere}/>diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsxindex 0dd13545a..d94e7840a 100644--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@ -15,6 +15,7 @@ import {formatKnowledgeTimestamp,kbCanReindex,kbNeedsReindex,+ providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,type IndexVersion,@@ -37,8 +38,12 @@ export default function KbIndexVersionsSection({}: KbIndexVersionsSectionProps) {const { t } = useTranslation();const [submitting, setSubmitting] = useState(false);+ const provider = kb.statistics?.rag_provider || "llamaindex";+ const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);const versions = kb.statistics?.index_versions ?? [];- const activeSig = kb.statistics?.active_signature ?? null;+ const activeSig = pageIndexProvider+ ? null+ : (kb.statistics?.active_signature ?? null);const needsReindex = kbNeedsReindex(kb);const isError = resolveKbStatus(kb) === "error";const mismatch = Boolean(kb.metadata?.embedding_mismatch);@@ -73,7 +78,9 @@ export default function KbIndexVersionsSection({</div><p className="text-[11px] text-[var(--muted-foreground)]">{t(- "Each embedding configuration gets its own stored vector index.",+ pageIndexProvider+ ? "PageIndex versions are model-insensitive and preserve rebuild history."+ : "Each embedding configuration gets its own stored vector index.",)}</p></div>@@ -90,7 +97,9 @@ export default function KbIndexVersionsSection({"Retry indexing from the documents already stored in this knowledge base.",): t(- "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",+ pageIndexProvider+ ? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."+ : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",)}className={`inline-flex shrink-0 items-center gap-1.5 rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:opacity-50 ${@@ -117,7 +126,7 @@ export default function KbIndexVersionsSection({{isError && <KbIndexFailureBanner kb={kb} />}- {!isError && (needsReindex || mismatch) && (+ {!pageIndexProvider && !isError && (needsReindex || mismatch) && (<div className="rounded-lg border border-amber-200 bg-amber-50/80 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300">{t("The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",diff --git a/web/components/knowledge/KbSettingsSection.tsx b/web/components/knowledge/KbSettingsSection.tsxindex 362d1ee54..9a760f3ec 100644--- a/web/components/knowledge/KbSettingsSection.tsx+++ b/web/components/knowledge/KbSettingsSection.tsx@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import { Star, Trash2 } from "lucide-react";import {formatKnowledgeTimestamp,+ providerUsesEmbeddingMetadata,type KnowledgeBase,} from "@/lib/knowledge-helpers";@@ -21,6 +22,7 @@ export default function KbSettingsSection({const { t } = useTranslation();const meta = kb.metadata || {};const provider = kb.statistics?.rag_provider || "llamaindex";+ const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);const embeddingLabel = meta.embedding_model? typeof meta.embedding_dim === "number"? `${meta.embedding_model} · ${meta.embedding_dim}${t("d")}`@@ -44,7 +46,9 @@ export default function KbSettingsSection({<dl className="grid gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3 sm:grid-cols-2"><Field label={t("RAG provider")}>{provider}</Field>- <Field label={t("Embedding")}>{embeddingLabel}</Field>+ {!pageIndexProvider && (+ <Field label={t("Embedding")}>{embeddingLabel}</Field>+ )}<Field label={t("Created")}>{created || "—"}</Field><Field label={t("Updated")}>{updated || "—"}</Field><Field label={t("Last indexed")}>{lastIndexed || "—"}</Field>diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex dbff8e69e..bc75d9327 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -16,6 +16,7 @@ import {import type { KnowledgeUploadPolicy } from "@/lib/knowledge-api";import {formatKnowledgeTimestamp,+ providerUsesEmbeddingMetadata,resolveKbStatus,type KnowledgeBase,} from "@/lib/knowledge-helpers";@@ -105,6 +106,7 @@ export default function KnowledgeBaseDetail({const meta = kb.metadata || {};const provider = kb.statistics?.rag_provider || "llamaindex";+ const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);const embeddingLabel = meta.embedding_model? typeof meta.embedding_dim === "number"? `${meta.embedding_model} · ${meta.embedding_dim}${t("d")}`@@ -169,7 +171,8 @@ export default function KnowledgeBaseDetail({/></div><p className="mt-1 text-[12px] text-[var(--muted-foreground)]">- {provider} · {embeddingLabel} · {t("Updated")} {updatedLabel}+ {provider}+ {!pageIndexProvider ? ` · ${embeddingLabel}` : ""} · {t("Updated")} {updatedLabel}{lastIndexedLabel? ` · ${t("Last indexed")} ${lastIndexedLabel}`: ""}diff --git a/web/components/knowledge/PageIndexSettingsModal.tsx b/web/components/knowledge/PageIndexSettingsModal.tsxindex 56ff31090..1f09abba3 100644--- a/web/components/knowledge/PageIndexSettingsModal.tsx+++ b/web/components/knowledge/PageIndexSettingsModal.tsx@@ -10,8 +10,6 @@ import {type PageIndexConfig,} from "@/lib/knowledge-api";-const DEFAULT_BASE_URL = "https://api.pageindex.ai";-interface PageIndexSettingsModalProps {isOpen: boolean;onClose: () => void;@@ -19,34 +17,39 @@ interface PageIndexSettingsModalProps {onSaved?: () => void;}-export default function PageIndexSettingsModal({- isOpen,- onClose,- onSaved,-}: PageIndexSettingsModalProps) {+interface PageIndexConfigFormProps {+ onChanged?: () => void;+ onSubmit?: () => void;+ onCancel?: () => void;+ onError?: (message: string) => void;+ onSavingChange?: (saving: boolean) => void;+}++export function PageIndexConfigForm({+ onChanged,+ onSubmit,+ onCancel,+ onError,+ onSavingChange,+}: PageIndexConfigFormProps) {const { t } = useTranslation();const [config, setConfig] = useState<PageIndexConfig | null>(null);const [apiKey, setApiKey] = useState("");- const [baseUrl, setBaseUrl] = useState("");- const [loading, setLoading] = useState(false);+ const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);useEffect(() => {- if (!isOpen) return;let cancelled = false;- setLoading(true);- setError(null);- setApiKey("");getPageIndexConfig({ force: true })- .then((cfg) => {- if (cancelled) return;- setConfig(cfg);- setBaseUrl(cfg.api_base_url || "");+ .then((next) => {+ if (!cancelled) setConfig(next);}).catch((err) => {- if (!cancelled)- setError(err instanceof Error ? err.message : String(err));+ if (cancelled) return;+ const message = err instanceof Error ? err.message : String(err);+ setError(message);+ onError?.(message);}).finally(() => {if (!cancelled) setLoading(false);@@ -54,144 +57,155 @@ export default function PageIndexSettingsModal({return () => {cancelled = true;};- }, [isOpen]);+ // The form intentionally loads once when it is mounted.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);- const persist = async (payload: {- api_key?: string;- api_base_url?: string;- }) => {+ const persist = async (payload: { api_key?: string }) => {setSaving(true);+ onSavingChange?.(true);setError(null);try {const next = await updatePageIndexConfig(payload);setConfig(next);setApiKey("");- onSaved?.();- return next;+ onChanged?.();+ return true;} catch (err) {- setError(err instanceof Error ? err.message : String(err));- return null;+ const message = err instanceof Error ? err.message : String(err);+ setError(message);+ onError?.(message);+ return false;} finally {setSaving(false);+ onSavingChange?.(false);}};- const handleSave = async () => {- // Blank key keeps the stored one; a typed value replaces it.- const payload: { api_key?: string; api_base_url?: string } = {- api_base_url: baseUrl.trim() || undefined,- };- if (apiKey.trim()) payload.api_key = apiKey.trim();- const next = await persist(payload);- if (next) onClose();+ const save = async () => {+ const payload = apiKey.trim() ? { api_key: apiKey.trim() } : {};+ if (await persist(payload)) onSubmit?.();};const keySet = config?.api_key_set ?? false;+ const modal = Boolean(onCancel);return (- <Modal- isOpen={isOpen}- onClose={saving ? () => {} : onClose}- title={t("PageIndex settings")}- titleIcon={<KeyRound size={16} />}- width="md"- closeOnBackdrop={!saving}- closeOnEscape={!saving}- footer={- <div className="flex items-center justify-between gap-2">- <a- href="https://dash.pageindex.ai/api-keys"- target="_blank"- rel="noreferrer"- className="inline-flex items-center gap-1 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- >- {t("Get an API key")}- <ExternalLink className="h-3 w-3" />- </a>- <div className="flex items-center gap-2">+ <div+ className={+ modal+ ? "space-y-4 px-5 py-4"+ : "space-y-4 rounded-2xl border border-[var(--border)] p-4"+ }+ >+ <p className="text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.",+ )}+ </p>++ {loading ? (+ <div className="flex items-center justify-center py-6">+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : (+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("API key")}+ </label>+ <input+ type="password"+ value={apiKey}+ onChange={(event) => setApiKey(event.target.value)}+ disabled={saving}+ placeholder={+ keySet+ ? t("•••••••• (configured — leave blank to keep)")+ : t("Enter your PageIndex API key")+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ {keySet && (<buttontype="button"- onClick={onClose}+ onClick={() => void persist({ api_key: "" })}disabled={saving}- className="rounded-md px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"+ className="mt-1.5 text-[11px] font-medium text-red-600 transition-colors hover:text-red-700 disabled:opacity-40 dark:text-red-400">- {t("Cancel")}+ {t("Remove stored key")}</button>+ )}+ </div>+ )}++ {error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {error}+ </div>+ )}++ <div className="flex items-center justify-between gap-2">+ <a+ href="https://dash.pageindex.ai/api-keys"+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {t("Get an API key")}+ <ExternalLink className="h-3 w-3" />+ </a>+ <div className="flex items-center gap-2">+ {onCancel && (<buttontype="button"- onClick={() => void handleSave()}- disabled={saving || loading}- className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ onClick={onCancel}+ disabled={saving}+ className="rounded-md px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40">- {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}- {t("Save")}+ {t("Cancel")}</button>- </div>- </div>- }- >- <div className="space-y-4 px-5 py-4">- <p className="text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.",)}- </p>-- {loading ? (- <div className="flex items-center justify-center py-6">- <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />- </div>- ) : (- <>- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("API key")}- </label>- <input- type="password"- value={apiKey}- onChange={(event) => setApiKey(event.target.value)}- disabled={saving}- placeholder={- keySet- ? t("•••••••• (configured — leave blank to keep)")- : t("Enter your PageIndex API key")- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- {keySet && (- <button- type="button"- onClick={() => void persist({ api_key: "" })}- disabled={saving}- className="mt-1.5 text-[11px] font-medium text-red-600 transition-colors hover:text-red-700 disabled:opacity-40 dark:text-red-400"- >- {t("Remove stored key")}- </button>- )}- </div>+ <button+ type="button"+ onClick={() => void save()}+ disabled={saving || loading}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t(modal ? "Save" : "Save changes")}+ </button>+ </div>+ </div>+ </div>+ );+}- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {t("API base URL")}- </label>- <input- value={baseUrl}- onChange={(event) => setBaseUrl(event.target.value)}- disabled={saving}- placeholder={DEFAULT_BASE_URL}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- </div>- </>- )}+export default function PageIndexSettingsModal({+ isOpen,+ onClose,+ onSaved,+}: PageIndexSettingsModalProps) {+ const { t } = useTranslation();+ const [saving, setSaving] = useState(false);- {error && (- <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">- {error}- </div>- )}- </div>+ return (+ <Modal+ isOpen={isOpen}+ onClose={saving ? () => {} : onClose}+ title={t("PageIndex settings")}+ titleIcon={<KeyRound size={16} />}+ width="md"+ closeOnBackdrop={!saving}+ closeOnEscape={!saving}+ >+ {isOpen && (+ <PageIndexConfigForm+ onChanged={onSaved}+ onSubmit={onClose}+ onCancel={onClose}+ onSavingChange={setSaving}+ />+ )}</Modal>);}diff --git a/web/hooks/useKnowledgeProgress.ts b/web/hooks/useKnowledgeProgress.tsindex 23ea5dfc1..0979758dd 100644--- a/web/hooks/useKnowledgeProgress.ts+++ b/web/hooks/useKnowledgeProgress.ts@@ -17,6 +17,36 @@ export interface TaskState {retryable?: boolean;}+export function appendTaskLog(logs: string[], message?: string): string[] {+ const line = String(message || "").trim();+ if (!line || logs.at(-1) === line) return logs;+ return [...logs, line];+}++export function taskStateAfterProgress(+ current: TaskState,+ expectedTaskId: string | undefined,+ progress: ProgressInfo,+): TaskState {+ const taskId = expectedTaskId || progress.task_id;+ if (taskId && current.taskId !== taskId) return current;+ const logs = appendTaskLog(current.logs, progress.message);+ if (progress.stage === "completed") {+ return { ...current, logs, executing: false, error: null };+ }+ if (progress.stage === "error") {+ return {+ ...current,+ logs,+ executing: false,+ error: progress.error || progress.message || "Task failed",+ errorCode: progress.error_code,+ retryable: progress.retryable,+ };+ }+ return logs === current.logs ? current : { ...current, logs };+}+interface UseKnowledgeProgressOptions {onComplete?: (kbName: string) => void;/**@@ -110,8 +140,36 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {}setProgress(kbName, progress);const stage = progress.stage;+ const terminal = stage === "completed" || stage === "error";+ setTasksByKb((prev) => {+ const current = prev[kbName];+ if (!current) return prev;+ const finalState = taskStateAfterProgress(+ current,+ expectedTaskId,+ progress,+ );+ if (finalState === current) return prev;+ const startedAt =+ startedAtRef.current[`${kbName}:${current.taskId}`] ?? Date.now();+ if (terminal && current.executing) {+ delete startedAtRef.current[`${kbName}:${current.taskId}`];+ onTaskSettledRef.current?.(kbName, {+ ...finalState,+ status: finalState.error ? "error" : "completed",+ startedAt,+ completedAt: Date.now(),+ } as TaskState & {+ startedAt: number;+ completedAt: number;+ status: "error" | "completed";+ });+ }+ return { ...prev, [kbName]: finalState };+ });if (stage === "completed" || stage === "error") {closeSocket(kbName);+ closeSource(kbName);onCompleteRef.current?.(kbName);}} catch {@@ -124,7 +182,7 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {delete socketsRef.current[kbName];};},- [closeSocket, setProgress],+ [closeSocket, closeSource, setProgress],);const openTaskStream = useCallback(@@ -195,6 +253,7 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {setTasksByKb((prev) => {const current = prev[kbName];if (!current || current.taskId !== taskId) return prev;+ if (!current.executing) return prev;const finalState = { ...current, executing: false };const startedAt =startedAtRef.current[`${kbName}:${taskId}`] ?? Date.now();@@ -236,6 +295,7 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {setTasksByKb((prev) => {const current = prev[kbName];if (!current || current.taskId !== taskId) return prev;+ if (!current.executing) return prev;const finalState = {...current,executing: false,@@ -262,20 +322,8 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {source.onerror = () => {if (settled) return;- setTasksByKb((prev) => {- const current = prev[kbName];- if (!current || current.taskId !== taskId) return prev;- if (!current.executing) return prev;- return {- ...prev,- [kbName]: {- ...current,- executing: false,- error: current.error || "Process log stream disconnected.",- },- };- });- closeSource(kbName);+ // EventSource reconnects automatically. Progress WebSocket remains the+ // authoritative terminal-state fallback while SSE reconnects.};},[closeSource, setProgress],diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex e81087f02..90ba9f803 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -26,6 +26,8 @@ export interface RagProviderSummary {description: string;/** Whether the engine is ready to use (e.g. its API key is set). */configured?: boolean;+ /** Actionable reason when configured is false. */+ readiness_reason?: string;/** Whether the engine needs an API key configured before use. */requires_api_key?: boolean;/** Retrieval modes this engine supports (empty for mode-less engines). */@@ -37,7 +39,6 @@ export interface RagProviderSummary {}export interface PageIndexConfig {- api_base_url: string;api_key_set: boolean;configured: boolean;}@@ -269,7 +270,6 @@ export async function getPageIndexConfig(options?: {export async function updatePageIndexConfig(payload: {/** Omit to keep the stored key, "" to clear it, any value to replace it. */api_key?: string;- api_base_url?: string;}): Promise<PageIndexConfig> {const res = await apiFetch(apiUrl(PAGEINDEX_CONFIG_PATH), {method: "PUT",@@ -615,10 +615,14 @@ export async function createKnowledgeBase(payload: {name: string;provider: string;files: File[];+ pageindexMode?: "flash" | "standard";}): Promise<KnowledgeTaskResponse> {const form = new FormData();form.append("name", payload.name);form.append("rag_provider", payload.provider);+ if (payload.pageindexMode) {+ form.append("pageindex_mode", payload.pageindexMode);+ }appendFilesWithPaths(form, payload.files);const res = await apiFetch(apiUrl("/api/v1/knowledge/create"), {diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex f998af2d8..7dc2f99ba 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -12,6 +12,33 @@ export const DEFAULT_UPLOAD_POLICY: KnowledgeUploadPolicy = {max_file_size_bytes: 200 * 1024 * 1024,};+const PAGEINDEX_UPLOAD_EXTENSIONS: Record<string, string[]> = {+ pageindex: [+ ".pdf",+ ".md",+ ".markdown",+ ".txt",+ ".docx",+ ".doc",+ ".pptx",+ ".ppt",+ ".xlsx",+ ".xls",+ ".csv",+ ],+ "pageindex-oss": [".pdf"],+};++export function uploadPolicyForProvider(+ policy: KnowledgeUploadPolicy,+ provider?: string,+): KnowledgeUploadPolicy {+ const extensions = PAGEINDEX_UPLOAD_EXTENSIONS[provider || ""];+ return extensions+ ? { ...policy, extensions, accept: extensions.join(",") }+ : policy;+}+export interface ProgressInfo {task_id?: string;stage?: string;@@ -95,6 +122,9 @@ export interface KnowledgeBase {export type ProviderConnectionStatus = "ready" | "needs_key" | "unavailable";+export const providerUsesEmbeddingMetadata = (provider?: string): boolean =>+ provider !== "pageindex" && provider !== "pageindex-oss";+export const providerConnectionStatus = (provider: {id: string;configured?: boolean;diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex a2746a29f..dd1ee0499 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1295,7 +1295,9 @@"Delete knowledge base": "Delete knowledge base","Index versions": "Index versions","Each embedding configuration gets its own stored vector index.": "Each embedding configuration gets its own stored vector index.",+ "PageIndex versions are model-insensitive and preserve rebuild history.": "PageIndex versions are model-insensitive and preserve rebuild history.","Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.": "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",+ "Rebuild this PageIndex knowledge base. Existing index versions are preserved.": "Rebuild this PageIndex knowledge base. Existing index versions are preserved.","Retry indexing from the documents already stored in this knowledge base.": "Retry indexing from the documents already stored in this knowledge base.","Re-index": "Re-index","Re-indexing…": "Re-indexing…",@@ -3076,6 +3078,13 @@"This book was written without reading your sources.": "This book was written without reading your sources.","Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.","Source sweep failed": "Source sweep failed",+ "Index mode": "Index mode",+ "Default — Flash, summaries and full optimization": "Default — Flash, summaries and full optimization",+ "Uses the globally active LLM credential. Leaving this unset delegates to the PageIndex SDK default.": "Uses the globally active LLM credential. Leaving this unset delegates to the PageIndex SDK default.",+ "PDF only — use PageIndex Cloud for Office, Markdown or CSV": "PDF only — use PageIndex Cloud for Office, Markdown or CSV",+ "This engine isn't ready on the server. Check its requirements before creating.": "This engine isn't ready on the server. Check its requirements before creating.",+ "Local chunkless and vectorless indexing. Accepts PDF files and uses the globally active chat model credential for indexing; the index remains readable after model changes.": "Local chunkless and vectorless indexing. Accepts PDF files and uses the globally active chat model credential for indexing; the index remains readable after model changes.",+ "PageIndex API plans": "PageIndex API plans","A record needs a title.": "A record needs a title.","Body": "Body","Copy to notebook": "Copy to notebook",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 6e9ce30ed..e6d1a8665 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1415,7 +1415,9 @@"Delete knowledge base": "删除知识库","Index versions": "索引版本","Each embedding configuration gets its own stored vector index.": "每个 embedding 配置都对应一个独立存储的向量索引。",+ "PageIndex versions are model-insensitive and preserve rebuild history.": "PageIndex 索引版本与模型无关,并保留每次重建记录。","Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.": "点击“重建索引”,使用当前激活的 embedding 模型重建此知识库。已有索引版本会保留。",+ "Rebuild this PageIndex knowledge base. Existing index versions are preserved.": "重建此 PageIndex 知识库,已有索引版本会保留。","Retry indexing from the documents already stored in this knowledge base.": "使用此知识库中已经保存的文档重试索引。","Re-index": "重建索引","Re-indexing…": "正在重建索引…",@@ -3076,6 +3078,13 @@"This book was written without reading your sources.": "这本书生成时没有读取你的资料来源。","Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "规划阶段检索失败,因此各章仅基于方案生成。重建会重新尝试读取你的知识库。","Source sweep failed": "来源扫描失败",+ "Index mode": "索引模式",+ "Default — Flash, summaries and full optimization": "默认 — Flash、摘要与完整优化",+ "Uses the globally active LLM credential. Leaving this unset delegates to the PageIndex SDK default.": "使用全局当前启用的 LLM 凭据。留空时采用 PageIndex SDK 默认配置。",+ "PDF only — use PageIndex Cloud for Office, Markdown or CSV": "仅支持 PDF;Office、Markdown 或 CSV 请使用 PageIndex Cloud",+ "This engine isn't ready on the server. Check its requirements before creating.": "此引擎尚未就绪,请先检查其运行要求。",+ "Local chunkless and vectorless indexing. Accepts PDF files and uses the globally active chat model credential for indexing; the index remains readable after model changes.": "本地无分块、无向量索引。支持 PDF,并使用全局当前聊天模型凭据构建索引;切换模型后旧索引仍可读取。",+ "PageIndex API plans": "PageIndex API 套餐","A record needs a title.": "记录需要一个标题。","Body": "正文","Copy to notebook": "复制到笔记本",diff --git a/web/next.config.js b/web/next.config.jsindex 7fb79d1c9..8d356a0ef 100644--- a/web/next.config.js+++ b/web/next.config.js@@ -115,6 +115,9 @@ const nextConfig = {// their total size is not coupled to this in-memory clone limit.experimental: {proxyClientMaxBodySize: 210 * 1024 * 1024,+ // Agentic reads and full-draft edits routinely exceed Next's 30-second+ // rewrite default; the browser remains responsible for cancelling them.+ proxyTimeout: 30 * 60 * 1000,},// Move dev indicator to bottom-right cornerdiff --git a/web/tests/book-page-chat.test.ts b/web/tests/book-page-chat.test.tsnew file mode 100644index 000000000..be5494330--- /dev/null+++ b/web/tests/book-page-chat.test.ts@@ -0,0 +1,29 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";++const source = readFileSync(+ path.resolve(+ process.cwd(),+ "app/(workspace)/book/components/BookChatPanel.tsx",+ ),+ "utf8",+);++test("resolving the first Page Chat session preserves its active socket", () => {+ const effectStart = source.indexOf("let cancelled = false;");+ const sameSessionGuard = source.indexOf(+ "initialSessionId === sessionIdRef.current",+ effectStart,+ );+ const disconnect = source.indexOf("clientRef.current?.disconnect();", effectStart);++ assert.notEqual(effectStart, -1);+ assert.notEqual(sameSessionGuard, -1);+ assert.notEqual(disconnect, -1);+ assert.ok(+ sameSessionGuard < disconnect,+ "the newly persisted session id must be ignored before resetting the live turn",+ );+});diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.tsindex 6cbfe64f0..ea9e66be1 100644--- a/web/tests/knowledge-helpers.test.ts+++ b/web/tests/knowledge-helpers.test.ts@@ -3,12 +3,35 @@ import assert from "node:assert/strict";import {kbCanReindex,+ providerUsesEmbeddingMetadata,resolveKnowledgeIndexFailure,taskFailureMessage,+ uploadPolicyForProvider,providerConnectionStatus,type KnowledgeBase,} from "../lib/knowledge-helpers";+test("PageIndex providers do not expose embedding metadata", () => {+ assert.equal(providerUsesEmbeddingMetadata("pageindex"), false);+ assert.equal(providerUsesEmbeddingMetadata("pageindex-oss"), false);+ assert.equal(providerUsesEmbeddingMetadata("llamaindex"), true);+ assert.equal(providerUsesEmbeddingMetadata("graphrag"), true);+});++test("PageIndex OSS upload policy accepts PDF only", () => {+ const base = {+ extensions: [".pdf", ".pptx", ".txt"],+ accept: ".pdf,.pptx,.txt",+ max_file_size_bytes: 100,+ };+ assert.deepEqual(uploadPolicyForProvider(base, "pageindex-oss"), {+ extensions: [".pdf"],+ accept: ".pdf",+ max_file_size_bytes: 100,+ });+ assert.equal(uploadPolicyForProvider(base, "llamaindex"), base);+});+function kb(overrides: Partial<KnowledgeBase>): KnowledgeBase {return {name: "kb",diff --git a/web/tests/knowledge-progress.test.ts b/web/tests/knowledge-progress.test.tsnew file mode 100644index 000000000..b80a36d15--- /dev/null+++ b/web/tests/knowledge-progress.test.ts@@ -0,0 +1,48 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ appendTaskLog,+ taskStateAfterProgress,+ type TaskState,+} from "../hooks/useKnowledgeProgress";++const running: TaskState = {+ taskId: "task-1",+ kind: "create",+ label: "Create KB",+ logs: ["Queued"],+ executing: true,+ error: null,+};++test("progress messages append once and complete the active task", () => {+ assert.deepEqual(appendTaskLog(["Queued"], "Indexing"), [+ "Queued",+ "Indexing",+ ]);+ assert.deepEqual(appendTaskLog(["Queued", "Indexing"], "Indexing"), [+ "Queued",+ "Indexing",+ ]);++ const completed = taskStateAfterProgress(running, "task-1", {+ task_id: "task-1",+ stage: "completed",+ message: "Index ready",+ });+ assert.equal(completed.executing, false);+ assert.equal(completed.error, null);+ assert.deepEqual(completed.logs, ["Queued", "Index ready"]);+});++test("progress from another task cannot overwrite current state", () => {+ assert.equal(+ taskStateAfterProgress(running, "task-2", {+ task_id: "task-2",+ stage: "error",+ error: "wrong task",+ }),+ running,+ );+});diff --git a/web/tests/proxy-policy.test.ts b/web/tests/proxy-policy.test.tsindex 1e5862220..72c21e198 100644--- a/web/tests/proxy-policy.test.ts+++ b/web/tests/proxy-policy.test.ts@@ -46,6 +46,16 @@ test("large knowledge uploads bypass the buffering proxy", () => {assert.equal(matches("http://localhost/home"), true);});+test("backend proxy allows long-running agent requests", () => {+ const nextConfig = require(path.resolve(process.cwd(), "next.config.js")) as {+ experimental?: { proxyTimeout?: number };+ };+ assert.ok(+ (nextConfig.experimental?.proxyTimeout ?? 0) >= 30 * 60 * 1000,+ "proxyTimeout must accommodate long PageIndex and Co-Writer turns",+ );+});+test("isCodexCallbackPath matches only the exact public callback path", () => {assert.equal(CODEX_CALLBACK_PATH, "/auth/callback");assert.equal(CODEX_CALLBACK_API_PATH, "/api/v1/auth/openai-codex/callback");