feat: 新增岗位管理、提示词模板与资源标签,完善用户提示词与推荐问题接口

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
吉鑫升andClaude Opus 4.8 committed 2026-06-16 10:49:36 +08:00
1 parent 2f414c6e08
commit 3855c30edd
52 files changed
+3143 -57

No files matched your search

@@ -0,0 +1,220 @@
"""岗位 (position) → resource subscription **sync engine**.
A user's position decides which agents / scheduled tasks / custom prompts they
are subscribed to, and which skills / recommended questions they can see. This
service turns a position's *tag bindings* into concrete, materialized rows in
the existing "我的" tables (idempotent, re-runnable).
Resolution rule (per resource type):
* The user's position is ``users.position_id``; if unset, the ``is_default``
position is used; if there is none, every type falls back to its default set.
* For a resource type **with** bound tags → the union of resources carrying any
of those tags.
* For a resource type **without** bound tags → the *default set*:
- ``agent`` → all built-in agents (``user_id IS NULL``)
- ``scheduled_task`` → empty (no built-in tasks)
- ``user_prompt`` → admin templates that carry no tag
- ``skill`` / ``recommended_question`` → *unrestricted* (handled at query
time, never materialized — see :meth:`resolve_visible`)
Materialization (``sync_user``) only ever touches rows it created itself
(``origin='position'``), so a user's own favorites / subscriptions / prompts are
never clobbered. The skill + recommended-question visibility filters are
computed live by :meth:`resolve_visible` and are *not* materialized.
"""
from __future__ import annotations
import logging
import uuid
from datetime import UTC, datetime
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from deerflow.persistence.agents.model import AgentFavoriteRow, AgentRow
from deerflow.persistence.positions.base import PositionStore
from deerflow.persistence.scheduled_tasks.model import ScheduledTaskSubscriptionRow
from deerflow.persistence.tags.base import TagStore
from deerflow.persistence.user_prompts.model import UserCustomPromptRow
logger = logging.getLogger(__name__)
# Materialized into "我的" tables by sync_user.
_MATERIALIZED_TYPES = ("agent", "scheduled_task", "user_prompt")
# Resolved live at query time (visibility filters), never materialized.
_VISIBILITY_TYPES = ("skill", "recommended_question")
class PositionSyncService:
def __init__(self, session_factory: async_sessionmaker[AsyncSession], position_store: PositionStore, tag_store: TagStore) -> None:
self._sf = session_factory
self._positions = position_store
self._tags = tag_store
# ----------------------------------------------------------- resolution
async def _effective_position_id(self, user_id: str) -> str | None:
pid = await self._positions.get_user_position_id(user_id)
if pid:
return pid
return await self._positions.get_default_position_id()
async def resolve_visible(self, user_id: str, resource_type: str) -> set[str] | None:
"""Return the set of visible ``resource_type`` ids, or ``None`` = unrestricted.
Used by the skills list + recommended-questions filters. ``None`` means
"no position restriction → show everything"; a set means "restrict to
exactly these ids".
"""
pid = await self._effective_position_id(user_id)
if not pid:
return None
bindings = await self._positions.get_tag_bindings(pid)
tag_ids = bindings.get(resource_type) or []
if not tag_ids:
return None
return set(await self._tags.list_targets_for_tags(resource_type, tag_ids))
async def _resolve_materialized(self, user_id: str, resource_type: str, session: AsyncSession) -> set[str]:
pid = await self._effective_position_id(user_id)
bindings = await self._positions.get_tag_bindings(pid) if pid else {}
tag_ids = bindings.get(resource_type) or []
if tag_ids:
return set(await self._tags.list_targets_for_tags(resource_type, tag_ids))
return await self._default_set(resource_type, session)
async def _default_set(self, resource_type: str, session: AsyncSession) -> set[str]:
if resource_type == "agent":
rows = (await session.execute(select(AgentRow.id).where(AgentRow.user_id.is_(None)))).all()
return {r[0] for r in rows}
if resource_type == "scheduled_task":
return set()
if resource_type == "user_prompt":
# Admin templates that carry no tag = global default templates.
template_ids = {r[0] for r in (await session.execute(select(UserCustomPromptRow.id).where(UserCustomPromptRow.is_template.is_(True)))).all()}
if not template_ids:
return set()
tagged = set(await self._tags.list_targets_for_tags("user_prompt", await self._all_user_prompt_tag_ids()))
return template_ids - tagged
return set()
async def _all_user_prompt_tag_ids(self) -> list[str]:
return [t["id"] for t in await self._tags.list_tags("user_prompt")]
# --------------------------------------------------------- materialize
async def sync_user(self, user_id: str) -> None:
"""Reconcile all materialized subscriptions for one user (idempotent)."""
if self._sf is None:
return
pid = await self._effective_position_id(user_id)
async with self._sf() as session:
await self._sync_agents(session, user_id, pid)
await self._sync_tasks(session, user_id, pid)
await self._sync_prompts(session, user_id, pid)
await session.commit()
async def _sync_agents(self, session: AsyncSession, user_id: str, position_id: str | None) -> None:
target = await self._resolve_materialized(user_id, "agent", session)
rows = list((await session.execute(select(AgentFavoriteRow).where(AgentFavoriteRow.user_id == user_id))).scalars())
owned_any = {r.agent_id for r in rows}
position_rows = {r.agent_id: r for r in rows if r.origin == "position"}
now = datetime.now(UTC)
for agent_id in target - owned_any:
session.add(AgentFavoriteRow(id=uuid.uuid4().hex, user_id=user_id, agent_id=agent_id, origin="position", position_id=position_id, created_at=now))
for agent_id, row in position_rows.items():
if agent_id not in target:
await session.delete(row)
async def _sync_tasks(self, session: AsyncSession, user_id: str, position_id: str | None) -> None:
target = await self._resolve_materialized(user_id, "scheduled_task", session)
rows = list((await session.execute(select(ScheduledTaskSubscriptionRow).where(ScheduledTaskSubscriptionRow.user_id == user_id))).scalars())
owned_any = {r.task_id for r in rows}
position_rows = {r.task_id: r for r in rows if r.origin == "position"}
now = datetime.now(UTC)
for task_id in target - owned_any:
session.add(ScheduledTaskSubscriptionRow(id=uuid.uuid4().hex, task_id=task_id, user_id=user_id, notify_element=False, origin="position", position_id=position_id, created_at=now, updated_at=now))
for task_id, row in position_rows.items():
if task_id not in target:
await session.delete(row)
async def _sync_prompts(self, session: AsyncSession, user_id: str, position_id: str | None) -> None:
target_template_ids = await self._resolve_materialized(user_id, "user_prompt", session)
# Load the templates we need to clone, so we can copy their content.
templates: dict[str, UserCustomPromptRow] = {}
if target_template_ids:
for row in (await session.execute(select(UserCustomPromptRow).where(UserCustomPromptRow.id.in_(target_template_ids), UserCustomPromptRow.is_template.is_(True)))).scalars():
templates[row.id] = row
existing = list(
(await session.execute(select(UserCustomPromptRow).where(UserCustomPromptRow.user_id == user_id, UserCustomPromptRow.origin == "position"))).scalars()
)
existing_by_template = {r.template_id: r for r in existing if r.template_id}
now = datetime.now(UTC)
# Remove stale clones (template no longer granted or template deleted).
for tpl_id, row in existing_by_template.items():
if tpl_id not in templates:
await session.delete(row)
# Add / refresh clones for granted templates.
for tpl_id, tpl in templates.items():
row = existing_by_template.get(tpl_id)
if row is None:
session.add(
UserCustomPromptRow(
id=uuid.uuid4().hex,
user_id=user_id,
title=tpl.title,
content=tpl.content,
sort_order=tpl.sort_order,
agent_id=tpl.agent_id,
is_template=False,
origin="position",
template_id=tpl_id,
position_id=position_id,
created_at=now,
updated_at=now,
)
)
else:
# Keep the user's clone in step with the template content.
row.title = tpl.title
row.content = tpl.content
row.agent_id = tpl.agent_id
row.position_id = position_id
row.updated_at = now
# ------------------------------------------------------------- fan-out
async def sync_position(self, position_id: str) -> int:
"""Re-sync every member of a position. Returns the member count."""
member_ids = await self._positions.list_member_ids(position_id)
for uid in member_ids:
try:
await self.sync_user(uid)
except Exception:
logger.exception("position sync failed for user %s (position %s)", uid, position_id)
return len(member_ids)
async def sync_default_members(self) -> int:
"""Re-sync users with NO explicit position (they inherit the default)."""
default_id = await self._positions.get_default_position_id()
if not default_id:
return 0
assigned = set(await self._positions.list_assigned_user_ids())
count = 0
if self._sf is None:
return 0
from deerflow.persistence.user.model import UserRow
async with self._sf() as session:
all_ids = [uid for (uid,) in (await session.execute(select(UserRow.id))).all()]
for uid in all_ids:
if uid in assigned:
continue
try:
await self.sync_user(uid)
count += 1
except Exception:
logger.exception("default position sync failed for user %s", uid)
return count