Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix:partners & improve my agents

Bingxi Zhao (Frank)7871955ab5ab
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index 03992d056..6f91f7230 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -101,6 +101,8 @@ def compose_enabled_tools(
capability_owned: Iterable[str] = (),
exclusive: bool = False,
builtin_whitelist: set[str] | None = None,
+ forced: Iterable[str] = (),
+ suppressed: Iterable[str] = (),
) -> list[str]:
"""Compose the per-turn enabled-tool list.
@@ -135,12 +137,20 @@ def compose_enabled_tools(
subtracts. User-toggled tools (step 1) and capability-owned tools (step 3)
are unaffected — they have their own gates.
+ ``forced`` tools are appended unconditionally — they bypass both the
+ ``builtin_whitelist`` and the context gates (used by the partner runtime to
+ mandate ``partner_read`` / ``partner_memorize`` / ``partner_search``).
+ ``suppressed`` tools are removed from the final list regardless of how they
+ got there (the partner runtime suppresses chat's ``read_memory`` /
+ ``write_memory`` in favour of the partner variants). Both apply in the
+ ``exclusive`` branch too.
+
The result is ordered and deduplicated. ``optional_whitelist`` is still
expected to exclude ``AUTO_MOUNTED_TOOLS`` via :func:`default_optional_tools`.
"""
if exclusive:
owned = [str(name) for name in capability_owned if str(name).strip()]
- return _ordered_unique([*owned, "ask_user"])
+ return _finalize([*owned, "ask_user"], forced, suppressed)
def _builtin_allowed(name: str) -> bool:
return builtin_whitelist is None or name in builtin_whitelist
@@ -157,7 +167,17 @@ def compose_enabled_tools(
for always_on in ("write_memory", "web_fetch", "github", "ask_user", "cron"):
if _builtin_allowed(always_on):
composed.append(always_on)
- return _ordered_unique(composed)
+ return _finalize(composed, forced, suppressed)
+
+
+def _finalize(
+ names: Iterable[str], forced: Iterable[str], suppressed: Iterable[str]
+) -> list[str]:
+ """Append ``forced`` (bypassing all gates), dedupe, then drop ``suppressed``."""
+ out = list(names)
+ out.extend(str(name) for name in forced if str(name).strip())
+ suppressed_set = {str(name) for name in suppressed}
+ return [name for name in _ordered_unique(out) if name not in suppressed_set]
def _ordered_unique(names: Iterable[str]) -> list[str]:
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 52c0536e8..a19ae7891 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -52,9 +52,13 @@ from deeptutor.services.llm import (
)
from deeptutor.services.llm.context_window import resolve_effective_context_window
from deeptutor.services.prompt import get_prompt_manager
+from deeptutor.tools.builtin import PARTNER_BUILTIN_TOOL_NAMES
logger = logging.getLogger(__name__)
+# Chat memory tools a partner turn replaces with the partner_* variants.
+_PARTNER_SUPPRESSED_TOOLS: tuple[str, ...] = ("read_memory", "write_memory")
+
CHAT_EXCLUDED_TOOLS: set[str] = set()
CHAT_OPTIONAL_TOOLS = default_optional_tools(excluded=CHAT_EXCLUDED_TOOLS)
@@ -499,6 +503,7 @@ class AgenticChatPipeline:
return False
def _compose_enabled_tools(self, context: UnifiedContext) -> list[str]:
+ is_partner = str((context.metadata or {}).get("source")) == "partner"
composed = compose_enabled_tools(
registry=self.registry,
requested_tools=context.enabled_tools,
@@ -523,6 +528,12 @@ class AgenticChatPipeline:
if context.allowed_builtin_tools is not None
else None
),
+ # Partners get the partner_* memory/history tools force-mounted and
+ # chat's read_memory/write_memory suppressed — the split-memory model
+ # (own workspace writable, owner's memory read-only) lives in those
+ # tools, not in chat's.
+ forced=PARTNER_BUILTIN_TOOL_NAMES if is_partner else (),
+ suppressed=_PARTNER_SUPPRESSED_TOOLS if is_partner else (),
)
return _drop_unconfigured_generation_tools(composed)
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py
index fda24bbe4..ad3e9e630 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -420,13 +420,15 @@ async def tool_options():
``tools`` mirrors the user-toggleable system tools (the same pool the
chat composer / settings expose); ``builtin_tools`` lists the auto-mounted
- built-in tools (rag / read_memory / web_fetch / …) the owner can allow or
- deny; ``mcp_tools`` lists every configured MCP tool the partner could be
- allowed to load.
+ built-in tools (rag / web_fetch / …) the owner can allow or deny;
+ ``mcp_tools`` lists every configured MCP tool the partner could be allowed
+ to load. ``read_memory`` / ``write_memory`` are excluded: partners use the
+ mandatory ``partner_read`` / ``partner_memorize`` / ``partner_search`` tools
+ instead, which are always on and not owner-configurable.
"""
from deeptutor.api.utils.tool_options import build_tool_options
- return await build_tool_options()
+ return await build_tool_options(exclude_builtin={"read_memory", "write_memory"})
# ── Create / read / update / lifecycle ─────────────────────────
diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.py
index 4fd6ab8a3..23dbf5952 100644
--- a/deeptutor/api/routers/subagents.py
+++ b/deeptutor/api/routers/subagents.py
@@ -22,11 +22,12 @@ from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
-from deeptutor.api.routers.auth import require_admin
+from deeptutor.api.routers.auth import require_admin, require_auth
from deeptutor.knowledge.kb_types import SUBAGENT_KB_TYPE
from deeptutor.multi_user.knowledge_access import current_kb_manager
from deeptutor.services.rag.linked_kb import assert_path_allowed
from deeptutor.services.subagent import (
+ PARTNER_BACKEND_KIND,
detect_all,
list_backend_kinds,
load_subagent_settings,
@@ -42,6 +43,9 @@ class ConnectSubagentRequest(BaseModel):
name: str
agent_kind: str
cwd: str = ""
+ # For the partner backend (``agent_kind == "partner"``): which partner to
+ # consult. Ignored by the local-CLI backends, which use ``cwd`` instead.
+ partner_id: str = ""
class SubagentSettingsPayload(BaseModel):
@@ -77,10 +81,12 @@ async def sync_backend(kind: str):
For Claude Code this scrapes its ``/model`` TUI live and caches the result;
for Codex it re-reads the CLI-maintained cache.
"""
- from deeptutor.services.subagent import list_backend_kinds
+ from deeptutor.services.subagent import get_backend
from deeptutor.services.subagent.models import sync_backend_options
- if kind not in list_backend_kinds():
+ backend = get_backend(kind)
+ if backend is None or not getattr(backend, "local_cli", True):
+ # Only local CLIs have a model catalog to sync; partners run their own.
raise HTTPException(status_code=400, detail=f"Unknown agent kind: {kind!r}")
options = await sync_backend_options(kind)
return options.to_dict()
@@ -100,6 +106,7 @@ async def list_connections():
"name": name,
"agent_kind": meta.get("agent_kind", ""),
"cwd": meta.get("cwd", ""),
+ "partner_id": meta.get("partner_id", ""),
"description": meta.get("description", ""),
"created_at": meta.get("created_at"),
"updated_at": meta.get("updated_at"),
@@ -109,8 +116,14 @@ async def list_connections():
@router.post("/connections")
-async def create_connection(payload: ConnectSubagentRequest):
- """Connect a local agent CLI as a selectable subagent KB."""
+async def create_connection(payload: ConnectSubagentRequest, auth=Depends(require_auth)):
+ """Connect a subagent (a local CLI, or one of the user's partners) as a selectable KB.
+
+ A partner connection (``agent_kind == "partner"``) binds a ``partner_id``
+ instead of a working directory: consulting it opens a fresh session on that
+ partner, exactly as if the user started one from the partner page. Every
+ consult within one DeepTutor chat lands in that one partner session.
+ """
name = (payload.name or "").strip()
agent_kind = (payload.agent_kind or "").strip()
if not name or not agent_kind:
@@ -119,16 +132,33 @@ async def create_connection(payload: ConnectSubagentRequest):
raise HTTPException(status_code=400, detail=f"Unknown agent kind: {agent_kind!r}")
resolved_cwd = ""
- raw_cwd = (payload.cwd or "").strip()
- if raw_cwd:
- try:
- resolved_cwd = str(assert_path_allowed(raw_cwd))
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
+ partner_id = ""
+ if agent_kind == PARTNER_BACKEND_KIND:
+ # Partners are anchored to the admin workspace (the whole partners API is
+ # admin-gated), and consulting one runs it in that scope. This router is
+ # only auth-gated, so gate the partner branch on admin to match — a
+ # non-admin must not be able to drive an admin-scoped partner.
+ await require_admin(auth)
+ partner_id = (payload.partner_id or "").strip()
+ if not partner_id:
+ raise HTTPException(status_code=400, detail="A partner_id is required to connect a partner.")
+ from deeptutor.services.partners import get_partner_manager
+
+ if not get_partner_manager().partner_exists(partner_id):
+ raise HTTPException(status_code=400, detail=f"No partner named {partner_id!r}.")
+ else:
+ raw_cwd = (payload.cwd or "").strip()
+ if raw_cwd:
+ try:
+ resolved_cwd = str(assert_path_allowed(raw_cwd))
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
manager = current_kb_manager()
- entry = manager.register_subagent_connection(name, agent_kind, cwd=resolved_cwd)
+ entry = manager.register_subagent_connection(
+ name, agent_kind, cwd=resolved_cwd, partner_id=partner_id
+ )
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # pragma: no cover - defensive
@@ -140,6 +170,7 @@ async def create_connection(payload: ConnectSubagentRequest):
"name": name,
"agent_kind": entry["agent_kind"],
"cwd": entry["cwd"],
+ "partner_id": entry.get("partner_id", ""),
}
@@ -190,6 +221,7 @@ async def message_connection(name: str, payload: SubagentMessageRequest):
kind = str(meta.get("agent_kind") or "")
cwd = str(meta.get("cwd") or "")
+ partner_id = str(meta.get("partner_id") or "")
backend = get_backend(kind)
if backend is None:
raise HTTPException(status_code=400, detail=f"Unknown agent kind: {kind!r}")
@@ -212,6 +244,7 @@ async def message_connection(name: str, payload: SubagentMessageRequest):
cwd=cwd or None,
session_id=resume_id,
config=config,
+ partner_id=partner_id or None,
)
await queue.put(("done", res))
except Exception as exc: # pragma: no cover - defensive
diff --git a/deeptutor/api/utils/tool_options.py b/deeptutor/api/utils/tool_options.py
index 7b32eeddc..8130da871 100644
--- a/deeptutor/api/utils/tool_options.py
+++ b/deeptutor/api/utils/tool_options.py
@@ -18,11 +18,22 @@ from deeptutor.i18n.metadata_i18n import localized_description, tool_description
logger = logging.getLogger(__name__)
-async def build_tool_options() -> dict[str, list[dict[str, Any]]]:
+async def build_tool_options(
+ *, exclude_builtin: set[str] | None = None
+) -> dict[str, list[dict[str, Any]]]:
+ """Build the configurable-tool surface.
+
+ ``exclude_builtin`` drops built-in tools from the ``builtin_tools`` list —
+ the partners API passes ``{"read_memory", "write_memory"}`` because partners
+ use the mandatory ``partner_*`` memory tools instead and cannot configure
+ chat's memory tools.
+ """
from deeptutor.agents._shared.tool_composition import default_optional_tools
from deeptutor.runtime.registry.tool_registry import get_tool_registry
from deeptutor.tools.builtin import CONFIGURABLE_BUILTIN_TOOL_NAMES
+ exclude = exclude_builtin or set()
+
registry = get_tool_registry()
language = current_language()
try:
@@ -49,7 +60,7 @@ async def build_tool_options() -> dict[str, list[dict[str, Any]]]:
tools: list[dict[str, Any]] = [_describe(name) for name in default_optional_tools()]
builtin_tools: list[dict[str, Any]] = [
- _describe(name) for name in CONFIGURABLE_BUILTIN_TOOL_NAMES
+ _describe(name) for name in CONFIGURABLE_BUILTIN_TOOL_NAMES if name not in exclude
]
mcp_tools: list[dict[str, Any]] = []
diff --git a/deeptutor/capabilities/subagent/binding.py b/deeptutor/capabilities/subagent/binding.py
index 0f3c16de0..cb8207a9d 100644
--- a/deeptutor/capabilities/subagent/binding.py
+++ b/deeptutor/capabilities/subagent/binding.py
@@ -2,10 +2,11 @@
Mirrors :mod:`deeptutor.capabilities.obsidian.binding`: the binding is derived
once per turn from the user's selected knowledge bases — the first selection
-whose KB metadata is ``type == subagent`` wins, and its ``agent_kind`` / ``cwd``
-become the live connection the consult tool drives. Cached on
-``context.metadata`` so ``is_active`` / ``augment_kwargs`` / ``system_block``
-share one lookup. Pure read; access errors resolve to "no connection".
+whose KB metadata is ``type == subagent`` wins, and its ``agent_kind`` plus its
+target (``cwd`` for a local CLI, ``partner_id`` for a partner) become the live
+connection the consult tool drives. Cached on ``context.metadata`` so
+``is_active`` / ``augment_kwargs`` / ``system_block`` share one lookup. Pure
+read; access errors resolve to "no connection".
"""
from __future__ import annotations
@@ -13,14 +14,14 @@ from __future__ import annotations
from deeptutor.core.context import UnifiedContext
from deeptutor.knowledge.kb_types import SUBAGENT_KB_TYPE
-# Cached on context.metadata: a {"name", "kind", "cwd"} dict, or "" once we've
-# looked and found none. Absence of the key means "not resolved yet".
+# Cached on context.metadata: a {"name", "kind", "cwd", "partner_id"} dict, or ""
+# once we've looked and found none. Absence of the key means "not resolved yet".
_CACHE_KEY = "_subagent_connection"
_UNSET = object()
def connection_for_turn(context: UnifiedContext) -> dict[str, str] | None:
- """Return ``{"name", "kind", "cwd"}`` of the selected subagent, or ``None``."""
+ """Return ``{"name", "kind", "cwd", "partner_id"}`` of the selected subagent, or ``None``."""
cached = context.metadata.get(_CACHE_KEY, _UNSET)
if cached is not _UNSET:
return cached or None
@@ -46,6 +47,7 @@ def _resolve(context: UnifiedContext) -> dict[str, str] | None:
"name": str(meta.get("name") or ref),
"kind": kind,
"cwd": str(meta.get("cwd") or "").strip(),
+ "partner_id": str(meta.get("partner_id") or "").strip(),
}
return None
diff --git a/deeptutor/capabilities/subagent/capability.py b/deeptutor/capabilities/subagent/capability.py
index 8b441f4eb..9a49b658f 100644
--- a/deeptutor/capabilities/subagent/capability.py
+++ b/deeptutor/capabilities/subagent/capability.py
@@ -53,7 +53,9 @@ class SubagentCapability(KnowledgeCapability):
# runs once during prompt assembly, before the loop reads its round
# budget — see ``_FINISH_HEADROOM``.
context.metadata["_min_loop_rounds"] = budget + _FINISH_HEADROOM
- return PromptBlock("subagent", _system_text(language, conn["name"], budget))
+ return PromptBlock(
+ "subagent", _system_text(language, conn["name"], budget, conn.get("kind", ""))
+ )
def augment_kwargs(
self,
@@ -99,6 +101,7 @@ class SubagentCapability(KnowledgeCapability):
updated["_subagent"] = {
"kind": conn["kind"],
"cwd": conn.get("cwd") or "",
+ "partner_id": conn.get("partner_id") or "",
"name": conn["name"],
"budget": _resolve_budget(context),
"config": config,
@@ -154,28 +157,55 @@ def _resolve_budget(context: UnifiedContext) -> int:
return load_subagent_settings().consult_budget
-def _system_text(language: str, name: str, budget: int) -> str:
- if str(language or "en").lower().startswith("zh"):
+def _system_text(language: str, name: str, budget: int, kind: str = "") -> str:
+ from deeptutor.services.subagent import PARTNER_BACKEND_KIND
+
+ is_partner = kind == PARTNER_BACKEND_KIND
+ zh = str(language or "en").lower().startswith("zh")
+ if zh:
+ if is_partner:
+ framing = (
+ f"本轮你已连接到用户的伙伴「{name}」——一个有自己人格、知识库与技能的助手。你可以通过 "
+ f"`consult_subagent` 工具向它咨询,把它当作一位独立的同事来求助(例如借助它专属的知识库"
+ f"或视角来回答)。你们的往来会作为一个完整会话归档到该伙伴的历史里,它的回复过程会实时展示给用户。"
+ )
+ else:
+ framing = (
+ f"本轮你已连接到用户本机的外部智能体「{name}」。你可以通过 `consult_subagent` "
+ f"工具向它提问,把它当作一个能在用户机器上读写文件、运行命令的得力助手来委派任务"
+ f"(例如排查代码库、复现问题、运行脚本)。它的完整运行过程会实时展示给用户。"
+ )
return (
- f"本轮你已连接到用户本机的外部智能体「{name}」。你可以通过 `consult_subagent` "
- f"工具向它提问,把它当作一个能在用户机器上读写文件、运行命令的得力助手来委派任务"
- f"(例如排查代码库、复现问题、运行脚本)。它的完整运行过程会实时展示给用户。\n\n"
+ f"{framing}\n\n"
f"- 本轮最多可向它提问 {budget} 次;每次结果会告诉你还剩几次。它会在本轮内记住你"
f"之前的提问,所以可以层层追问。\n"
f"- 当你掌握了足够信息后,停止调用该工具,用你自己的口吻直接回答用户——"
- f"不要假借该智能体的身份或第一人称转述它的话。"
+ f"不要假借它的身份或第一人称转述它的话。"
+ )
+ if is_partner:
+ framing = (
+ f"You are connected this turn to the user's partner “{name}” — a companion "
+ f"with its own persona, library and skills. Consult it with the "
+ f"`consult_subagent` tool as you would an independent colleague (e.g. for "
+ f"its dedicated knowledge or perspective). Your exchange is archived as one "
+ f"complete session in that partner's history, and its reply is shown to the "
+ f"user live."
+ )
+ else:
+ framing = (
+ f"You are connected this turn to the user's local external agent “{name}”. "
+ f"Consult it with the `consult_subagent` tool, delegating work it is better "
+ f"placed to do on the user's machine — inspecting a codebase, reproducing a "
+ f"bug, running commands. Its full run is shown to the user live."
)
return (
- f"You are connected this turn to the user's local external agent “{name}”. "
- f"Consult it with the `consult_subagent` tool, delegating work it is better "
- f"placed to do on the user's machine — inspecting a codebase, reproducing a "
- f"bug, running commands. Its full run is shown to the user live.\n\n"
+ f"{framing}\n\n"
f"- You may consult it at most {budget} time(s) this turn; each result tells "
f"you how many remain. It remembers your earlier questions this turn, so you "
f"can drill down.\n"
f"- Once you have enough, stop calling the tool and answer the user directly "
- f"in your own voice — never impersonate the agent or relay its words in the "
- f"first person."
+ f"in your own voice — never impersonate it or relay its words in the first "
+ f"person."
)
diff --git a/deeptutor/capabilities/subagent/tools.py b/deeptutor/capabilities/subagent/tools.py
index e9d25c307..9370f1c96 100644
--- a/deeptutor/capabilities/subagent/tools.py
+++ b/deeptutor/capabilities/subagent/tools.py
@@ -47,15 +47,17 @@ class ConsultSubagentTool(BaseTool):
name="consult_subagent",
description=(
"Ask the connected external agent (the user's local Claude Code / "
- "Codex) a focused question and get its answer. The agent runs on the "
- "user's machine with access to their files and tools; its full "
- "step-by-step run is shown to the user live. Use it to delegate work "
- "the local agent is better placed to do — inspecting a codebase, "
- "running commands, reproducing a bug. You may consult it more than "
- "once to drill down, but you have a limited number of consults this "
- "turn (the result tells you how many remain). When you have enough, "
- "stop calling this tool and answer the user yourself in your own "
- "voice — never impersonate the agent."
+ "Codex, or one of their partners) a focused question and get its "
+ "answer. A local agent runs on the user's machine with access to their "
+ "files and tools; a partner answers with its own persona, library and "
+ "skills. Either way its full step-by-step run is shown to the user "
+ "live. Use it to delegate work it is better placed to do — inspecting "
+ "a codebase, running commands, reproducing a bug, or drawing on a "
+ "partner's dedicated knowledge. You may consult it more than once to "
+ "drill down, but you have a limited number of consults this turn (the "
+ "result tells you how many remain). When you have enough, stop calling "
+ "this tool and answer the user yourself in your own voice — never "
+ "impersonate the agent."
),
parameters=[
ToolParameter(
@@ -144,6 +146,7 @@ class ConsultSubagentTool(BaseTool):
session_id=state.get("session_id"),
config=spec.get("config"),
images=image_paths or None,
+ partner_id=spec.get("partner_id") or None,
)
except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn
logger.warning("consult_subagent failed: %s", exc, exc_info=True)
diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.py
index ccf456b5a..2d82b3af6 100644
--- a/deeptutor/knowledge/kb_types.py
+++ b/deeptutor/knowledge/kb_types.py
@@ -13,11 +13,11 @@ flavours exist today:
engine index the user built elsewhere (LlamaIndex / GraphRAG / LightRAG).
Retrieval reads that index in place — the indexing step is skipped, and the
KB is queried by its bound ``rag_provider`` exactly like an ordinary KB.
-* ``subagent`` — a pointer to one of the user's *local* agent CLIs (Claude
- Code / Codex). It has no path on disk: ``agent_kind`` names the backend and
- an optional ``cwd`` is the working directory. There is nothing to index or
- retrieve — the subagent capability drives the live CLI through the
- ``consult_subagent`` tool. See ``capabilities/subagent``.
+* ``subagent`` — a pointer to a connected agent the capability drives live
+ through the ``consult_subagent`` tool. ``agent_kind`` names the backend: a
+ *local* CLI (Claude Code / Codex), keyed by an optional ``cwd``; or a
+ ``partner`` (one of the user's own partners), keyed by ``partner_id``. It has
+ no path on disk and nothing to index or retrieve. See ``capabilities/subagent``.
All connected flavours share the same lifecycle quirks: no on-disk folder under
``base_dir``, no embedding reconcile, and deletion must never touch the
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 90bf8a410..d6527dfe8 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -788,18 +788,21 @@ class KnowledgeBaseManager:
agent_kind: str,
*,
cwd: str = "",
+ partner_id: str = "",
description: str = "",
) -> dict:
- """Register a connected subagent (local Claude Code / Codex) as a KB.
+ """Register a connected subagent (local Claude Code / Codex, or a partner) as a KB.
Like the other connected types this creates no folder and runs no index:
it records a ``type: subagent`` pointer naming the backend (``agent_kind``)
- and an optional working directory (``cwd``). The subagent capability
- drives the live CLI; there is nothing on disk to retrieve or reconcile.
- Raises ``ValueError`` on a missing name/kind or a name clash.
+ and its target — an optional working directory (``cwd``) for a local CLI,
+ or the bound ``partner_id`` for the partner backend. The subagent
+ capability drives the live agent; there is nothing on disk to retrieve or
+ reconcile. Raises ``ValueError`` on a missing name/kind or a name clash.
"""
name = (name or "").strip()
agent_kind = (agent_kind or "").strip()
+ partner_id = (partner_id or "").strip()
if not name:
raise ValueError("Connection name is required.")
if not agent_kind:
@@ -822,6 +825,7 @@ class KnowledgeBaseManager:
"type": SUBAGENT_KB_TYPE,
"agent_kind": agent_kind,
"cwd": resolved_cwd,
+ "partner_id": partner_id,
"description": description or f"Connected subagent: {name}",
"status": "ready",
"created_at": now,
@@ -976,6 +980,7 @@ class KnowledgeBaseManager:
# Subagent connection fields (None for non-subagent KBs).
"agent_kind": kb_config.get("agent_kind"),
"cwd": kb_config.get("cwd"),
+ "partner_id": kb_config.get("partner_id"),
}
metadata.update(self._embedding_fields(kb_config))
# Remove None values
diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.py
index 05c44ed13..861cbef93 100644
--- a/deeptutor/services/partners/runtime.py
+++ b/deeptutor/services/partners/runtime.py
@@ -235,9 +235,7 @@ class PartnerRunner:
becomes the reply (the final outbound is then marked ``_streamed``
so the channel doesn't send it twice).
"""
- from deeptutor.multi_user.paths import get_admin_path_service
from deeptutor.runtime.orchestrator import ChatOrchestrator
- from deeptutor.services.memory import memory_path_service_override
from deeptutor.services.model_selection.runtime import (
activate_llm_selection,
reset_llm_selection,
@@ -279,17 +277,15 @@ class PartnerRunner:
wants_stream = is_im and send_progress and bool(msg.metadata.get("_wants_stream"))
_config, llm_token = activate_llm_selection(selection)
- # Partner scope routes rag / skills / notebooks at the partner's own
- # workspace, but memory is the *owner's*: partners are anchored to
- # the admin workspace, so read_memory / write_memory must see the
- # admin's L3 (gated by the builtin-tool whitelist — an owner denies
- # memory to an IM-facing partner). Without this, the partner scope's
- # empty memory makes user_has_memory() False and read_memory never
- # mounts, so the agent falls back to notebooks to "know the user".
- with (
- user_context(partner_user(self.partner_id, name=self.config.name)),
- memory_path_service_override(get_admin_path_service()),
- ):
+ # Everything — rag / skills / notebooks AND memory — resolves to the
+ # partner's own synthetic workspace. The partner-only memory tools
+ # (partner_read / partner_memorize / partner_search, force-mounted by
+ # the pipeline) own the split-memory model: partner_read folds in the
+ # owner's shared L3 on top of the partner's own, partner_memorize
+ # writes only the partner's own. Chat's read_memory / write_memory
+ # are suppressed on partner turns, so no admin memory override is
+ # needed here (and the partner can never write the owner's memory).
+ with user_context(partner_user(self.partner_id, name=self.config.name)):
orchestrator = ChatOrchestrator()
async for event in orchestrator.handle(context):
if on_event is not None:
diff --git a/deeptutor/services/session/source_inventory.py b/deeptutor/services/session/source_inventory.py
index 39051dc61..ae437e288 100644
--- a/deeptutor/services/session/source_inventory.py
+++ b/deeptutor/services/session/source_inventory.py
@@ -624,11 +624,16 @@ def _imported_agent_label(meta: dict[str, Any], lang: str) -> str | None:
A referenced session is "imported" when its id carries the ``imported_``
prefix or its preferences hold the ``import`` block written at import time.
+ A referenced *partner* session (resolved by :func:`_load_partner_session`)
+ carries ``source == "partner"`` and is framed with the partner's own name.
"""
prefs = meta.get("preferences") if isinstance(meta, dict) else None
import_meta = prefs.get("import") if isinstance(prefs, dict) else None
source = str((import_meta or {}).get("source") or "").strip().lower()
sid = str(meta.get("session_id") or meta.get("id") or "")
+ if source == "partner":
+ name = str(meta.get("partner_name") or "").strip()
+ return name or ("伙伴" if lang == "zh" else "a partner")
if not source and not sid.startswith("imported_"):
return None
if source in _EXTERNAL_AGENT_LABELS:
@@ -708,6 +713,56 @@ def serialize_referenced_transcript(
return header + "\n\n" + "\n\n".join(lines)
+# A referenced *partner* session: ``partner:{partner_id}:{session_key}``. The
+# session_key itself may contain ``:`` (e.g. ``web:abc``), so only the partner
+# id is split off — partner ids are colon-free slugs.
+_PARTNER_REF_PREFIX = "partner:"
+
+
+def _load_partner_session(ref: str, *, language: str = "en") -> tuple[str, str]:
+ """Resolve a ``partner:{pid}:{session_key}`` reference into transcript + title.
+
+ Partner conversations live in the admin-scoped ``PartnerSessionStore`` (one
+ JSONL per session under ``data/partners/<id>/sessions/``), not the main
+ session store — so they resolve here through the partner manager rather than
+ ``store.get_session``. Gated to admins: partner data is admin-scoped (the
+ whole partners API is admin-gated), and this read runs inside the user's
+ turn, so a non-admin must not be able to pull a partner's transcript by
+ hand-crafting a reference id. Returns ``("", "")`` on any miss.
+ """
+ rest = ref[len(_PARTNER_REF_PREFIX):]
+ pid, _, session_key = rest.partition(":")
+ pid, session_key = pid.strip(), session_key.strip()
+ if not pid or not session_key:
+ return "", ""
+
+ from deeptutor.multi_user.context import get_current_user
+
+ if not get_current_user().is_admin:
+ return "", ""
+ try:
+ from deeptutor.services.partners import get_partner_manager
+
+ manager = get_partner_manager()
+ if not manager.partner_exists(pid):
+ return "", ""
+ messages = manager.get_history(pid, session_key=session_key, limit=400)
+ config = manager.load_config(pid)
+ except Exception:
+ logger.debug("Failed to resolve partner session %r", ref, exc_info=True)
+ return "", ""
+
+ partner_name = (getattr(config, "name", "") or pid).strip()
+ meta = {"preferences": {"import": {"source": "partner"}}, "partner_name": partner_name}
+ transcript = serialize_referenced_transcript(meta, messages, language=language)
+ if not transcript:
+ return "", ""
+ opener = next((m for m in messages if str(m.get("role")) == "user"), None)
+ first_line = str((opener or {}).get("content", "") or "").strip().splitlines()
+ title = (first_line[0][:60].strip() if first_line else "") or partner_name
+ return transcript, title
+
+
async def _load_history_session(
store: SessionStoreProtocol,
history_session_id: str,
@@ -716,7 +771,12 @@ async def _load_history_session(
) -> tuple[str, str]:
"""Fetch and serialize a referenced history session into transcript +
title. Returns ``("", "")`` when the session is empty or missing.
+
+ A ``partner:`` reference resolves through the partner store instead of the
+ main session store (see :func:`_load_partner_session`).
"""
+ if history_session_id.startswith(_PARTNER_REF_PREFIX):
+ return _load_partner_session(history_session_id, language=language)
try:
meta = await store.get_session(history_session_id)
except Exception:
diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.py
index b4907191c..c64705739 100644
--- a/deeptutor/services/subagent/__init__.py
+++ b/deeptutor/services/subagent/__init__.py
@@ -22,6 +22,7 @@ from deeptutor.services.subagent.config import (
save_subagent_settings,
settings_from_dict,
)
+from deeptutor.services.subagent.partner import PARTNER_BACKEND_KIND
from deeptutor.services.subagent.registry import detect_all, get_backend, list_backend_kinds
from deeptutor.services.subagent.types import (
ConsultResult,
@@ -37,6 +38,7 @@ __all__ = [
"DEFAULT_CONSULT_BUDGET",
"CONSULT_BUDGET_MIN",
"CONSULT_BUDGET_MAX",
+ "PARTNER_BACKEND_KIND",
"get_consult_budget",
"load_subagent_settings",
"save_subagent_settings",
diff --git a/deeptutor/services/subagent/base.py b/deeptutor/services/subagent/base.py
index 11645eb75..263600ad3 100644
--- a/deeptutor/services/subagent/base.py
+++ b/deeptutor/services/subagent/base.py
@@ -22,11 +22,15 @@ OnEvent = Callable[[SubagentEvent], Awaitable[None]]
class SubagentBackend(ABC):
- """Drive one local agent CLI (Claude Code, Codex, …) as a subagent."""
+ """Drive one subagent (a local CLI, or one of the user's partners)."""
kind: str
display_name: str
cli_command: str
+ # Local-CLI backends (Claude Code, Codex) are detected on this machine and
+ # offered in the connect-CLI modal. Non-CLI backends (a Partner) are
+ # connected from their own list, so they sit out machine detection.
+ local_cli: bool = True
@abstractmethod
async def detect(self) -> DetectResult:
@@ -42,6 +46,7 @@ class SubagentBackend(ABC):
session_id: str | None = None,
config: BackendConfig | None = None,
images: list[str] | None = None,
+ partner_id: str | None = None,
) -> ConsultResult:
"""Put one question to the subagent and stream every native event.
@@ -50,8 +55,9 @@ class SubagentBackend(ABC):
returned :class:`ConsultResult` carries the session id to thread into the
next consult. ``images`` are local file paths the user forwarded with the
question (Codex attaches them with ``-i``; Claude Code is pointed at them
- for its Read tool). Waits unconditionally for the subagent to finish —
- only its own exit (clean or error) ends the consult.
+ for its Read tool). ``partner_id`` names the bound partner for the partner
+ backend (the CLI backends ignore it). Waits unconditionally for the
+ subagent to finish — only its own exit (clean or error) ends the consult.
"""
diff --git a/deeptutor/services/subagent/claude_code.py b/deeptutor/services/subagent/claude_code.py
index 123b3e729..d779ad3ce 100644
--- a/deeptutor/services/subagent/claude_code.py
+++ b/deeptutor/services/subagent/claude_code.py
@@ -128,6 +128,7 @@ class ClaudeCodeBackend(SubagentBackend):
session_id: str | None = None,
config: BackendConfig | None = None,
images: list[str] | None = None,
+ partner_id: str | None = None, # noqa: ARG002 — partner-only; ignored here
) -> ConsultResult:
config = config or BackendConfig()
cmd = self._build_command(
diff --git a/deeptutor/services/subagent/codex.py b/deeptutor/services/subagent/codex.py
index ca5a752a4..dd6c64875 100644
--- a/deeptutor/services/subagent/codex.py
+++ b/deeptutor/services/subagent/codex.py
@@ -122,6 +122,7 @@ class CodexBackend(SubagentBackend):
session_id: str | None = None,
config: BackendConfig | None = None,
images: list[str] | None = None,
+ partner_id: str | None = None, # noqa: ARG002 — partner-only; ignored here
) -> ConsultResult:
config = config or BackendConfig()
cmd = self._build_command(
diff --git a/deeptutor/services/subagent/partner.py b/deeptutor/services/subagent/partner.py
new file mode 100644
index 000000000..c3d906443
--- /dev/null
+++ b/deeptutor/services/subagent/partner.py
@@ -0,0 +1,249 @@
+"""Partner backend — consult one of the user's own partners as a subagent.
+
+Unlike the local-CLI backends (Claude Code / Codex) this drives no subprocess:
+it puts the question to a running partner through the partner manager's web
+entry point, exactly as if the user opened a new session on the partner page.
+The partner answers with its own chat loop — its soul, library and skills — and
+streams its native trace back, which we map onto the coarse subagent event
+channels so the sidebar renders it like any other consulted agent.
+
+Session continuity is the whole point of the design. ``session_id`` here IS the
+*partner session key*. The first consult of a DeepTutor chat session has none,
+so we mint a fresh ``dt-…`` key and return it; the cross-turn registry
+(:mod:`deeptutor.services.subagent.sessions`) remembers it against
+(chat session, connection), so every later consult in the same DeepTutor chat —
+within one turn or across turns — resumes the SAME partner session. The partner
+page then sees one complete history session per DeepTutor chat, titled from the
+first consult's question.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+import uuid
+
+from deeptutor.services.subagent.base import OnEvent, SubagentBackend
+from deeptutor.services.subagent.config import BackendConfig
+from deeptutor.services.subagent.types import (
+ EVENT_ERROR,
+ EVENT_REASONING,
+ EVENT_TEXT,
+ EVENT_TOOL,
+ EVENT_TOOL_RESULT,
+ ConsultResult,
+ DetectResult,
+ SubagentEvent,
+)
+
+if TYPE_CHECKING: # avoid importing the core/partner packages at module load
+ from deeptutor.core.stream import StreamEvent
+
+logger = logging.getLogger(__name__)
+
+PARTNER_BACKEND_KIND = "partner"
+
+# Cap on how much of a tool-call's args / a tool result we echo into the trace
+# line — keeps the sidebar readable without dropping the event.
+_MAX_LINE_CHARS = 600
+
+
+class PartnerBackend(SubagentBackend):
+ """Consult one of the user's partners as a delegate, in-process."""
+
+ kind = PARTNER_BACKEND_KIND
+ display_name = "Partner"
+ cli_command = ""
+ local_cli = False
+
+ async def detect(self) -> DetectResult:
+ # Partners are a built-in feature, not a machine-local CLI: ``available``
+ # only gates the connect-CLI modal, which this backend deliberately sits
+ # out (partners are connected from the partner list instead).
+ return DetectResult(
+ kind=self.kind,
+ display_name=self.display_name,
+ available=False,
+ detail="Partners are connected from your partner list, not detected on this machine.",
+ )
+
+ async def consult(
+ self,
+ question: str,
+ *,
+ on_event: OnEvent,
+ cwd: str | None = None, # noqa: ARG002 — CLI-only; partners have no cwd
+ session_id: str | None = None,
+ config: BackendConfig | None = None, # noqa: ARG002 — partner runs its own soul
+ images: list[str] | None = None,
+ partner_id: str | None = None,
+ ) -> ConsultResult:
+ pid = str(partner_id or "").strip()
+ if not pid:
+ return ConsultResult(success=False, error="No partner is bound to this connection.")
+
+ from deeptutor.services.partners import get_partner_manager
+
+ manager = get_partner_manager()
+ if not manager.partner_exists(pid):
+ return ConsultResult(success=False, error=f"Partner '{pid}' no longer exists.")
+
+ # Bring the partner online if it isn't already (auto-start partners are).
+ instance = manager.get_partner(pid)
+ if instance is None or not instance.running:
+ try:
+ await manager.start_partner(pid)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("Failed to start partner %s for consult: %s", pid, exc)
+ return ConsultResult(success=False, error=f"Could not start partner '{pid}': {exc}")
+
+ # ``session_id`` is the partner session key. None on the first consult of
+ # a DeepTutor chat → mint a stable, colon-free key; the registry threads
+ # it through every later consult so they all land in one partner session.
+ session_key = str(session_id or "").strip() or f"dt-{uuid.uuid4().hex[:12]}"
+
+ events = 0
+ # Per-stream state shared across the loop's events:
+ # - text/reason: the chat loop streams CONTENT/THINKING as *incremental*
+ # deltas; we accumulate per call_id and emit the running full text (the
+ # CLI backends do the same) so the row grows instead of being wiped by
+ # each chunk.
+ # - pending_tools: the loop dispatches tools in PARALLEL — all TOOL_CALL
+ # events, then all TOOL_RESULT events — so a call and its result aren't
+ # adjacent. We hold each call (keyed by its call_id, shared with its
+ # result) and emit it back-to-back with its result, so the trace reads
+ # as call → result pairs.
+ state = {
+ "text": {}, # type: dict[str, str]
+ "reason": {}, # type: dict[str, str]
+ "pending_tools": {}, # type: dict[str, str]
+ }
+
+ async def relay(event: "StreamEvent") -> None:
+ nonlocal events
+ for out in _to_subagent_events(event, state):
+ events += 1
+ await on_event(out)
+
+ try:
+ reply = await manager.send_message(
+ pid,
+ question,
+ session_key=session_key,
+ media=list(images or []),
+ on_event=relay,
+ )
+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn
+ logger.warning("Partner consult failed (%s): %s", pid, exc, exc_info=True)
+ return ConsultResult(
+ session_id=session_key, success=False, error=str(exc), event_count=events
+ )
+
+ # Defensive: surface any tool call that never produced a result event so
+ # it isn't silently lost (every tool normally emits one).
+ for label in state["pending_tools"].values():
+ events += 1
+ await on_event(SubagentEvent(EVENT_TOOL, label))
+
+ reply = (reply or "").strip()
+ return ConsultResult(
+ final_text=reply,
+ session_id=session_key,
+ success=bool(reply),
+ event_count=events,
+ error="" if reply else "the partner produced no reply",
+ )
+
+
+def _to_subagent_events(
+ event: "StreamEvent",
+ state: dict[str, dict[str, str]],
+) -> list[SubagentEvent]:
+ """Map a partner chat-loop ``StreamEvent`` to zero or more subagent events.
+
+ Renders the partner's run like the CLI backends do — a tool call, its result,
+ streamed thinking and the streamed answer — so the sidebar reads as a faithful
+ transcript:
+
+ * ``CONTENT`` / ``THINKING`` arrive as incremental deltas, so we accumulate
+ per ``call_id`` (in ``state``) and emit the running full text under a
+ per-stream ``merge_id`` (the row grows in place, never overwritten by a
+ single chunk).
+ * A ``TOOL_CALL`` (name + args/query) and its ``TOOL_RESULT`` share a
+ ``call_id`` in the loop, but the loop dispatches tools in parallel, so the
+ calls and results don't interleave. We hold each call in
+ ``state["pending_tools"]`` and emit it immediately before its result, as
+ two adjacent rows — so every result sits under the call it belongs to.
+ * Pure status/bookkeeping (``PROGRESS`` call-status, ``RESULT`` marker,
+ ``DONE``/``SESSION*``) carries no trace value and is dropped.
+ """
+ from deeptutor.core.stream import StreamEventType
+
+ meta = event.metadata or {}
+ call_id = str(meta.get("call_id") or "")
+ text = event.content or ""
+ etype = event.type
+ pending = state["pending_tools"]
+
+ if etype == StreamEventType.CONTENT:
+ if not text:
+ return []
+ running = state["text"][call_id] = state["text"].get(call_id, "") + text
+ merge = {"merge_id": f"text:{call_id}"} if call_id else {}
+ return [SubagentEvent(EVENT_TEXT, running, meta=merge)]
+ if etype == StreamEventType.THINKING:
+ if not text.strip():
+ return []
+ running = state["reason"][call_id] = state["reason"].get(call_id, "") + text
+ merge = {"merge_id": f"reason:{call_id}"} if call_id else {}
+ return [SubagentEvent(EVENT_REASONING, running, meta=merge)]
+ if etype == StreamEventType.TOOL_CALL:
+ name = text.strip() or str(meta.get("tool_name") or "tool")
+ args = _compact(meta.get("args"))
+ label = f"{name} {args}" if args else name
+ if call_id:
+ # Defer: emit it right before its result so the pair stays adjacent.
+ pending[call_id] = label
+ return []
+ return [SubagentEvent(EVENT_TOOL, label)]
+ if etype == StreamEventType.TOOL_RESULT:
+ out = _flush_pending_call(pending, call_id)
+ body = text.strip()
+ if body:
+ out.append(SubagentEvent(EVENT_TOOL_RESULT, _truncate(body)))
+ return out
+ if etype == StreamEventType.ERROR:
+ # An error can close out a pending tool call — surface the call first.
+ out = _flush_pending_call(pending, call_id)
+ if text.strip():
+ out.append(SubagentEvent(EVENT_ERROR, text.strip()))
+ return out
+ # PROGRESS (call-status duplicates the tool rows), RESULT (final answer,
+ # returned separately), SOURCES, DONE, SESSION* and WAIT_FOR_INPUT carry no
+ # trace value here.
+ return []
+
+
+def _flush_pending_call(pending: dict[str, str], call_id: str) -> list[SubagentEvent]:
+ """Emit (and clear) the buffered tool-call row for ``call_id``, if any."""
+ label = pending.pop(call_id, "") if call_id else ""
+ return [SubagentEvent(EVENT_TOOL, label)] if label else []
+
+
+def _compact(args: object) -> str:
+ if not args:
+ return ""
+ import json
+
+ try:
+ text = json.dumps(args, ensure_ascii=False) if not isinstance(args, str) else args
+ except (TypeError, ValueError):
+ text = str(args)
+ return _truncate(text.strip())
+
+
+def _truncate(text: str) -> str:
+ return text if len(text) <= _MAX_LINE_CHARS else text[: _MAX_LINE_CHARS - 1] + "…"
+
+
+__all__ = ["PARTNER_BACKEND_KIND", "PartnerBackend"]
diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.py
index 157f92dc8..d00786662 100644
--- a/deeptutor/services/subagent/registry.py
+++ b/deeptutor/services/subagent/registry.py
@@ -1,7 +1,10 @@
"""Backend registry — the single place that knows which subagents exist.
-Add a new local agent CLI by writing a :class:`SubagentBackend` and listing it
-here; the capability, API and UI all discover it through these helpers.
+Add a new subagent by writing a :class:`SubagentBackend` and listing it here;
+the capability, API and UI all discover it through these helpers. Local-CLI
+backends (Claude Code / Codex) and the in-process partner backend live in the
+same registry but are told apart by ``local_cli`` — only CLIs are detected on
+the machine and offered in the connect-CLI modal.
"""
from __future__ import annotations
@@ -11,15 +14,17 @@ import asyncio
from deeptutor.services.subagent.base import SubagentBackend
from deeptutor.services.subagent.claude_code import ClaudeCodeBackend
from deeptutor.services.subagent.codex import CodexBackend
+from deeptutor.services.subagent.partner import PartnerBackend
from deeptutor.services.subagent.types import DetectResult
_BACKENDS: dict[str, SubagentBackend] = {
backend.kind: backend
- for backend in (ClaudeCodeBackend(), CodexBackend())
+ for backend in (ClaudeCodeBackend(), CodexBackend(), PartnerBackend())
}
def list_backend_kinds() -> list[str]:
+ """Every connectable backend kind (CLIs + partner)."""
return list(_BACKENDS.keys())
@@ -27,14 +32,24 @@ def get_backend(kind: str) -> SubagentBackend | None:
return _BACKENDS.get(str(kind or "").strip())
+def _cli_backends() -> list[SubagentBackend]:
+ return [b for b in _BACKENDS.values() if getattr(b, "local_cli", True)]
+
+
async def detect_all() -> list[DetectResult]:
- """Probe every backend for installability on this machine, concurrently."""
+ """Probe each local-CLI backend for installability on this machine.
+
+ Non-CLI backends (the partner backend) are skipped — they aren't installed,
+ they're connected from their own list — so this only ever returns the CLIs
+ the connect-CLI modal offers.
+ """
+ cli = _cli_backends()
results = await asyncio.gather(
- *(backend.detect() for backend in _BACKENDS.values()),
+ *(backend.detect() for backend in cli),
return_exceptions=True,
)
detections: list[DetectResult] = []
- for backend, result in zip(_BACKENDS.values(), results, strict=True):
+ for backend, result in zip(cli, results, strict=True):
if isinstance(result, DetectResult):
detections.append(result)
else:
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index ea260d1c2..75423ba87 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -14,6 +14,12 @@ from deeptutor.capabilities.subagent import SUBAGENT_TOOL_TYPES
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
from deeptutor.tools.exec_tool import ExecTool
from deeptutor.tools.media_gen_tool import ImagegenTool, VideogenTool
+from deeptutor.tools.partner_memory import (
+ PARTNER_BUILTIN_TOOL_NAMES,
+ PartnerMemorizeTool,
+ PartnerReadTool,
+ PartnerSearchTool,
+)
from deeptutor.tools.prompting import load_prompt_hints
logger = logging.getLogger(__name__)
@@ -1470,6 +1476,14 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
# capability runs the turn exclusively on it when a connected agent is the
# selected KB.
*SUBAGENT_TOOL_TYPES,
+ # Partner-only memory + history tools. Globally registered so schemas/API
+ # stay stable, but never mounted in product chat: the partner runtime
+ # force-mounts them (and suppresses chat's read_memory/write_memory) on
+ # every partner turn. Deliberately absent from CONFIGURABLE_BUILTIN_TOOL_NAMES
+ # — they are mandatory, not owner-configurable.
+ PartnerReadTool,
+ PartnerMemorizeTool,
+ PartnerSearchTool,
)
# No tools are parked right now. When a tool's implementation is being
@@ -1540,6 +1554,7 @@ __all__ = [
"COMING_SOON_TOOL_NAMES",
"COMING_SOON_TOOL_TYPES",
"CONFIGURABLE_BUILTIN_TOOL_NAMES",
+ "PARTNER_BUILTIN_TOOL_NAMES",
"TOOL_ALIASES",
"USER_TOGGLEABLE_TOOL_NAMES",
"AskUserTool",
@@ -1552,6 +1567,9 @@ __all__ = [
"VideogenTool",
"ListNotebookTool",
"PaperSearchToolWrapper",
+ "PartnerMemorizeTool",
+ "PartnerReadTool",
+ "PartnerSearchTool",
"RAGTool",
"LoadToolsTool",
"ReadMemoryTool",
diff --git a/deeptutor/tools/partner_memory.py b/deeptutor/tools/partner_memory.py
new file mode 100644
index 000000000..18a37d6c5
--- /dev/null
+++ b/deeptutor/tools/partner_memory.py
@@ -0,0 +1,307 @@
+"""Partner-only memory + history tools.
+
+A partner has a *split* memory model that the product chat does not:
+
+* its OWN long-term memory lives in the partner's synthetic workspace
+ (``data/partners/<id>/workspace/memory``) and is the only thing
+ ``partner_memorize`` ever writes to — a partner can never mutate the
+ owner's memory;
+* the OWNER's shared memory (the admin L3) is read-only context the
+ partner inherits, so ``partner_read`` returns *both* layers concatenated.
+
+These three tools replace the product chat's ``read_memory`` / ``write_memory``
+for partners (which are suppressed on partner turns) and add a keyword search
+over the partner's own conversation history. They are force-mounted by the
+partner runtime and never available in product chat, so — unlike the chat
+memory tools — they don't gate on ``user_has_memory`` and aren't configurable.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
+
+# Force-mounted on every partner turn (see ``compose_enabled_tools`` /
+# ``agentic_pipeline``). Single source of truth for the partner memory surface.
+PARTNER_BUILTIN_TOOL_NAMES: tuple[str, ...] = (
+ "partner_read",
+ "partner_memorize",
+ "partner_search",
+)
+
+_SNIPPET_WIDTH = 140
+_MAX_SCAN_MATCHES = 300
+
+
+def _concat_l3() -> str:
+ """Concatenate the active scope's L3 docs, or ``""`` when empty.
+
+ Resolves through ``memory_root()`` like the chat ``read_memory`` tool, so a
+ ``memory_path_service_override`` around the call decides whose memory this
+ reads. Unlike ``MemoryStore.read_l3_concat`` it returns an empty string
+ (not the chat placeholder) when nothing is stored, so the caller can label
+ the empty layer cleanly.
+ """
+ from deeptutor.services.memory import get_memory_store, paths
+
+ store = get_memory_store()
+ parts: list[str] = []
+ for slot in paths.L3_SLOTS:
+ body = store.read_raw("L3", slot).strip()
+ if body:
+ parts.append(body)
+ return "\n\n---\n\n".join(parts)
+
+
+def _resolve_partner_id() -> str | None:
+ """The active partner id, or ``None`` when not inside a partner scope."""
+ from deeptutor.multi_user.context import get_current_user_or_none
+ from deeptutor.services.partners.scope import PARTNER_USER_PREFIX
+
+ user = get_current_user_or_none()
+ user_id = user.scope.user_id if user and user.scope else ""
+ if not user_id.startswith(PARTNER_USER_PREFIX):
+ return None
+ return user_id[len(PARTNER_USER_PREFIX) :]
+
+
+def _snippet_around(content: str, needle_lower: str) -> str:
+ """A one-line window of *content* centred on the first match of *needle*."""
+ low = content.lower()
+ idx = low.find(needle_lower)
+ flat = " ".join(content.split())
+ if idx < 0:
+ return flat[:_SNIPPET_WIDTH]
+ # Re-find in the flattened text so offsets line up with what we slice.
+ flat_idx = flat.lower().find(needle_lower)
+ if flat_idx < 0:
+ return flat[:_SNIPPET_WIDTH]
+ half = _SNIPPET_WIDTH // 2
+ start = max(0, flat_idx - half)
+ end = min(len(flat), flat_idx + len(needle_lower) + half)
+ prefix = "…" if start > 0 else ""
+ suffix = "…" if end < len(flat) else ""
+ return f"{prefix}{flat[start:end].strip()}{suffix}"
+
+
+class PartnerReadTool(BaseTool):
+ """Read the partner's combined memory: the owner's shared L3 + the
+ partner's own L3. Partner-only; force-mounted by the partner runtime."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="partner_read",
+ description=(
+ "Read your memory: the owner's shared long-term memory plus your "
+ "own accumulated notes about this person. Use it to personalise "
+ "tone, depth, and examples — not on every turn, and not for "
+ "purely factual questions."
+ ),
+ parameters=[],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.multi_user.paths import (
+ get_admin_path_service,
+ get_current_path_service,
+ )
+ from deeptutor.services.memory import memory_path_service_override
+
+ with memory_path_service_override(get_admin_path_service()):
+ shared = _concat_l3()
+ with memory_path_service_override(get_current_path_service()):
+ own = _concat_l3()
+
+ sections = [
+ "## Shared memory (the owner's — read-only)\n\n"
+ + (shared or "(none yet)"),
+ "## Your own memory\n\n" + (own or "(none yet — use partner_memorize to add)"),
+ ]
+ text = "\n\n".join(sections)
+ return ToolResult(
+ content=text,
+ metadata={"char_count": len(text), "has_shared": bool(shared), "has_own": bool(own)},
+ )
+
+
+class PartnerMemorizeTool(BaseTool):
+ """Persist a note into the partner's OWN ``preferences`` doc. Never touches
+ the owner's memory. Partner-only; force-mounted by the partner runtime."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="partner_memorize",
+ description=(
+ "Save something worth remembering about this person to your own "
+ "long-term memory — a lasting preference, a recurring need, a "
+ "durable fact. Writes ONLY to your own memory, never the owner's. "
+ "Call when the user clearly states a preference or you learn "
+ "something durable — never speculate."
+ ),
+ parameters=[
+ ToolParameter(
+ name="op",
+ type="string",
+ description="`add` for a new note, `edit` to revise an existing one.",
+ enum=["add", "edit"],
+ required=True,
+ ),
+ ToolParameter(
+ name="text",
+ type="string",
+ description="The note, in the user's own words where possible. ≤ 240 chars.",
+ required=True,
+ ),
+ ToolParameter(
+ name="target_id",
+ type="string",
+ description="Existing entry id (form `m_xxx`). Required for `edit`.",
+ required=False,
+ ),
+ ToolParameter(
+ name="reason",
+ type="string",
+ description="Optional one-line note recorded in the memory log.",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.multi_user.paths import get_current_path_service
+ from deeptutor.services.memory import get_memory_store, memory_path_service_override
+ from deeptutor.services.memory.trace import TraceEvent
+
+ op = str(kwargs.get("op") or "").strip().lower()
+ text = str(kwargs.get("text") or "").strip()
+ target_id = kwargs.get("target_id")
+ reason = kwargs.get("reason")
+
+ if op not in {"add", "edit"}:
+ return ToolResult(
+ content=f"Error: op must be 'add' or 'edit', got {op!r}.", success=False
+ )
+ if not text:
+ return ToolResult(
+ content="Error: text is required and must be non-empty.", success=False
+ )
+
+ store = get_memory_store()
+ # Trace + preference both land in the partner's own memory scope, so the
+ # footnote ref resolves inside the same tree it's stored in.
+ with memory_path_service_override(get_current_path_service()):
+ event = TraceEvent.new(
+ "partner",
+ "preference_stated",
+ {"op": op, "text": text, "target_id": target_id, "reason": reason},
+ )
+ await store.emit(event)
+ report = await store.write_preference(
+ op=op, # type: ignore[arg-type]
+ text=text,
+ target_id=str(target_id).strip() if target_id else None,
+ reason=str(reason).strip() if reason else None,
+ trace_id=event.id,
+ )
+ if not report.accepted:
+ return ToolResult(
+ content=f"partner_memorize rejected: {report.reason}",
+ success=False,
+ metadata={"op": op},
+ )
+ entry_id = report.results[0].entry_id if report.results else None
+ return ToolResult(
+ content=f"noted ({op}, entry={entry_id or target_id}).",
+ metadata={"op": op, "entry_id": entry_id or target_id},
+ )
+
+
+class PartnerSearchTool(BaseTool):
+ """Keyword-search the partner's own past conversations (all sessions).
+ Partner-only; force-mounted by the partner runtime."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="partner_search",
+ description=(
+ "Search your past conversations with this person by keyword. "
+ "Returns matching message snippets with their session and time. "
+ "Use it to recall what you discussed before when memory isn't enough."
+ ),
+ parameters=[
+ ToolParameter(
+ name="query",
+ type="string",
+ description="Keyword or phrase to search for (case-insensitive).",
+ required=True,
+ ),
+ ToolParameter(
+ name="limit",
+ type="integer",
+ description="Max snippets to return (default 30, max 100).",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.partners.config.paths import get_partner_sessions_dir
+ from deeptutor.services.partners.sessions import PartnerSessionStore
+
+ query = str(kwargs.get("query") or "").strip()
+ if not query:
+ return ToolResult(content="Error: query is required.", success=False)
+ try:
+ limit = int(kwargs.get("limit") or 30)
+ except (TypeError, ValueError):
+ limit = 30
+ limit = max(1, min(limit, 100))
+
+ partner_id = _resolve_partner_id()
+ if partner_id is None:
+ return ToolResult(
+ content="Error: partner_search is only available inside a partner.",
+ success=False,
+ )
+
+ store = PartnerSessionStore(get_partner_sessions_dir(partner_id))
+ needle = query.lower()
+ # (timestamp, formatted_line) — collected across all sessions, then
+ # sorted most-recent-first and truncated to ``limit``.
+ matches: list[tuple[str, str]] = []
+ for summary in store.list_sessions():
+ key = str(summary.get("session_key") or "")
+ title = str(summary.get("title") or "") or "(untitled)"
+ for record in store.messages(key, limit=10000):
+ role = str(record.get("role") or "")
+ if role == "tool":
+ continue
+ content = str(record.get("content") or "")
+ if needle not in content.lower():
+ continue
+ ts = str(record.get("timestamp") or "")
+ snippet = _snippet_around(content, needle)
+ matches.append((ts, f"[{title} · {role} · {ts[:19]}] {snippet}"))
+ if len(matches) >= _MAX_SCAN_MATCHES:
+ break
+ if len(matches) >= _MAX_SCAN_MATCHES:
+ break
+
+ if not matches:
+ return ToolResult(
+ content=f"No past messages matched {query!r}.",
+ metadata={"query": query, "count": 0},
+ )
+ matches.sort(key=lambda m: m[0], reverse=True)
+ lines = [line for _, line in matches[:limit]]
+ text = "\n".join(lines)
+ return ToolResult(content=text, metadata={"query": query, "count": len(lines)})
+
+
+__all__ = [
+ "PARTNER_BUILTIN_TOOL_NAMES",
+ "PartnerMemorizeTool",
+ "PartnerReadTool",
+ "PartnerSearchTool",
+]
diff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.py
index 0966cc826..2008b9038 100644
--- a/tests/api/test_partners_router.py
+++ b/tests/api/test_partners_router.py
@@ -137,8 +137,12 @@ class TestConfigAndSoul:
body = client.get("/api/v1/partners/tool-options").json()
assert {"tools", "builtin_tools", "mcp_tools"} <= set(body)
builtin_names = {t["name"] for t in body["builtin_tools"]}
- # The memory tools are configurable built-ins now.
- assert {"rag", "read_memory", "write_memory"} <= builtin_names
+ # rag stays owner-configurable; the chat memory tools are NOT — partners
+ # use the mandatory partner_read / partner_memorize / partner_search
+ # instead, so they never surface in the partner config UI.
+ assert "rag" in builtin_names
+ assert "read_memory" not in builtin_names
+ assert "write_memory" not in builtin_names
def test_avatar_roundtrip_and_validation(self, client):
_create(client)
diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.py
index 9f2630b70..4fdf8e5c3 100644
--- a/tests/api/test_subagents_router.py
+++ b/tests/api/test_subagents_router.py
@@ -40,7 +40,9 @@ class _FakeKBManager:
def get_metadata(self, name: str | None = None) -> dict:
return dict(self.kbs.get(name or "", {}))
- def register_subagent_connection(self, name, agent_kind, *, cwd="", description=""):
+ def register_subagent_connection(
+ self, name, agent_kind, *, cwd="", partner_id="", description=""
+ ):
if name in self.kbs:
raise ValueError(f"A knowledge base named '{name}' already exists.")
entry = {
@@ -48,6 +50,7 @@ class _FakeKBManager:
"type": "subagent",
"agent_kind": agent_kind,
"cwd": cwd,
+ "partner_id": partner_id,
"description": description or f"Connected subagent: {name}",
}
self.kbs[name] = entry
@@ -62,7 +65,9 @@ class _FakeKBManager:
def client(monkeypatch, tmp_path):
manager = _FakeKBManager()
monkeypatch.setattr(subagents_module, "current_kb_manager", lambda: manager)
- monkeypatch.setattr(subagents_module, "list_backend_kinds", lambda: ["claude_code", "codex"])
+ monkeypatch.setattr(
+ subagents_module, "list_backend_kinds", lambda: ["claude_code", "codex", "partner"]
+ )
monkeypatch.setattr(subagents_module, "assert_path_allowed", lambda p: Path(p))
# Isolate settings persistence to a temp file — the PUT path otherwise
# writes the developer's real data/user/settings/subagent.json.
@@ -123,6 +128,57 @@ def test_connect_rejects_unknown_kind(client):
assert res.status_code == 400
+class _FakePartnerManagerForConnect:
+ def __init__(self, known: set[str]) -> None:
+ self._known = known
+
+ def partner_exists(self, pid: str) -> bool:
+ return pid in self._known
+
+
+def _patch_partner_existence(monkeypatch, known: set[str]) -> None:
+ import deeptutor.services.partners as partners_pkg
+
+ monkeypatch.setattr(
+ partners_pkg, "get_partner_manager", lambda: _FakePartnerManagerForConnect(known)
+ )
+
+
+def test_connect_partner_binds_partner_id(client, monkeypatch):
+ _patch_partner_existence(monkeypatch, {"paul"})
+ created = client.post(
+ "/api/v1/subagents/connections",
+ json={"name": "Paul", "agent_kind": "partner", "partner_id": "paul"},
+ )
+ assert created.status_code == 200
+ body = created.json()
+ assert body["agent_kind"] == "partner"
+ assert body["partner_id"] == "paul"
+ assert body["cwd"] == ""
+
+ listed = client.get("/api/v1/subagents/connections").json()["connections"]
+ assert listed[0]["agent_kind"] == "partner"
+ assert listed[0]["partner_id"] == "paul"
+
+
+def test_connect_partner_requires_partner_id(client, monkeypatch):
+ _patch_partner_existence(monkeypatch, {"paul"})
+ res = client.post(
+ "/api/v1/subagents/connections",
+ json={"name": "Paul", "agent_kind": "partner"},
+ )
+ assert res.status_code == 400
+
+
+def test_connect_partner_rejects_unknown_partner(client, monkeypatch):
+ _patch_partner_existence(monkeypatch, set())
+ res = client.post(
+ "/api/v1/subagents/connections",
+ json={"name": "Ghost", "agent_kind": "partner", "partner_id": "ghost"},
+ )
+ assert res.status_code == 400
+
+
def test_disconnect_unknown_is_404(client):
res = client.delete("/api/v1/subagents/connections/nope")
assert res.status_code == 404
@@ -175,7 +231,9 @@ def test_message_connection_streams_and_persists(client, monkeypatch, tmp_path):
class _FakeBackend:
kind = "claude_code"
- async def consult(self, message, *, on_event, cwd, session_id, config, images=None):
+ async def consult(
+ self, message, *, on_event, cwd, session_id, config, images=None, partner_id=None
+ ):
await on_event(SubagentEvent(kind="text", text="hi", meta={"merge_id": "txt:m:0"}))
return ConsultResult(final_text="hi", session_id="sess-9", success=True, event_count=1)
diff --git a/tests/capabilities/test_subagent_capability.py b/tests/capabilities/test_subagent_capability.py
index 616a4c4d7..eb353fbd1 100644
--- a/tests/capabilities/test_subagent_capability.py
+++ b/tests/capabilities/test_subagent_capability.py
@@ -141,7 +141,9 @@ class _FakeBackend:
self.calls: list[tuple[str, str | None]] = []
self.last_images: list[str] | None = None
- async def consult(self, question, *, on_event, cwd, session_id, config, images=None):
+ async def consult(
+ self, question, *, on_event, cwd, session_id, config, images=None, partner_id=None
+ ):
self.calls.append((question, session_id))
self.last_images = images
await on_event(SubagentEvent(kind="tool", text="$ ls"))
diff --git a/tests/knowledge/test_subagent_connection_kb.py b/tests/knowledge/test_subagent_connection_kb.py
new file mode 100644
index 000000000..88f5c7754
--- /dev/null
+++ b/tests/knowledge/test_subagent_connection_kb.py
@@ -0,0 +1,43 @@
+"""Manager handling of connected-subagent KBs (``type: subagent`` pointers).
+
+A subagent connection records the backend (``agent_kind``) and its target — a
+``cwd`` for a local CLI, or a ``partner_id`` for a partner. Like the other
+connected types it creates no folder and runs no index. The critical contract
+exercised here: ``get_metadata`` must surface ``partner_id`` — the subagent
+binding reads it from there to drive the right partner, so dropping it silently
+breaks partner consults ("No partner is bound to this connection").
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def test_register_partner_connection_round_trips_partner_id(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+
+ entry = manager.register_subagent_connection("Panda Kate", "partner", partner_id="panda-kate")
+ assert entry["type"] == "subagent"
+ assert entry["agent_kind"] == "partner"
+ assert entry["partner_id"] == "panda-kate"
+ assert entry["cwd"] == ""
+ # No KB folder is created under base_dir.
+ assert not (manager.base_dir / "Panda Kate").exists()
+
+ # The binding resolves the partner through get_metadata — it MUST carry it.
+ meta = manager.get_metadata("Panda Kate")
+ assert meta["type"] == "subagent"
+ assert meta["agent_kind"] == "partner"
+ assert meta["partner_id"] == "panda-kate"
+
+
+def test_register_cli_connection_has_no_partner_id(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+
+ manager.register_subagent_connection("MyClaude", "claude_code", cwd="")
+ meta = manager.get_metadata("MyClaude")
+ assert meta["agent_kind"] == "claude_code"
+ # Empty partner_id is dropped from the curated metadata (None-stripped).
+ assert "partner_id" not in meta or not meta["partner_id"]
diff --git a/tests/services/partners/test_partner_memory_tools.py b/tests/services/partners/test_partner_memory_tools.py
new file mode 100644
index 000000000..90c3962e9
--- /dev/null
+++ b/tests/services/partners/test_partner_memory_tools.py
@@ -0,0 +1,142 @@
+"""Partner-only memory + history tools.
+
+Covers the split-memory model: ``partner_memorize`` writes ONLY the partner's
+own memory (never the owner's), ``partner_read`` folds the owner's shared L3 on
+top of the partner's own, and ``partner_search`` greps the partner's sessions.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from deeptutor.multi_user.paths import get_admin_path_service, user_context
+from deeptutor.partners.config.paths import get_partner_sessions_dir, get_partner_workspace
+from deeptutor.services.partners.scope import partner_user
+from deeptutor.services.partners.sessions import PartnerSessionStore
+from deeptutor.tools.partner_memory import (
+ PartnerMemorizeTool,
+ PartnerReadTool,
+ PartnerSearchTool,
+)
+
+PID = "alice"
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
[email protected](autouse=True)
+def _fresh_memory_singleton(monkeypatch):
+ """Each test gets a fresh MemoryStore so its write locks don't leak."""
+ from deeptutor.services.memory import store
+
+ monkeypatch.setattr(store, "_singleton", None)
+
+
+def _write_owner_preference(text: str) -> None:
+ """Seed the owner's (admin) L3 preferences directly on disk."""
+ admin_mem = get_admin_path_service().get_memory_dir()
+ pref = admin_mem / "L3" / "preferences.md"
+ pref.parent.mkdir(parents=True, exist_ok=True)
+ pref.write_text(f"# Preferences\n\n## Preferences\n- {text}\n", encoding="utf-8")
+
+
+def test_memorize_writes_own_not_owner(partners_root: Path) -> None:
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(
+ PartnerMemorizeTool().execute(op="add", text="prefers terse answers")
+ )
+ assert result.success, result.content
+
+ own_pref = get_partner_workspace(PID) / "memory" / "L3" / "preferences.md"
+ assert own_pref.exists()
+ assert "prefers terse answers" in own_pref.read_text(encoding="utf-8")
+
+ # The owner's memory must be untouched.
+ admin_pref = get_admin_path_service().get_memory_dir() / "L3" / "preferences.md"
+ assert not admin_pref.exists()
+
+
+def test_read_concats_owner_and_own(partners_root: Path) -> None:
+ _write_owner_preference("owner wants formal tone")
+ with user_context(partner_user(PID, name="Alice")):
+ _run(PartnerMemorizeTool().execute(op="add", text="alice likes calculus examples"))
+ result = _run(PartnerReadTool().execute())
+
+ assert "Shared memory" in result.content
+ assert "Your own memory" in result.content
+ assert "owner wants formal tone" in result.content
+ assert "alice likes calculus examples" in result.content
+ assert result.metadata["has_shared"] is True
+ assert result.metadata["has_own"] is True
+
+
+def test_read_labels_empty_layers(partners_root: Path) -> None:
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(PartnerReadTool().execute())
+ assert "(none yet" in result.content
+ assert result.metadata["has_shared"] is False
+ assert result.metadata["has_own"] is False
+
+
+def test_read_own_does_not_leak_into_owner(partners_root: Path) -> None:
+ """A partner's own note must not appear under the shared (owner) section."""
+ with user_context(partner_user(PID, name="Alice")):
+ _run(PartnerMemorizeTool().execute(op="add", text="secret partner note"))
+ result = _run(PartnerReadTool().execute())
+ shared_part, _, own_part = result.content.partition("## Your own memory")
+ assert "secret partner note" not in shared_part
+ assert "secret partner note" in own_part
+
+
+def test_search_matches_history(partners_root: Path) -> None:
+ store = PartnerSessionStore(get_partner_sessions_dir(PID))
+ store.append("s1", "user", "Can you explain calculus limits to me?")
+ store.append("s1", "assistant", "Sure — a limit describes the value a function approaches.")
+ store.append("s2", "user", "Let's talk about linear algebra instead.")
+
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(PartnerSearchTool().execute(query="calculus"))
+
+ assert result.success
+ assert result.metadata["count"] == 1
+ assert "calculus limits" in result.content
+
+
+def test_search_skips_tool_messages(partners_root: Path) -> None:
+ store = PartnerSessionStore(get_partner_sessions_dir(PID))
+ store.append("s1", "tool", "calculus tool payload noise")
+ store.append("s1", "user", "real question about calculus")
+
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(PartnerSearchTool().execute(query="calculus"))
+ assert result.metadata["count"] == 1
+ assert "real question" in result.content
+
+
+def test_search_no_match(partners_root: Path) -> None:
+ store = PartnerSessionStore(get_partner_sessions_dir(PID))
+ store.append("s1", "user", "hello there")
+
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(PartnerSearchTool().execute(query="nonexistent-term"))
+ assert result.metadata["count"] == 0
+ assert "No past messages matched" in result.content
+
+
+def test_search_requires_partner_scope(partners_root: Path) -> None:
+ # No partner user_context → the admin/local scope is active.
+ result = _run(PartnerSearchTool().execute(query="anything"))
+ assert not result.success
+ assert "only available inside a partner" in result.content
+
+
+def test_memorize_rejects_bad_op(partners_root: Path) -> None:
+ with user_context(partner_user(PID, name="Alice")):
+ result = _run(PartnerMemorizeTool().execute(op="delete", text="x"))
+ assert not result.success
+ assert "op must be" in result.content
diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py
index 37078f65e..0f0b3bf82 100644
--- a/tests/services/partners/test_partner_runtime.py
+++ b/tests/services/partners/test_partner_runtime.py
@@ -446,20 +446,22 @@ class TestBuiltinToolsAndMemory:
assert context.allowed_builtin_tools == ["rag", "web_fetch"]
@pytest.mark.asyncio
- async def test_turn_runs_against_owner_memory(self, partners_root, fake_orchestrator):
- """The turn resolves memory to the admin (owner) workspace, not the
- partner's own empty scope — so read_memory can know the user."""
- from deeptutor.multi_user.paths import get_admin_path_service
+ async def test_turn_runs_against_partner_memory(self, partners_root, fake_orchestrator):
+ """The turn resolves memory to the partner's OWN synthetic workspace, not
+ the owner's. The partner_* tools (force-mounted) own the split-memory
+ model: partner_read folds in the owner's shared L3 on top, while
+ partner_memorize writes only the partner's own scope."""
+ from deeptutor.partners.config.paths import get_partner_workspace
fake_orchestrator.script = _finish("ok")
runner = _runner(partners_root)
await runner.process_message(_msg())
- admin_memory = get_admin_path_service().get_memory_dir().resolve()
+ partner_memory = (get_partner_workspace("ada") / "memory").resolve()
seen = fake_orchestrator.seen_memory_roots[0].resolve()
- assert seen == admin_memory
- assert "partners" not in seen.parts # NOT the partner's own scope
+ assert seen == partner_memory
+ assert "partners" in seen.parts # the partner's own scope, NOT admin
@pytest.mark.asyncio
async def test_memory_override_is_reset_after_turn(self, partners_root, fake_orchestrator):
diff --git a/tests/services/session/test_source_inventory.py b/tests/services/session/test_source_inventory.py
index 61f3506fb..136a4927b 100644
--- a/tests/services/session/test_source_inventory.py
+++ b/tests/services/session/test_source_inventory.py
@@ -418,3 +418,89 @@ def test_serialize_returns_empty_when_no_content() -> None:
meta = {"session_id": "imported_x"}
assert serialize_referenced_transcript(meta, [{"role": "user", "content": " "}]) == ""
assert serialize_referenced_transcript(meta, []) == ""
+
+
+# ---------------------------------------------------------------------------
+# Partner session references (partner:{pid}:{session_key})
+# ---------------------------------------------------------------------------
+
+
+def test_serialize_partner_transcript_uses_partner_name() -> None:
+ """A partner transcript is framed as a third party under the partner's own
+ name (not the generic 'external AI assistant')."""
+ meta = {"preferences": {"import": {"source": "partner"}}, "partner_name": "Panda Kate"}
+ out = serialize_referenced_transcript(
+ meta, [{"role": "assistant", "content": "hi"}], language="en"
+ )
+ assert "Panda Kate" in out
+ assert "## Panda Kate" in out
+
+
+class _FakePartnerManager:
+ def __init__(self, *, exists=True, messages=None, name="Panda Kate") -> None:
+ self._exists = exists
+ self._messages = messages or []
+ self._name = name
+
+ def partner_exists(self, pid):
+ return self._exists
+
+ def get_history(self, pid, *, session_key, limit=100):
+ return list(self._messages)
+
+ def load_config(self, pid):
+ cfg = type("Cfg", (), {})()
+ cfg.name = self._name
+ return cfg
+
+
+def _patch_partner(monkeypatch, manager, *, is_admin=True):
+ import deeptutor.multi_user.context as ctx
+ import deeptutor.services.partners as partners_pkg
+
+ monkeypatch.setattr(partners_pkg, "get_partner_manager", lambda: manager)
+ user = type("U", (), {"is_admin": is_admin})()
+ monkeypatch.setattr(ctx, "get_current_user", lambda: user)
+
+
+async def test_load_history_session_resolves_partner_reference(monkeypatch) -> None:
+ from deeptutor.services.session.source_inventory import _load_history_session
+
+ manager = _FakePartnerManager(
+ messages=[
+ {"role": "user", "content": "我最近做了什么"},
+ {"role": "assistant", "content": "你最近在配置 DeepTutor。"},
+ ]
+ )
+ _patch_partner(monkeypatch, manager, is_admin=True)
+
+ # The session_key itself contains a colon (web:abc) — only the pid is split.
+ text, title = await _load_history_session(
+ FakeStore(), "partner:panda-kate:web:abc", language="zh"
+ )
+ assert "Panda Kate" in text # framed under the partner's name
+ assert "我最近做了什么" in text
+ assert title == "我最近做了什么"
+
+
+async def test_load_history_session_partner_blocked_for_non_admin(monkeypatch) -> None:
+ from deeptutor.services.session.source_inventory import _load_history_session
+
+ manager = _FakePartnerManager(messages=[{"role": "user", "content": "secret"}])
+ _patch_partner(monkeypatch, manager, is_admin=False)
+
+ text, title = await _load_history_session(FakeStore(), "partner:paul:dt-1", language="en")
+ assert text == "" and title == "" # partner data is admin-scoped
+
+
+async def test_load_history_session_partner_missing_returns_empty(monkeypatch) -> None:
+ from deeptutor.services.session.source_inventory import _load_history_session
+
+ manager = _FakePartnerManager(exists=False)
+ _patch_partner(monkeypatch, manager, is_admin=True)
+
+ text, _ = await _load_history_session(FakeStore(), "partner:ghost:dt-1")
+ assert text == ""
diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.py
index 1c43463c2..1604b016e 100644
--- a/tests/services/test_subagent_backends.py
+++ b/tests/services/test_subagent_backends.py
@@ -592,3 +592,278 @@ async def test_codex_options_tolerate_missing_cache(monkeypatch, tmp_path) -> No
assert codex.available is False
assert codex.models == []
assert codex.allow_custom_model is True
+
+
+# ---- registry: partner backend is registered but not a local CLI -------------
+
+
+def test_registry_partner_is_non_cli_backend() -> None:
+ from deeptutor.services.subagent import PARTNER_BACKEND_KIND, get_backend, list_backend_kinds
+
+ assert PARTNER_BACKEND_KIND in list_backend_kinds()
+ backend = get_backend(PARTNER_BACKEND_KIND)
+ assert backend is not None
+ assert backend.local_cli is False
+ assert get_backend("claude_code").local_cli is True
+
+
+async def test_detect_all_excludes_partner_backend() -> None:
+ from deeptutor.services.subagent import detect_all
+
+ kinds = {d.kind for d in await detect_all()}
+ assert "partner" not in kinds
+ assert kinds <= {"claude_code", "codex"}
+
+
+# ---- partner backend: drive a partner as a subagent --------------------------
+
+
+class _FakePartnerInstance:
+ def __init__(self, running: bool = True) -> None:
+ self.running = running
+
+
+class _FakePartnerManager:
+ """Stands in for the partner manager: records calls, scripts a reply/trace."""
+
+ def __init__(self, *, exists: bool = True, running: bool = True, reply: str = "Hi from partner.") -> None:
+ self._exists = exists
+ self._running = running
+ self._reply = reply
+ self.started: list[str] = []
+ self.sent: list[dict] = []
+ self._trace: list = []
+
+ def script_trace(self, events: list) -> None:
+ self._trace = events
+
+ def partner_exists(self, pid: str) -> bool:
+ return self._exists
+
+ def get_partner(self, pid: str):
+ return _FakePartnerInstance(self._running) if self._running else None
+
+ async def start_partner(self, pid: str):
+ self.started.append(pid)
+ self._running = True
+ return _FakePartnerInstance(True)
+
+ async def send_message(self, pid, content, *, session_key, media=None, on_event=None):
+ self.sent.append(
+ {"pid": pid, "content": content, "session_key": session_key, "media": media or []}
+ )
+ if on_event is not None:
+ for ev in self._trace:
+ await on_event(ev)
+ return self._reply
+
+
+def _patch_manager(monkeypatch, manager) -> None:
+ import deeptutor.services.partners as partners_pkg
+
+ monkeypatch.setattr(partners_pkg, "get_partner_manager", lambda: manager)
+
+
+async def test_partner_consult_mints_session_key_and_returns_reply(monkeypatch) -> None:
+ from deeptutor.core.stream import StreamEvent, StreamEventType
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ manager = _FakePartnerManager(reply="The answer.")
+ manager.script_trace(
+ [
+ StreamEvent(type=StreamEventType.THINKING, content="thinking…"),
+ StreamEvent(type=StreamEventType.TOOL_CALL, content="web_search", metadata={"call_id": "c1", "args": {"q": "x"}}),
+ StreamEvent(type=StreamEventType.CONTENT, content="The answer.", metadata={"call_id": "c2"}),
+ StreamEvent(type=StreamEventType.DONE), # bookkeeping → dropped
+ ]
+ )
+ _patch_manager(monkeypatch, manager)
+
+ emitted: list[tuple[str, str]] = []
+
+ async def on_event(ev):
+ emitted.append((ev.kind, ev.text))
+
+ result = await PartnerBackend().consult("hello", on_event=on_event, partner_id="paul")
+
+ assert result.success is True
+ assert result.final_text == "The answer."
+ # First consult mints a fresh, colon-free partner session key …
+ assert result.session_id.startswith("dt-")
+ # … and send_message used exactly that key.
+ assert manager.sent[0]["session_key"] == result.session_id
+ assert manager.sent[0]["pid"] == "paul"
+ # The substantive trace is forwarded; the DONE marker is dropped.
+ kinds = [k for k, _ in emitted]
+ assert "reasoning" in kinds and "tool" in kinds and "text" in kinds
+ assert result.event_count == 3
+
+
+async def test_partner_consult_resumes_given_session(monkeypatch) -> None:
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ manager = _FakePartnerManager()
+ _patch_manager(monkeypatch, manager)
+
+ async def on_event(ev):
+ pass
+
+ result = await PartnerBackend().consult(
+ "again", on_event=on_event, partner_id="paul", session_id="dt-abc123"
+ )
+ # A remembered key is reused verbatim — the partner session continues.
+ assert result.session_id == "dt-abc123"
+ assert manager.sent[0]["session_key"] == "dt-abc123"
+
+
+async def test_partner_consult_starts_partner_when_idle(monkeypatch) -> None:
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ manager = _FakePartnerManager(running=False)
+ _patch_manager(monkeypatch, manager)
+
+ async def on_event(ev):
+ pass
+
+ await PartnerBackend().consult("q", on_event=on_event, partner_id="paul")
+ assert manager.started == ["paul"] # brought online before messaging
+
+
+async def test_partner_consult_requires_partner_id() -> None:
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ async def on_event(ev):
+ pass
+
+ result = await PartnerBackend().consult("q", on_event=on_event)
+ assert result.success is False
+ assert "partner" in result.error.lower()
+
+
+async def test_partner_consult_unknown_partner(monkeypatch) -> None:
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ manager = _FakePartnerManager(exists=False)
+ _patch_manager(monkeypatch, manager)
+
+ async def on_event(ev):
+ pass
+
+ result = await PartnerBackend().consult("q", on_event=on_event, partner_id="ghost")
+ assert result.success is False
+ assert manager.sent == [] # never messaged a non-existent partner
+
+
+async def test_partner_consult_empty_reply_is_unsuccessful(monkeypatch) -> None:
+ from deeptutor.services.subagent.partner import PartnerBackend
+
+ manager = _FakePartnerManager(reply="")
+ _patch_manager(monkeypatch, manager)
+
+ async def on_event(ev):
+ pass
+
+ result = await PartnerBackend().consult("q", on_event=on_event, partner_id="paul")
+ assert result.success is False
+ assert result.final_text == ""
+
+
+def _partner_trace_state() -> dict[str, dict[str, str]]:
+ return {"text": {}, "reason": {}, "pending_tools": {}}
+
+
+def test_partner_event_mapping_covers_channels() -> None:
+ from deeptutor.core.stream import StreamEvent, StreamEventType
+ from deeptutor.services.subagent.partner import _to_subagent_events
+
+ def kinds(etype, **kw):
+ return [
+ e.kind
+ for e in _to_subagent_events(StreamEvent(type=etype, **kw), _partner_trace_state())
+ ]
+
+ assert kinds(StreamEventType.CONTENT, content="hi") == ["text"]
+ assert kinds(StreamEventType.THINKING, content="plan") == ["reasoning"]
+ # A tool call without a call_id can't be paired -> emitted immediately.
+ assert kinds(StreamEventType.TOOL_CALL, content="rag") == ["tool"]
+ # A tool result with no buffered call -> just the result row.
+ assert kinds(StreamEventType.TOOL_RESULT, content="rows") == ["tool_result"]
+ assert kinds(StreamEventType.ERROR, content="boom") == ["error"]
+ # Status / bookkeeping markers are dropped (the tool rows already carry the
+ # substance - keeping the trace clean like the CLI backends).
+ assert kinds(StreamEventType.PROGRESS, content="step 1") == []
+ assert kinds(StreamEventType.RESULT, content="final") == []
+ assert kinds(StreamEventType.DONE) == []
+ # Only a truly-empty CONTENT delta is dropped; whitespace is preserved so
+ # streamed spacing survives the accumulation.
+ assert kinds(StreamEventType.CONTENT, content="") == []
+ assert kinds(StreamEventType.CONTENT, content=" ") == ["text"]
+
+
+def test_partner_tool_call_pairs_with_its_result_adjacently() -> None:
+ # The loop dispatches tools in parallel - both TOOL_CALL events, then both
+ # TOOL_RESULT events - sharing a call_id per tool. Each call is buffered and
+ # re-emitted right before its own result, so the trace reads as adjacent
+ # call -> result pairs (never two calls then two results).
+ from deeptutor.core.stream import StreamEvent, StreamEventType
+ from deeptutor.services.subagent.partner import _to_subagent_events
+
+ st = _partner_trace_state()
+ a = _to_subagent_events(
+ StreamEvent(
+ type=StreamEventType.TOOL_CALL,
+ content="partner_search",
+ metadata={"call_id": "c1", "args": {"query": "Agentic RAG"}},
+ ),
+ st,
+ )
+ b = _to_subagent_events(
+ StreamEvent(
+ type=StreamEventType.TOOL_CALL,
+ content="read_skill",
+ metadata={"call_id": "c2", "args": {"name": "x"}},
+ ),
+ st,
+ )
+ assert a == [] and b == [] # both deferred until their results
+
+ r1 = _to_subagent_events(
+ StreamEvent(type=StreamEventType.TOOL_RESULT, content="hits", metadata={"call_id": "c1"}),
+ st,
+ )
+ assert [e.kind for e in r1] == ["tool", "tool_result"]
+ assert "partner_search" in r1[0].text and "Agentic RAG" in r1[0].text
+ assert r1[1].text == "hits"
+
+ r2 = _to_subagent_events(
+ StreamEvent(type=StreamEventType.TOOL_RESULT, content="body", metadata={"call_id": "c2"}),
+ st,
+ )
+ assert [e.kind for e in r2] == ["tool", "tool_result"]
+ assert "read_skill" in r2[0].text
+ # No shared merge_id - each call and result is its own row.
+ assert not any(e.meta.get("merge_id") for e in r1 + r2)
+
+
+def test_partner_content_accumulates_cumulatively() -> None:
+ # Incremental CONTENT deltas accumulate into a growing full-text row under a
+ # stable merge_id - so the streamed answer never gets wiped by a new chunk.
+ from deeptutor.core.stream import StreamEvent, StreamEventType
+ from deeptutor.services.subagent.partner import _to_subagent_events
+
+ st = _partner_trace_state()
+ a = _to_subagent_events(
+ StreamEvent(type=StreamEventType.CONTENT, content="The ", metadata={"call_id": "f1"}), st
+ )
+ b = _to_subagent_events(
+ StreamEvent(type=StreamEventType.CONTENT, content="answer", metadata={"call_id": "f1"}), st
+ )
+ assert a[0].text == "The " and b[0].text == "The answer"
+ assert a[0].meta["merge_id"] == b[0].meta["merge_id"] == "text:f1"
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index a33e6cfdb..8041bd55c 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -285,7 +285,7 @@ interface KnowledgeBase {
metadata?: {
/** Connected-source kind, e.g. "obsidian" | "subagent". */
type?: string;
- /** Backend of a connected subagent: "claude_code" | "codex". */
+ /** Backend of a connected subagent: "claude_code" | "codex" | "partner". */
agent_kind?: string;
};
}
diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsx
index b39f9acf9..332998c3d 100644
--- a/web/components/agents/ConnectedAgents.tsx
+++ b/web/components/agents/ConnectedAgents.tsx
@@ -5,7 +5,9 @@ import { useTranslation } from "react-i18next";
import { Cpu, Loader2, Plug, Plus, Trash2, X } from "lucide-react";
import { agentGlyph } from "@/components/agents/agent-icons";
+import PartnerAvatar from "@/components/partners/PartnerAvatar";
import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
+import { listPartners, type PartnerInfo } from "@/lib/partners-api";
import {
connectSubagent,
detectSubagents,
@@ -16,19 +18,23 @@ import {
} from "@/lib/subagents-api";
/**
- * Connected agents — live Claude Code / Codex on the user's machine, registered
- * as pointers the chat composer can select and consult in real time. Distinct
- * from the imported-history agents below it: those replay past transcripts,
- * these drive the local CLI now. Detection is machine-global (is the CLI
- * installed here); if nothing is detected the connect action stays out of the
- * way with a one-line hint.
+ * Connected agents — live agents the chat composer can select and consult in
+ * real time: Claude Code / Codex on the user's machine, or one of their
+ * partners. Distinct from the imported-history agents below it: those replay
+ * past transcripts, these drive the live agent now. CLI detection is
+ * machine-global (is the CLI installed here); partners come from the user's
+ * partner list. Consulting a partner opens a fresh session on it — every
+ * consult within one DeepTutor chat is archived as one partner session.
*/
+const PARTNER_KIND = "partner";
+
type Lang = { zh: string; en: string };
-function backendLabel(kind: string): string {
+function backendLabel(kind: string, tr: (l: Lang) => string): string {
if (kind === "claude_code") return "Claude Code";
if (kind === "codex") return "Codex";
+ if (kind === PARTNER_KIND) return tr({ zh: "伙伴", en: "Partner" });
return kind;
}
@@ -39,6 +45,7 @@ export default function ConnectedAgents() {
const [backends, setBackends] = useState<SubagentBackendInfo[]>([]);
const [connections, setConnections] = useState<SubagentConnection[]>([]);
+ const [partners, setPartners] = useState<PartnerInfo[]>([]);
const [loading, setLoading] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [busyName, setBusyName] = useState<string | null>(null);
@@ -46,12 +53,14 @@ export default function ConnectedAgents() {
const load = useCallback(async () => {
setLoading(true);
try {
- const [detected, conns] = await Promise.all([
+ const [detected, conns, parts] = await Promise.all([
detectSubagents().catch(() => [] as SubagentBackendInfo[]),
listSubagentConnections().catch(() => [] as SubagentConnection[]),
+ listPartners().catch(() => [] as PartnerInfo[]),
]);
setBackends(detected);
setConnections(conns);
+ setPartners(parts);
} finally {
setLoading(false);
}
@@ -65,6 +74,12 @@ export default function ConnectedAgents() {
() => backends.filter((b) => b.available),
[backends],
);
+ // Something is connectable when a CLI is installed here or a partner exists.
+ const canConnect = available.length > 0 || partners.length > 0;
+ const partnerName = useCallback(
+ (id: string) => partners.find((p) => p.partner_id === id)?.name || id,
+ [partners],
+ );
const handleDisconnect = useCallback(
async (name: string) => {
@@ -94,11 +109,11 @@ export default function ConnectedAgents() {
icon={Plug}
title={tr({ zh: "连接的智能体", en: "Connected agents" })}
description={tr({
- zh: "把本机已配置的 Claude Code / Codex 接进来,在对话中选中后直接向它提问 —— 它的完整运行过程会实时展示。",
- en: "Bring in the Claude Code / Codex configured on this machine — select one in chat to consult it directly, with its full run shown live.",
+ zh: "把本机的 Claude Code / Codex 或你的伙伴接进来,在对话中选中后直接向它提问 —— 它的完整运行过程会实时展示。",
+ en: "Bring in the Claude Code / Codex on this machine, or one of your partners — select one in chat to consult it directly, with its full run shown live.",
})}
action={
- available.length > 0 ? (
+ canConnect ? (
<button
type="button"
onClick={() => setModalOpen(true)}
@@ -116,39 +131,62 @@ export default function ConnectedAgents() {
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{tr({ zh: "检测本机智能体…", en: "Detecting local agents…" })}
</div>
- ) : available.length === 0 ? (
+ ) : !canConnect ? (
<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
{tr({
- zh: "未在本机检测到 Claude Code 或 Codex。安装并登录其中任一 CLI 后即可连接。",
- en: "No Claude Code or Codex detected on this machine. Install and log in to either CLI to connect one.",
+ zh: "未在本机检测到 Claude Code 或 Codex,也还没有任何伙伴。安装并登录其中任一 CLI,或在「伙伴」里新建一个,即可连接。",
+ en: "No Claude Code or Codex detected on this machine, and no partners yet. Install and log in to either CLI, or create a partner, to connect one.",
})}
</div>
) : connections.length === 0 ? (
<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
{tr({
- zh: "尚未连接任何智能体。点击「连接智能体」把本机的 Claude Code / Codex 接进来。",
- en: "No agents connected yet. Click “Connect agent” to bring in your local Claude Code / Codex.",
+ zh: "尚未连接任何智能体。点击「连接智能体」把本机的 Claude Code / Codex 或你的伙伴接进来。",
+ en: "No agents connected yet. Click “Connect agent” to bring in your local Claude Code / Codex, or a partner.",
})}
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2">
{connections.map((conn) => {
const Glyph = agentGlyph(conn.agent_kind);
+ // A partner connection wears its own face (the avatar set on the
+ // partner page), not the generic heart glyph.
+ const partner =
+ conn.agent_kind === PARTNER_KIND
+ ? partners.find((p) => p.partner_id === conn.partner_id)
+ : undefined;
return (
<div
key={conn.name}
className="group flex items-center gap-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] px-4 py-3"
>
- <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-[var(--border)]/60 bg-[var(--background)] text-[var(--foreground)]">
- {Glyph ? <Glyph size={20} /> : <Cpu size={18} strokeWidth={1.6} />}
- </span>
+ {partner ? (
+ <PartnerAvatar
+ name={partner.name}
+ emoji={partner.emoji}
+ color={partner.color}
+ image={partner.avatar}
+ size={40}
+ className="shrink-0"
+ />
+ ) : (
+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-[var(--border)]/60 bg-[var(--background)] text-[var(--foreground)]">
+ {Glyph ? <Glyph size={20} /> : <Cpu size={18} strokeWidth={1.6} />}
+ </span>
+ )}
<div className="min-w-0 flex-1">
<div className="truncate text-[13.5px] font-semibold tracking-tight text-[var(--foreground)]">
{conn.name}
</div>
<div className="mt-0.5 truncate text-[11.5px] text-[var(--muted-foreground)]">
- {backendLabel(conn.agent_kind)}
- {conn.cwd ? ` · ${conn.cwd}` : ""}
+ {backendLabel(conn.agent_kind, tr)}
+ {conn.agent_kind === PARTNER_KIND
+ ? conn.partner_id
+ ? ` · ${partnerName(conn.partner_id)}`
+ : ""
+ : conn.cwd
+ ? ` · ${conn.cwd}`
+ : ""}
</div>
</div>
<button
@@ -174,6 +212,7 @@ export default function ConnectedAgents() {
{modalOpen && (
<ConnectModal
backends={available}
+ partners={partners}
existingNames={connections.map((c) => c.name)}
tr={tr}
onClose={() => setModalOpen(false)}
@@ -189,23 +228,48 @@ export default function ConnectedAgents() {
function ConnectModal({
backends,
+ partners,
existingNames,
tr,
onClose,
onConnected,
}: {
backends: SubagentBackendInfo[];
+ partners: PartnerInfo[];
existingNames: string[];
tr: (l: Lang) => string;
onClose: () => void;
onConnected: () => void;
}) {
- const [kind, setKind] = useState(backends[0]?.kind ?? "");
+ // The agent-type choices: each detected CLI, plus "Partner" when any exist.
+ const options = useMemo(
+ () => [
+ ...backends.map((b) => ({ kind: b.kind, label: b.display_name })),
+ ...(partners.length
+ ? [{ kind: PARTNER_KIND, label: tr({ zh: "伙伴", en: "Partner" }) }]
+ : []),
+ ],
+ [backends, partners, tr],
+ );
+
+ const [kind, setKind] = useState(options[0]?.kind ?? "");
const [name, setName] = useState("");
+ const [nameTouched, setNameTouched] = useState(false);
const [cwd, setCwd] = useState("");
+ const [partnerId, setPartnerId] = useState(partners[0]?.partner_id ?? "");
const [error, setError] = useState("");
const [submitting, setSubmitting] = useState(false);
+ const isPartner = kind === PARTNER_KIND;
+
+ // While the user hasn't renamed the connection, mirror the chosen partner's
+ // name so the connection reads as that partner by default.
+ useEffect(() => {
+ if (!isPartner || nameTouched) return;
+ const picked = partners.find((p) => p.partner_id === partnerId);
+ setName(picked?.name ?? "");
+ }, [isPartner, nameTouched, partnerId, partners]);
+
const submit = useCallback(async () => {
const trimmed = name.trim();
if (!trimmed) {
@@ -216,17 +280,25 @@ function ConnectModal({
setError(tr({ zh: "已存在同名连接。", en: "A connection with this name already exists." }));
return;
}
+ if (isPartner && !partnerId) {
+ setError(tr({ zh: "请选择一个伙伴。", en: "Please pick a partner." }));
+ return;
+ }
setSubmitting(true);
setError("");
try {
- await connectSubagent({ name: trimmed, agent_kind: kind, cwd: cwd.trim() });
+ await connectSubagent(
+ isPartner
+ ? { name: trimmed, agent_kind: PARTNER_KIND, partner_id: partnerId }
+ : { name: trimmed, agent_kind: kind, cwd: cwd.trim() },
+ );
onConnected();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setSubmitting(false);
}
- }, [name, kind, cwd, existingNames, onConnected, tr]);
+ }, [name, kind, cwd, isPartner, partnerId, existingNames, onConnected, tr]);
return (
<div
@@ -257,27 +329,48 @@ function ConnectModal({
{tr({ zh: "智能体", en: "Agent" })}
</label>
<div className="flex gap-2">
- {backends.map((b) => {
- const Glyph = agentGlyph(b.kind);
+ {options.map((opt) => {
+ const Glyph = agentGlyph(opt.kind);
return (
<button
- key={b.kind}
+ key={opt.kind}
type="button"
- onClick={() => setKind(b.kind)}
+ onClick={() => setKind(opt.kind)}
className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-[12.5px] font-medium transition-colors ${
- kind === b.kind
+ kind === opt.kind
? "border-[var(--primary)] bg-[var(--primary)]/[0.07] text-[var(--foreground)]"
: "border-[var(--border)] text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"
}`}
>
{Glyph ? <Glyph size={15} /> : null}
- {b.display_name}
+ {opt.label}
</button>
);
})}
</div>
</div>
+ {isPartner && (
+ <div>
+ <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">
+ {tr({ zh: "伙伴", en: "Partner" })}
+ </label>
+ <select
+ value={partnerId}
+ onChange={(e) => setPartnerId(e.target.value)}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ >
+ {partners.map((p) => (
+ <option key={p.partner_id} value={p.partner_id}>
+ {p.emoji ? `${p.emoji} ` : ""}
+ {p.name}
+ {p.description ? ` — ${p.description}` : ""}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
<div>
<label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">
{tr({ zh: "名称", en: "Name" })}
@@ -285,26 +378,40 @@ function ConnectModal({
<input
autoFocus
value={name}
- onChange={(e) => setName(e.target.value)}
+ onChange={(e) => {
+ setName(e.target.value);
+ setNameTouched(true);
+ }}
placeholder={tr({ zh: "例如:我的代码助手", en: "e.g. My coding agent" })}
className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
/>
</div>
- <div>
- <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">
- {tr({ zh: "工作目录(可选)", en: "Working directory (optional)" })}
- </label>
- <input
- value={cwd}
- onChange={(e) => setCwd(e.target.value)}
- placeholder={tr({
- zh: "例如:/Users/you/project —— 智能体将在此目录运行",
- en: "e.g. /Users/you/project — the agent runs here",
+ {!isPartner && (
+ <div>
+ <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">
+ {tr({ zh: "工作目录(可选)", en: "Working directory (optional)" })}
+ </label>
+ <input
+ value={cwd}
+ onChange={(e) => setCwd(e.target.value)}
+ placeholder={tr({
+ zh: "例如:/Users/you/project —— 智能体将在此目录运行",
+ en: "e.g. /Users/you/project — the agent runs here",
+ })}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ )}
+
+ {isPartner && (
+ <p className="text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {tr({
+ zh: "在对话中咨询该伙伴时,会像在伙伴页开启一个新 session;同一对话里的多次咨询都会归档为同一个 session。",
+ en: "Consulting this partner in chat opens a session on it, just like the partner page; every consult within one chat is archived as the same session.",
})}
- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- />
- </div>
+ </p>
+ )}
{error && (
<p className="text-[12px] text-red-600 dark:text-red-400">{error}</p>
diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsx
index d498f3e26..d3819e428 100644
--- a/web/components/agents/agent-icons.tsx
+++ b/web/components/agents/agent-icons.tsx
@@ -69,10 +69,28 @@ export function CodexGlyph({ size = 16, ...props }: GlyphProps) {
);
}
+// A connected partner: a filled heart in the Partners accent, so a consulted
+// partner reads as a companion (not a CLI) everywhere a connected agent appears.
+export function PartnerGlyph({ size = 16, ...props }: GlyphProps) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="#7C6FF0"
+ aria-hidden
+ {...props}
+ >
+ <path d="M12 21s-7.5-4.35-10-9.16C.61 9.06 1.6 5.6 4.6 4.66c1.9-.6 3.86.18 5 1.74L12 9l.4-.6c.14-.96 1.1-1.74 2-2.34 1.74-1.16 4.1-.78 5.4.9 1.6 2.06 1 5.34-1.4 7.88C19.5 16.65 12 21 12 21z" />
+ </svg>
+ );
+}
+
export type AgentGlyph = ComponentType<GlyphProps>;
export function agentGlyph(kind: string | undefined): AgentGlyph | null {
if (kind === "claude_code") return ClaudeGlyph;
if (kind === "codex") return CodexGlyph;
+ if (kind === "partner") return PartnerGlyph;
return null;
}
diff --git a/web/components/chat/MyAgentsPicker.tsx b/web/components/chat/MyAgentsPicker.tsx
index 32f5edf59..7dbddf5f8 100644
--- a/web/components/chat/MyAgentsPicker.tsx
+++ b/web/components/chat/MyAgentsPicker.tsx
@@ -10,6 +10,7 @@ import {
ChevronRight,
Eye,
FolderOpen,
+ Heart,
Loader2,
Minus,
Search,
@@ -19,11 +20,13 @@ import PickerShell from "@/components/common/PickerShell";
import PickerHeader from "@/components/common/PickerHeader";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import { listImportedSessions } from "@/lib/imports-api";
+import { getSession } from "@/lib/session-api";
import {
- getSession,
- type SessionDetail,
- type SessionSummary,
-} from "@/lib/session-api";
+ getPartnerHistory,
+ getPartnerSessions,
+ type PartnerSessionInfo,
+} from "@/lib/partners-api";
+import { listSubagentConnections } from "@/lib/subagents-api";
import {
epochMsToISODate,
projectLabel,
@@ -44,16 +47,49 @@ interface MyAgentsPickerProps {
}
const UNGROUPED_PREFIX = "ungrouped:";
+const PARTNER_PREFIX = "partner:";
const ALL = "__all__";
+/** Normalized picker row — an imported conversation OR a connected partner's
+ * session. The shared shape lets one set of chip/group/preview/apply paths
+ * drive both sources. ``id`` is the reference id sent to the backend: a real
+ * session id for imports, ``partner:{pid}:{sessionKey}`` for partner sessions
+ * (resolved server-side against the partner store). */
+interface PickerRow {
+ id: string;
+ title: string;
+ lastMessage: string;
+ messageCount: number;
+ updatedAt: number; // epoch ms
+ ownerKey: string; // chip bucket: agent id | ungrouped:source | partner:{pid}
+ groupKey: string;
+ groupKind: "project" | "date" | "partner";
+ groupLabel: string;
+ kind: "imported" | "partner";
+ partnerId?: string;
+ sessionKey?: string;
+}
+
interface SubGroup {
key: string;
label: string;
- kind: "project" | "date";
- sessions: SessionSummary[];
+ kind: PickerRow["groupKind"];
+ rows: PickerRow[];
latest: number;
}
+interface PartnerAgent {
+ partnerId: string;
+ name: string;
+ sessions: PartnerSessionInfo[];
+}
+
+interface PreviewState {
+ row: PickerRow;
+ messages: { id: string; role: string; content: string }[] | null;
+ loading: boolean;
+}
+
function formatDay(key: string, lang: string): string {
const d = new Date(`${key}T00:00:00`);
if (Number.isNaN(d.getTime())) return key;
@@ -65,13 +101,20 @@ function formatDay(key: string, lang: string): string {
});
}
+function isoMs(value: string | undefined): number {
+ const ms = value ? new Date(value).getTime() : NaN;
+ return Number.isNaN(ms) ? 0 : ms;
+}
+
/**
- * Reference picker for imported agent conversations. Conversations are stored
- * as normal sessions, so a selection is just a list of session ids — the same
- * shape and backend path as the Chat History reference. Here we attribute each
- * conversation to its named agent (via the IndexedDB registry), let the user
- * filter by agent, then organize that agent's conversations by project (Claude
- * Code) or day (Codex) so they can pick a whole group or individual chats.
+ * Reference picker for agent conversations. Two sources feed one unified list:
+ * imported Claude Code / Codex conversations (stored as normal sessions, so a
+ * selection is just a session id), and the sessions of any partner connected as
+ * an agent (resolved server-side via a ``partner:{id}:{key}`` reference id).
+ * Either way a selection is a list of reference ids — the same backend path as
+ * the Chat History reference. We attribute each conversation to its agent, let
+ * the user filter by agent, then organize an agent's conversations by project
+ * (Claude Code), day (Codex / partner) so they can pick a group or single chats.
*/
export default function MyAgentsPicker({
open,
@@ -79,18 +122,17 @@ export default function MyAgentsPicker({
onApply,
}: MyAgentsPickerProps) {
const { t, i18n } = useTranslation();
- const [sessions, setSessions] = useState<SessionSummary[]>([]);
+ const [sessions, setSessions] = useState<
+ Awaited<ReturnType<typeof listImportedSessions>>
+ >([]);
const [agents, setAgents] = useState<ImportAgent[]>([]);
+ const [partnerAgents, setPartnerAgents] = useState<PartnerAgent[]>([]);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [query, setQuery] = useState("");
const [activeAgent, setActiveAgent] = useState<string>(ALL);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
- const [preview, setPreview] = useState<{
- session: SessionSummary;
- detail: SessionDetail | null;
- loading: boolean;
- } | null>(null);
+ const [preview, setPreview] = useState<PreviewState | null>(null);
useEffect(() => {
if (!open) return;
@@ -98,17 +140,41 @@ export default function MyAgentsPicker({
const load = async () => {
setLoading(true);
try {
- const [data, reg] = await Promise.all([
+ const [data, reg, conns] = await Promise.all([
listImportedSessions(200, 0, { force: true }),
getAgents(),
+ listSubagentConnections().catch(() => []),
]);
+ // For every partner connected as an agent, pull its sessions so they
+ // can be referenced just like an imported conversation.
+ const partners = conns.filter((c) => c.agent_kind === "partner");
+ const partnerData = await Promise.all(
+ partners.map(async (c) => {
+ const pid = c.partner_id || "";
+ if (!pid) return null;
+ const list = await getPartnerSessions(pid).catch(
+ () => [] as PartnerSessionInfo[],
+ );
+ const sessionsForPartner = list.filter(
+ (s) => !s.archived && (s.message_count ?? 0) > 0,
+ );
+ if (!sessionsForPartner.length) return null;
+ return {
+ partnerId: pid,
+ name: c.name || pid,
+ sessions: sessionsForPartner,
+ } satisfies PartnerAgent;
+ }),
+ );
if (!mounted) return;
setSessions(data);
setAgents(reg);
+ setPartnerAgents(partnerData.filter((p): p is PartnerAgent => !!p));
} catch {
if (mounted) {
setSessions([]);
setAgents([]);
+ setPartnerAgents([]);
}
} finally {
if (mounted) setLoading(false);
@@ -131,7 +197,8 @@ export default function MyAgentsPicker({
}
}, [open]);
- // Owner key per session: the agent id, or an ungrouped-by-source bucket.
+ // Owner key per imported session: the agent id, or an ungrouped-by-source
+ // bucket (partner sessions carry their own owner key, built in `rows`).
const ownerKeyById = useMemo(() => {
const ordered = [...agents].sort(
(a, b) => (b.lastSyncAt || b.createdAt) - (a.lastSyncAt || a.createdAt),
@@ -147,78 +214,132 @@ export default function MyAgentsPicker({
return map;
}, [agents, sessions]);
+ // The unified row list — imported conversations and partner sessions both
+ // normalized into `PickerRow`.
+ const rows = useMemo<PickerRow[]>(() => {
+ const out: PickerRow[] = [];
+ for (const session of sessions) {
+ const sid = session.session_id || session.id;
+ const ownerKey = ownerKeyById.get(sid);
+ if (!ownerKey) continue;
+ const meta = readImportMeta(session);
+ if (!meta) continue;
+ const isCodex = meta.source === "codex";
+ const unit = isCodex
+ ? epochMsToISODate(session.created_at * 1000)
+ : meta.sourceCwd;
+ out.push({
+ id: sid,
+ title: session.title || "",
+ lastMessage: session.last_message || "",
+ messageCount: session.message_count ?? 0,
+ updatedAt: session.updated_at,
+ ownerKey,
+ groupKey: `${meta.source}:${unit}`,
+ groupKind: isCodex ? "date" : "project",
+ groupLabel: isCodex
+ ? formatDay(unit, i18n.language)
+ : projectLabel(unit),
+ kind: "imported",
+ });
+ }
+ for (const partner of partnerAgents) {
+ for (const session of partner.sessions) {
+ const day = epochMsToISODate(isoMs(session.updated_at));
+ out.push({
+ id: `${PARTNER_PREFIX}${partner.partnerId}:${session.session_key}`,
+ title: session.title || "",
+ lastMessage: session.last_message || "",
+ messageCount: session.message_count ?? 0,
+ updatedAt: isoMs(session.updated_at),
+ ownerKey: `${PARTNER_PREFIX}${partner.partnerId}`,
+ groupKey: `${PARTNER_PREFIX}${partner.partnerId}:${day}`,
+ groupKind: "date",
+ groupLabel: formatDay(day, i18n.language),
+ kind: "partner",
+ partnerId: partner.partnerId,
+ sessionKey: session.session_key,
+ });
+ }
+ }
+ return out;
+ }, [sessions, ownerKeyById, partnerAgents, i18n.language]);
+
const labelForKey = useMemo(() => {
- const byId = new Map(agents.map((a) => [a.id, a.name]));
+ const byAgent = new Map(agents.map((a) => [a.id, a.name]));
+ const byPartner = new Map(
+ partnerAgents.map((p) => [`${PARTNER_PREFIX}${p.partnerId}`, p.name]),
+ );
return (key: string): string => {
+ if (key.startsWith(PARTNER_PREFIX)) return byPartner.get(key) ?? key;
if (key.startsWith(UNGROUPED_PREFIX)) {
const src = key.slice(UNGROUPED_PREFIX.length) as ImportSource;
return SOURCE_LABEL[src] ?? src;
}
- return byId.get(key) ?? t("Untitled conversation");
+ return byAgent.get(key) ?? t("Untitled conversation");
};
- }, [agents, t]);
+ }, [agents, partnerAgents, t]);
- // Filter chips — every owner that has at least one conversation, ordered with
- // named agents first (registry order), then ungrouped source buckets.
+ // Filter chips — every owner with at least one conversation. Named import
+ // agents first (registry order), then connected partners, then ungrouped
+ // source buckets.
const chips = useMemo(() => {
const counts = new Map<string, number>();
- for (const key of ownerKeyById.values())
- counts.set(key, (counts.get(key) ?? 0) + 1);
- const ordered = [...agents]
+ for (const row of rows) counts.set(row.ownerKey, (counts.get(row.ownerKey) ?? 0) + 1);
+ const importAgents = [...agents]
.sort(
(a, b) => (b.lastSyncAt || b.createdAt) - (a.lastSyncAt || a.createdAt),
)
.map((a) => a.id)
.filter((id) => counts.has(id));
+ const partners = partnerAgents
+ .map((p) => `${PARTNER_PREFIX}${p.partnerId}`)
+ .filter((k) => counts.has(k));
const ungrouped = [...counts.keys()]
.filter((k) => k.startsWith(UNGROUPED_PREFIX))
.sort();
- return [...ordered, ...ungrouped].map((key) => ({
+ return [...importAgents, ...partners, ...ungrouped].map((key) => ({
key,
label: labelForKey(key),
count: counts.get(key) ?? 0,
+ isPartner: key.startsWith(PARTNER_PREFIX),
}));
- }, [agents, ownerKeyById, labelForKey]);
+ }, [agents, partnerAgents, rows, labelForKey]);
- // Group the (chip- and search-filtered) sessions by project (Claude Code) or
- // day (Codex), so the user can bulk-pick a project/day or drill in.
+ // Group the (chip- and search-filtered) rows by project (Claude Code) or day
+ // (Codex / partner), so the user can bulk-pick a group or drill in.
const groups = useMemo<SubGroup[]>(() => {
const keyword = query.trim().toLowerCase();
const map = new Map<string, SubGroup>();
- for (const session of sessions) {
- const sid = session.session_id || session.id;
- const ownerKey = ownerKeyById.get(sid);
- if (!ownerKey) continue;
- if (activeAgent !== ALL && ownerKey !== activeAgent) continue;
+ for (const row of rows) {
+ if (activeAgent !== ALL && row.ownerKey !== activeAgent) continue;
if (keyword) {
- const title = String(session.title || "").toLowerCase();
- const last = normalizeMessageContent(
- session.last_message,
- ).toLowerCase();
+ const title = row.title.toLowerCase();
+ const last = normalizeMessageContent(row.lastMessage).toLowerCase();
if (!title.includes(keyword) && !last.includes(keyword)) continue;
}
- const meta = readImportMeta(session);
- if (!meta) continue;
- const isCodex = meta.source === "codex";
- const unit = isCodex
- ? epochMsToISODate(session.created_at * 1000)
- : meta.sourceCwd;
- const key = `${meta.source}:${unit}`;
const group =
- map.get(key) ??
+ map.get(row.groupKey) ??
({
- key,
- kind: isCodex ? "date" : "project",
- label: isCodex ? formatDay(unit, i18n.language) : projectLabel(unit),
- sessions: [],
+ key: row.groupKey,
+ kind: row.groupKind,
+ label: row.groupLabel,
+ rows: [],
latest: 0,
} satisfies SubGroup);
- group.sessions.push(session);
- group.latest = Math.max(group.latest, session.updated_at);
- map.set(key, group);
+ group.rows.push(row);
+ group.latest = Math.max(group.latest, row.updatedAt);
+ map.set(row.groupKey, group);
}
return Array.from(map.values()).sort((a, b) => b.latest - a.latest);
- }, [sessions, ownerKeyById, activeAgent, query, i18n.language]);
+ }, [rows, activeAgent, query]);
+
+ const titleById = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const row of rows)
+ map.set(row.id, row.title || t("Untitled conversation"));
+ return map;
+ }, [rows, t]);
const toggleSession = (id: string) =>
setSelectedIds((prev) =>
@@ -226,7 +347,7 @@ export default function MyAgentsPicker({
);
const toggleGroup = (group: SubGroup) => {
- const ids = group.sessions.map((s) => s.session_id || s.id);
+ const ids = group.rows.map((r) => r.id);
setSelectedIds((prev) => {
const all = ids.every((id) => prev.includes(id));
if (all) return prev.filter((id) => !ids.includes(id));
@@ -244,35 +365,41 @@ export default function MyAgentsPicker({
return next;
});
- const openPreview = async (session: SessionSummary) => {
- const sid = session.session_id || session.id;
- setPreview({ session, detail: null, loading: true });
+ const openPreview = async (row: PickerRow) => {
+ setPreview({ row, messages: null, loading: true });
try {
- const detail = await getSession(sid);
- // Ignore if the user navigated away from this preview meanwhile.
+ const messages =
+ row.kind === "partner" && row.partnerId && row.sessionKey
+ ? (
+ await getPartnerHistory(row.partnerId, {
+ sessionKey: row.sessionKey,
+ limit: 200,
+ })
+ ).map((m, idx) => ({
+ id: `${row.id}:${idx}`,
+ role: String(m.role || ""),
+ content: String(m.content || ""),
+ }))
+ : (await getSession(row.id)).messages.map((m) => ({
+ id: String(m.id),
+ role: String(m.role || ""),
+ content: String(m.content || ""),
+ }));
setPreview((cur) =>
- cur && (cur.session.session_id || cur.session.id) === sid
- ? { ...cur, detail, loading: false }
- : cur,
+ cur && cur.row.id === row.id ? { ...cur, messages, loading: false } : cur,
);
} catch {
setPreview((cur) =>
- cur && (cur.session.session_id || cur.session.id) === sid
- ? { ...cur, loading: false }
- : cur,
+ cur && cur.row.id === row.id ? { ...cur, loading: false } : cur,
);
}
};
const handleApply = () => {
- const selected = sessions
- .filter((session) =>
- selectedIds.includes(session.session_id || session.id),
- )
- .map((session) => ({
- sessionId: session.session_id || session.id,
- title: session.title || t("Untitled conversation"),
- }));
+ const selected = selectedIds.map((id) => ({
+ sessionId: id,
+ title: titleById.get(id) || t("Untitled conversation"),
+ }));
onApply(selected);
onClose();
};
@@ -315,6 +442,7 @@ export default function MyAgentsPicker({
label={chip.label}
count={chip.count}
active={activeAgent === chip.key}
+ partner={chip.isPartner}
onClick={() => setActiveAgent(chip.key)}
/>
))}
@@ -344,15 +472,9 @@ export default function MyAgentsPicker({
{preview ? (
<PreviewPane
preview={preview}
- selected={selectedIds.includes(
- preview.session.session_id || preview.session.id,
- )}
+ selected={selectedIds.includes(preview.row.id)}
onBack={() => setPreview(null)}
- onToggleSelect={() =>
- toggleSession(
- preview.session.session_id || preview.session.id,
- )
- }
+ onToggleSelect={() => toggleSession(preview.row.id)}
/>
) : loading ? (
<div className="flex min-h-[280px] items-center justify-center">
@@ -364,7 +486,7 @@ export default function MyAgentsPicker({
className="animate-fade-in divide-y divide-[var(--border)]"
>
{groups.map((group) => {
- const ids = group.sessions.map((s) => s.session_id || s.id);
+ const ids = group.rows.map((r) => r.id);
const selectedInGroup = ids.filter((id) =>
selectedIds.includes(id),
).length;
@@ -418,12 +540,11 @@ export default function MyAgentsPicker({
{isOpen && (
<div className="divide-y divide-[var(--border)]">
- {group.sessions.map((session) => {
- const id = session.session_id || session.id;
- const selected = selectedIds.includes(id);
+ {group.rows.map((row) => {
+ const selected = selectedIds.includes(row.id);
return (
<div
- key={id}
+ key={row.id}
className={`group/row flex w-full items-start transition-colors ${
selected
? "bg-[var(--primary)]/[0.08]"
@@ -432,7 +553,7 @@ export default function MyAgentsPicker({
>
<button
type="button"
- onClick={() => toggleSession(id)}
+ onClick={() => toggleSession(row.id)}
className="flex min-w-0 flex-1 items-start gap-3 py-3 pl-10 pr-2 text-left"
>
<div
@@ -446,28 +567,24 @@ export default function MyAgentsPicker({
</div>
<div className="min-w-0 flex-1">
<span className="block truncate text-[14px] font-medium text-[var(--foreground)]">
- {session.title ||
- t("Untitled conversation")}
+ {row.title || t("Untitled conversation")}
</span>
- {session.last_message ? (
+ {row.lastMessage ? (
<p className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">
{truncateText(
- normalizeMessageContent(
- session.last_message,
- ),
+ normalizeMessageContent(row.lastMessage),
200,
)}
</p>
) : null}
<div className="mt-2 text-[11px] text-[var(--muted-foreground)]/85">
- {session.message_count ?? 0}{" "}
- {t("messages")}
+ {row.messageCount} {t("messages")}
</div>
</div>
</button>
<button
type="button"
- onClick={() => void openPreview(session)}
+ onClick={() => void openPreview(row)}
title={t("Preview")}
aria-label={t("Preview")}
className="mr-3 mt-3 shrink-0 rounded-lg border border-transparent p-1.5 text-[var(--muted-foreground)] opacity-0 transition-all hover:border-[var(--border)] hover:text-[var(--foreground)] focus:opacity-100 group-hover/row:opacity-100"
@@ -548,18 +665,14 @@ function PreviewPane({
onBack,
onToggleSelect,
}: {
- preview: {
- session: SessionSummary;
- detail: SessionDetail | null;
- loading: boolean;
- };
+ preview: PreviewState;
selected: boolean;
onBack: () => void;
onToggleSelect: () => void;
}) {
const { t } = useTranslation();
- const { session, detail, loading } = preview;
- const messages = (detail?.messages ?? []).filter(
+ const { row, messages, loading } = preview;
+ const visible = (messages ?? []).filter(
(m) => (m.content || "").trim() && m.role !== "system",
);
return (
@@ -575,10 +688,10 @@ function PreviewPane({
</button>
<div className="min-w-0 flex-1">
<div className="truncate text-[13px] font-semibold text-[var(--foreground)]">
- {session.title || t("Untitled conversation")}
+ {row.title || t("Untitled conversation")}
</div>
<div className="text-[11px] text-[var(--muted-foreground)]">
- {session.message_count ?? messages.length} {t("messages")}
+ {row.messageCount || visible.length} {t("messages")}
</div>
</div>
<button
@@ -599,9 +712,9 @@ function PreviewPane({
<div className="flex min-h-[280px] items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
</div>
- ) : messages.length ? (
+ ) : visible.length ? (
<div className="space-y-3 px-4 py-4">
- {messages.map((m) => (
+ {visible.map((m) => (
<div key={m.id}>
<div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.1em] text-[var(--muted-foreground)]">
{m.role === "user" ? t("You") : t("Assistant")}
@@ -625,11 +738,13 @@ function Chip({
label,
count,
active,
+ partner,
onClick,
}: {
label: string;
count?: number;
active: boolean;
+ partner?: boolean;
onClick: () => void;
}) {
return (
@@ -642,6 +757,7 @@ function Chip({
: "border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:border-[var(--primary)]/50 hover:text-[var(--foreground)]"
}`}
>
+ {partner ? <Heart size={11} className="shrink-0 fill-current" /> : null}
<span className="truncate">{label}</span>
{typeof count === "number" ? (
<span
diff --git a/web/components/partners/ToolPicker.tsx b/web/components/partners/ToolPicker.tsx
index c6f604e6c..b9052202b 100644
--- a/web/components/partners/ToolPicker.tsx
+++ b/web/components/partners/ToolPicker.tsx
@@ -176,6 +176,17 @@ export default function ToolPicker({
</div>
)}
+ <div>
+ <h4 className="mb-1.5 text-[13px] font-medium text-[var(--muted-foreground)]">
+ {t("Memory")}
+ </h4>
+ <p className="px-2 text-[11.5px] text-[var(--muted-foreground)]">
+ {t(
+ "Always on and built in — not configurable. partner_read sees the owner's shared memory plus the partner's own; partner_memorize writes only the partner's own memory; partner_search keyword-searches past conversations.",
+ )}
+ </p>
+ </div>
+
{options.mcp_tools.length > 0 && (
<div>
<div className="mb-1.5 flex items-baseline justify-between">
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index ee79c437f..456502003 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -58,8 +58,10 @@ export interface KnowledgeBase {
type?: string;
/** Absolute path of a connected Obsidian vault (when type === "obsidian"). */
vault_path?: string;
- /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex". */
+ /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "partner". */
agent_kind?: string;
+ /** Bound partner id when agent_kind === "partner". */
+ partner_id?: string;
};
progress?: ProgressInfo;
statistics?: {
diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.ts
index 6646431f0..276ceaa0c 100644
--- a/web/lib/subagents-api.ts
+++ b/web/lib/subagents-api.ts
@@ -14,6 +14,8 @@ export interface SubagentConnection {
name: string;
agent_kind: string;
cwd: string;
+ /** Set for a partner connection (`agent_kind === "partner"`): the bound partner. */
+ partner_id?: string;
description?: string;
created_at?: string;
updated_at?: string | null;
@@ -41,6 +43,8 @@ export async function connectSubagent(payload: {
name: string;
agent_kind: string;
cwd?: string;
+ /** Required when `agent_kind === "partner"`: which partner to consult. */
+ partner_id?: string;
}): Promise<SubagentConnection> {
const res = await apiFetch(apiUrl("/api/v1/subagents/connections"), {
method: "POST",