Files
DeepTutor/deeptutor/multi_user/router.py
Bingxi Zhao (Frank) bd80a4d28a release: v1.5.17
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.

Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).

Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).

Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.

Two defects found by the release gate and fixed here:

- Six partner routes — the four channel-onboarding endpoints and both
  WeChat QR endpoints — kept the _auth-only mount they had inherited
  from the blanket admin gate, so any signed-in account could start a
  QR login for someone else's partner and write a bot token into its
  channel config. All six now declare _MANAGEABLE, and a sweep test
  asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
  landed, but ten call sites pass it somewhere that takes one key; a
  list would have rendered into an Authorization header verbatim.
  keypool.primary_api_key reduces at each boundary.

Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
2026-08-25 02:24:35 +08:00

237 lines
8.4 KiB
Python

"""Admin APIs for the optional multi-user layer."""
from __future__ import annotations
import asyncio
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from deeptutor.api.routers.auth import require_admin
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.services.config.model_catalog import ModelCatalogService
from deeptutor.services.skill.service import SkillService
from .audit import log_admin_action
from .context import get_current_user
from .grants import load_grant, save_grant
from .identity import get_user_by_id, list_user_info
from .knowledge_access import admin_kb_base_dir
from .model_access import is_owner_bound
from .paths import get_admin_path_service
router = APIRouter()
class GrantPayload(BaseModel):
grant: dict[str, Any]
class SkillInstallPayload(BaseModel):
ref: str
name: str | None = None
force: bool = False
allow_unverified: bool = False
def _admin_catalog_summary() -> dict[str, list[dict[str, Any]]]:
catalog = ModelCatalogService(
path=get_admin_path_service().get_settings_file("model_catalog")
).load()
out: dict[str, list[dict[str, Any]]] = {"llm": []}
for service, state in (catalog.get("services") or {}).items():
if service not in out:
continue
for profile in state.get("profiles", []) or []:
if is_owner_bound(profile):
# Bound to one person's OAuth identity, so it is not assignable.
# Listing it here would offer admins a grant the server drops.
continue
profile_id = str(profile.get("id") or "")
models = []
for model in profile.get("models", []) or []:
models.append(
{
"model_id": model.get("id", ""),
"name": model.get("name") or model.get("model") or model.get("id"),
"model": model.get("model", ""),
}
)
out[service].append(
{
"profile_id": profile_id,
"name": profile.get("name") or profile_id,
"models": models,
}
)
return out
def _admin_kb_summary() -> list[dict[str, Any]]:
manager = KnowledgeBaseManager(base_dir=str(admin_kb_base_dir()))
return [
{
"resource_id": f"admin:kb:{name}",
"name": name,
"source": "admin",
}
for name in manager.list_knowledge_bases()
]
def _admin_skill_summary() -> list[dict[str, Any]]:
root = get_admin_path_service().get_workspace_dir() / "skills"
service = SkillService(root=root)
return [item.to_dict() for item in service.list_skills()]
def _admin_partner_summary() -> list[dict[str, Any]]:
"""The partners an admin can hand to someone else.
Admin-managed partners only — the ones with no owner, or that the admin
created. A partner someone built for themselves is theirs to share or not;
listing it here would let an admin lend out a private companion (and its
soul, which people write personally) by a single click. Identity only: no
channel wiring or model selection leaks into the assignable summary.
"""
from deeptutor.services.partners import get_partner_manager
admin_id = get_current_user().id
return [
{
"partner_id": str(item.get("partner_id") or ""),
"name": item.get("name") or item.get("partner_id") or "",
"description": item.get("description") or "",
"emoji": item.get("emoji") or "",
}
for item in get_partner_manager().list_partners()
if str(item.get("owner_id") or "") in ("", admin_id)
]
def _require_assignable_user(user_id: str) -> tuple[str, dict[str, Any]]:
user_record = get_user_by_id(user_id)
if user_record is None:
raise HTTPException(status_code=404, detail="User not found")
username, record = user_record
if str(record.get("role") or "user") == "admin":
raise HTTPException(
status_code=403,
detail="Admin users use the main workspace and cannot receive assignments.",
)
return username, record
@router.get("/admin/resources")
async def admin_resources(_: object = Depends(require_admin)) -> dict[str, Any]:
"""Everything an admin can assign to a user: models, KBs, skills, and
the tool surface (system tools + MCP tools, same pool partners use)."""
from deeptutor.api.utils.tool_options import build_tool_options
tool_options = await build_tool_options()
return {
"models": _admin_catalog_summary(),
"knowledge_bases": _admin_kb_summary(),
"skills": _admin_skill_summary(),
"partners": _admin_partner_summary(),
"tools": tool_options["tools"],
"mcp_tools": tool_options["mcp_tools"],
}
@router.get("/users/{user_id}/grants")
async def get_user_grants(user_id: str, _: object = Depends(require_admin)) -> dict[str, Any]:
_require_assignable_user(user_id)
return {"grant": load_grant(user_id)}
@router.put("/users/{user_id}/grants")
async def put_user_grants(
user_id: str,
payload: GrantPayload,
_: object = Depends(require_admin),
) -> dict[str, Any]:
_require_assignable_user(user_id)
try:
grant = save_grant(user_id, payload.grant)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
log_admin_action(
"grant_set",
target_user_id=user_id,
summary={
"model_count": len(grant.get("models", {}).get("llm", []) or []),
"kb_count": len(grant.get("knowledge_bases", []) or []),
"skill_count": len(grant.get("skills", []) or []),
"partner_count": len(grant.get("partners", []) or []),
"enabled_tools": grant.get("enabled_tools"),
"mcp_tool_count": (
None if grant.get("mcp_tools") is None else len(grant.get("mcp_tools") or [])
),
"exec_enabled": grant.get("exec_enabled"),
},
)
return {"grant": grant}
@router.post("/admin/skills/install")
async def admin_install_skill(
payload: SkillInstallPayload,
_: object = Depends(require_admin),
) -> dict[str, Any]:
"""Install a hub skill into the admin catalog (``<hub>:<slug>[@version]``).
The skill lands in the admin workspace — the same pool ``/admin/resources``
lists — so it stays invisible to non-admin users until a grant assigns it.
The install pipeline (verdict gate, safe extraction, ``always`` stripping)
lives in :func:`deeptutor.services.skill.hub.install_from_hub`; this
endpoint only chooses the target root and audits the action.
"""
from deeptutor.services.skill.hub import HubError, install_from_hub
from deeptutor.services.skill.service import (
InvalidSkillNameError,
SkillExistsError,
SkillImportError,
)
service = SkillService(root=get_admin_path_service().get_workspace_dir() / "skills")
try:
outcome = await asyncio.to_thread(
install_from_hub,
payload.ref,
service=service,
rename_to=payload.name,
force=payload.force,
allow_unverified=payload.allow_unverified,
)
except SkillExistsError as exc:
raise HTTPException(status_code=409, detail=f"Skill already exists: {exc}") from exc
except (SkillImportError, InvalidSkillNameError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except HubError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
log_admin_action(
"skill_hub_install",
summary={
"ref": payload.ref,
"installed_as": outcome.result.info.name,
"version": outcome.ref.version,
"verdict": outcome.verdict.status,
"forced": payload.force,
"allow_unverified": payload.allow_unverified,
},
)
return {
"skill": outcome.result.info.to_dict(),
"verdict": {"status": outcome.verdict.status, "detail": outcome.verdict.detail},
"version": outcome.ref.version,
"skipped": [{"path": rel, "reason": reason} for rel, reason in outcome.result.skipped],
}
@router.get("/users")
async def multi_user_list_users(_: object = Depends(require_admin)) -> dict[str, Any]:
return {"users": list_user_info()}