feat(square): 新增发布广场功能,智能体/技能按广场分类展示

- 后端新增 PublishSquare/PublishSquaresSettings 配置与读写接口
- agents/skills 增加 square_id 字段及对应迁移脚本
- 前端新增发布广场设置页、技能转移选择器,画廊按广场分 Tab 展示
- lead_agent prompt 及若干持久化层适配调整

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
吉鑫升andClaude Opus 4.8 committed 2026-06-11 11:37:42 +08:00
1 parent 3845d5090b
commit f0aec4cd7f
39 files changed
+1707 -226

No files matched your search

@@ -20,7 +20,7 @@ from deerflow.agents.middlewares.token_usage_middleware import TokenUsageMiddlew
from deerflow.agents.middlewares.tool_error_handling_middleware import build_lead_runtime_middlewares
from deerflow.agents.middlewares.view_image_middleware import ViewImageMiddleware
from deerflow.agents.thread_state import ThreadState
from deerflow.config.agents_config import load_agent_config, validate_agent_id
from deerflow.config.agents_config import load_agent_config, load_agent_soul, validate_agent_id
from deerflow.config.app_config import AppConfig, get_app_config
from deerflow.models import create_chat_model
@@ -535,11 +535,30 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
default_tools = [notebook_search_tool] + default_tools
return create_agent(
model=create_chat_model(name=model_name, thinking_enabled=thinking_enabled, reasoning_effort=reasoning_effort, app_config=resolved_app_config),
tools=default_tools,
middleware=_build_middlewares(config, model_name=model_name, agent_name=agent_id, app_config=resolved_app_config),
system_prompt=apply_prompt_template(
# Custom agents are steered ONLY by their own SOUL.md — no generic
# super-agent system template and no personal memory injection. We branch to
# the agent-only prompt builder whenever a custom agent config carries a
# non-empty SOUL.md. The plain default lead agent (no agent_config) and
# notebook mode keep the full template. See apply_agent_only_prompt_template.
has_agent_soul = bool(agent_config) and bool(load_agent_soul(agent_id))
use_agent_only_prompt = has_agent_soul and not is_notebook_mode
if use_agent_only_prompt:
from deerflow.agents.lead_agent.prompt import apply_agent_only_prompt_template
system_prompt = apply_agent_only_prompt_template(
agent_id=agent_id,
agent_name=agent_display_name,
subagent_enabled=subagent_enabled,
max_concurrent_subagents=max_concurrent_subagents,
available_skills=(set(agent_config.skills or []) if agent_config else None),
app_config=resolved_app_config,
rag_mode_enabled=rag_mode_enabled,
writing_mode=writing_mode,
writing_artifact_path=writing_artifact_path,
)
else:
system_prompt = apply_prompt_template(
subagent_enabled=subagent_enabled,
max_concurrent_subagents=max_concurrent_subagents,
agent_id=agent_id,
@@ -552,6 +571,12 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
rag_mode_enabled=rag_mode_enabled,
is_notebook_mode=is_notebook_mode,
notebook_source_ids=notebook_source_ids,
),
)
return create_agent(
model=create_chat_model(name=model_name, thinking_enabled=thinking_enabled, reasoning_effort=reasoning_effort, app_config=resolved_app_config),
tools=default_tools,
middleware=_build_middlewares(config, model_name=model_name, agent_name=agent_id, app_config=resolved_app_config),
system_prompt=system_prompt,
state_schema=ThreadState,
)
@@ -615,6 +615,127 @@ combined with a FastAPI gateway for REST API access [citation:FastAPI](https://f
"""
# Minimal system prompt for custom agents that should be steered ONLY by their
# own SOUL.md — no generic "super agent" persona scaffolding (role line, thinking
# style, clarification system, citation rules, response-style / critical-reminder
# defaults) and no personal memory injection. Only the mechanical sections an
# agent still needs to actually use its configured skills/tools are kept.
AGENT_ONLY_PROMPT_TEMPLATE = """{soul}
{network_policy_section}{skills_section}
{deferred_tools_section}
{writing_mode_section}
{subagent_section}
<working_directory existed="true">
- User uploads: `/mnt/user-data/uploads` - Files uploaded by the user (automatically listed in context)
- User workspace: `/mnt/user-data/workspace` - Working directory for temporary files
- Output files: `/mnt/user-data/outputs` - Final deliverables must be saved here
**File Management:**
- Uploaded files are automatically listed in the <uploaded_files> section before each request
- Use `read_file` tool to read uploaded files using their paths from the list
- For PDF, PPT, Excel, and Word files, converted Markdown versions (*.md) are available alongside originals
- Treat `/mnt/user-data/workspace` as your default current working directory for coding and file-editing tasks
- Final deliverables must be copied to `/mnt/user-data/outputs` and presented using `present_files` tool
{acp_section}
</working_directory>
"""
def apply_agent_only_prompt_template(
*,
agent_id: str | None,
agent_name: str | None,
subagent_enabled: bool = False,
max_concurrent_subagents: int = 3,
available_skills: set[str] | None = None,
app_config: AppConfig | None = None,
rag_mode_enabled: bool = False,
writing_mode: bool = False,
writing_artifact_path: str | None = None,
) -> str:
"""Build a custom agent's system prompt from ONLY its SOUL.md plus the
mechanical sections required for its configured skills/tools to work.
Unlike :func:`apply_prompt_template`, this deliberately omits:
- the generic ``<role>`` "internal super agent" framing,
- ``<thinking_style>`` / ``<clarification_system>`` / ``<response_style>`` /
``<citations>`` / ``<critical_reminders>`` behavioural defaults,
- the personal ``<memory>`` injection (USER.md / MEMORY.md).
The agent's SOUL.md is therefore the sole source of persona and behaviour.
Skills, deferred tools, the subagent orchestration section (when enabled) and
the working-directory contract are kept because they are capability wiring,
not persona — dropping them would silently break agents that rely on skills
or file output.
"""
storage_agent_id = agent_id if agent_id is not None else agent_name
soul = get_agent_soul(storage_agent_id)
skills_section = get_skills_prompt_section(
available_skills,
app_config=app_config,
display_enabled=rag_mode_enabled,
)
deferred_tools_section = get_deferred_tools_prompt_section(app_config=app_config)
n = max_concurrent_subagents
subagent_section = _build_subagent_section(n, app_config=app_config) if subagent_enabled else ""
current_writing_artifact = (
f"\n**Current Markdown Artifact**\n- Continue editing this existing Markdown file unless the user explicitly asks for a new document: `{writing_artifact_path}`\n"
if writing_artifact_path
else ""
)
writing_mode_section = (
f"""<writing_mode>
Writing mode is enabled for this run.
- Your final deliverable MUST be a Markdown file saved under `/mnt/user-data/outputs/` (e.g. `/mnt/user-data/outputs/report.md`).
- If a current Markdown artifact is provided below, revise that file rather than creating a new one unless the user explicitly asks for a separate document.
- After writing the file, call `present_files` with the Markdown file path.
{current_writing_artifact}</writing_mode>
"""
if writing_mode
else ""
)
acp_section = _build_acp_section(app_config=app_config)
custom_mounts_section = _build_custom_mounts_section(app_config=app_config)
acp_and_mounts_section = "\n".join(section for section in (acp_section, custom_mounts_section) if section)
network_policy_section = _build_network_policy_section()
rag_mode_section = (
"""
<rag_citation_mode>
RAG/reference display mode is enabled.
- Treat every retrieval result from the same user turn as one combined `referenceBatch`; do not restart numbering per search term, tool, or skill.
- Use only the system-provided merged reference numbers in the final answer, formatted as `[1]`, `[2]`, `[1][3][5]`.
- Do not output `<skill-display .../>` in RAG/reference mode; the frontend renders the right reference panel.
</rag_citation_mode>
"""
if rag_mode_enabled
else ""
)
prompt = AGENT_ONLY_PROMPT_TEMPLATE.format(
soul=soul,
skills_section=skills_section,
deferred_tools_section=deferred_tools_section,
writing_mode_section=writing_mode_section,
subagent_section=subagent_section,
network_policy_section=network_policy_section,
acp_section=acp_and_mounts_section,
)
prompt = prompt + rag_mode_section + f"\n<current_date>{datetime.now().strftime('%Y-%m-%d, %A')}</current_date>"
return prompt
def _get_memory_context(agent_name: str | None = None, *, app_config: AppConfig | None = None, injection_enabled: bool = True) -> str:
"""组装注入系统提示词的记忆上下文 (Memory V2)。
@@ -7,7 +7,7 @@ import threading
from typing import Any
import yaml
from pydantic import BaseModel
from pydantic import BaseModel, model_validator
from deerflow.config.paths import get_paths
@@ -56,6 +56,32 @@ def validate_agent_name(name: str | None) -> str | None:
return validate_agent_id(name)
class CommonQuestion(BaseModel):
"""A recommended question shown on the agent chat home / sidebar.
``title`` is the short label rendered on the question chip; ``prompt`` is the
full message actually sent when the user clicks it. Splitting the two lets an
admin keep the chip terse while still sending a richly-worded question.
Legacy configs stored questions as bare strings (content only). The
before-validator coerces such a string into ``{title, prompt}`` so old
config.yaml files keep loading without a migration — the title falls back to
a truncated copy of the content.
"""
title: str = ""
prompt: str = ""
@model_validator(mode="before")
@classmethod
def _coerce_legacy_string(cls, value: Any) -> Any:
if isinstance(value, str):
text = value.strip()
title = text if len(text) <= 40 else text[:40].rstrip() + "…"
return {"title": title, "prompt": text}
return value
class AgentConfig(BaseModel):
"""Configuration for a custom agent."""
@@ -71,7 +97,9 @@ class AgentConfig(BaseModel):
skills: list[str] | None = None
# Frequently-asked questions ("常用问题") shown in the agent chat sidebar.
# Display/UX metadata only — the runtime never reads these. None = none set.
common_questions: list[str] | None = None
# Accepts both the legacy ``list[str]`` shape and the new ``{title, prompt}``
# objects (see CommonQuestion).
common_questions: list[CommonQuestion] | None = None
def load_agent_config(agent_id: str | None) -> AgentConfig | None:
@@ -86,6 +86,75 @@ class PrivateSquareSettings(BaseModel):
model_config = ConfigDict(extra="ignore")
#: Id of the always-present built-in default square (used when the admin has
#: configured no squares, or when a published item picks none).
DEFAULT_SQUARE_ID = "default"
class PublishSquare(BaseModel):
"""One admin-configured publish square (发布广场).
A pure organizational category that published agents/skills can be filed
under — unlike the password-gated :class:`PrivateSquareSettings`, a square
has **no access control**: every logged-in user can browse every square.
Each agent/skill belongs to at most one square (a single ``square_id``
field on the row), so an item can never be "published twice".
"""
id: str = Field(..., description="Stable square id (slug/uuid); used as agents.square_id / skills.square_id")
name: str = Field(..., description="Display name shown as the square's tab label")
description: str = Field(default="", description="Optional description shown in the admin config / tab hint")
model_config = ConfigDict(extra="ignore")
class PublishSquaresSettings(BaseModel):
"""Admin-configurable list of publish squares.
``squares`` is display-ordered. ``default_square_id`` selects the square a
publisher lands in when they do not pick one explicitly. There is always at
least one effective square — :func:`list_publish_squares` injects a built-in
"默认广场" when the admin has configured none, so the publish flow always has
a valid target.
"""
squares: list[PublishSquare] = Field(default_factory=list, description="Ordered list of configured squares")
default_square_id: str = Field(default=DEFAULT_SQUARE_ID, description="Square id used when a publisher picks none")
model_config = ConfigDict(extra="ignore")
def list_publish_squares(settings: PublishSquaresSettings) -> list[PublishSquare]:
"""Return the effective square list, always non-empty.
Falls back to a single built-in default square when the admin has not
configured any, so callers never have to special-case the empty state.
"""
if settings.squares:
return list(settings.squares)
return [PublishSquare(id=DEFAULT_SQUARE_ID, name="默认广场", description="")]
def resolve_default_square_id(settings: PublishSquaresSettings) -> str:
"""Resolve the effective default square id against the configured set."""
ids = [s.id for s in settings.squares]
if settings.default_square_id and settings.default_square_id in ids:
return settings.default_square_id
return ids[0] if ids else DEFAULT_SQUARE_ID
def normalize_square_id(square_id: str | None, settings: PublishSquaresSettings) -> str:
"""Coerce an arbitrary ``square_id`` to a valid configured square id.
Empty / unknown / orphaned (square later deleted) ids all collapse to the
effective default square, so a published item always resolves to a real
tab.
"""
default_id = resolve_default_square_id(settings)
if not square_id:
return default_id
valid = {s.id for s in list_publish_squares(settings)}
return square_id if square_id in valid else default_id
class LeaderboardSettings(BaseModel):
"""Admin-configurable defaults for the user leaderboard analytics."""
@@ -102,6 +171,7 @@ class SystemSettings(BaseModel):
prompt_prefix: PromptPrefixSettings = Field(default_factory=PromptPrefixSettings)
private_square: PrivateSquareSettings = Field(default_factory=PrivateSquareSettings)
publish_squares: PublishSquaresSettings = Field(default_factory=PublishSquaresSettings)
appearance: AppearanceSettings = Field(default_factory=AppearanceSettings)
citation_display: CitationDisplaySettings = Field(default_factory=CitationDisplaySettings)
leaderboard: LeaderboardSettings = Field(default_factory=LeaderboardSettings)
@@ -229,8 +229,8 @@ const GRAPH = __GRAPH_DATA__;
// Theme is supplied by the embedding iframe (it can't read the parent's CSS).
const THEME = (new URLSearchParams(location.search).get('theme') === 'light') ? 'light' : 'dark';
const PAL = {
dark: {note:'#5b8cff', entity:'#ffb454', label:'rgba(231,236,255,.92)', edge:[140,165,255], halo:'rgba(11,16,32,.55)'},
light: {note:'#2f6df6', entity:'#d97706', label:'rgba(31,36,51,.92)', edge:[70,110,200], halo:'rgba(255,255,255,.65)'},
dark: {note:'#5b8cff', entity:'#ffb454', label:'rgba(231,236,255,.92)', edge:[150,178,255], halo:'rgba(11,16,32,.55)'},
light: {note:'#2f6df6', entity:'#d97706', label:'rgba(31,36,51,.92)', edge:[63,96,168], halo:'rgba(255,255,255,.7)'},
}[THEME];
document.documentElement.classList.toggle('light', THEME === 'light');
document.getElementById('lg-note').style.background = PAL.note;
@@ -317,12 +317,16 @@ function draw(){
const act=active(), nb=neighbors(act), zoomed=cam.k>1.35;
const [er,eg,eb]=PAL.edge;
// edges: dim by default; when a node is focused, only its edges stay bright.
// edges: clearly visible by default; when a node is focused, only its edges
// stay bright and the rest fade back (but never to invisible).
for(const e of edges){
const lit = act && (e.s===act||e.t===act);
const op = act ? (lit?0.9:0.05) : Math.min(0.5,0.12+e.w*0.05);
const op = act ? (lit?0.98:0.12) : Math.min(0.85,0.55+e.w*0.06);
// Keep a stable on-screen thickness regardless of zoom (>=1px), so lines
// never thin out to a hairline when zoomed in or on dense graphs.
const screenW = lit ? 2.6 : Math.min(2.4,1.4+e.w*0.45);
ctx.strokeStyle='rgba('+er+','+eg+','+eb+','+op+')';
ctx.lineWidth=(lit?1.6:0.8)*Math.max(0.6,e.w*0.55)/Math.sqrt(cam.k);
ctx.lineWidth=Math.max(1,screenW)/cam.k;
ctx.beginPath();ctx.moveTo(e.s.x,e.s.y);ctx.lineTo(e.t.x,e.t.y);ctx.stroke();
}
// nodes
@@ -131,6 +131,8 @@ class AgentStore(ABC):
admin: bool = False,
sort: str = "time_desc",
owner: str | None = None,
square_id: str | None = None,
square_is_default: bool = False,
) -> tuple[list[dict[str, Any]], int]:
"""Return one page of agents plus the total matching count.
@@ -61,6 +61,8 @@ class MemoryAgentStore(AgentStore):
"description": data.get("description") or "",
"user_id": data.get("user_id"),
"published": bool(data.get("published", False)),
"is_private": bool(data.get("is_private", False)),
"square_id": str(data.get("square_id") or ""),
"featured_order": None,
"created_at": now,
"updated_at": now,
@@ -93,7 +95,7 @@ class MemoryAgentStore(AgentStore):
row = self._agents.get(agent_id)
if row is None or row.get("user_id") != user_id:
return None
for key in ("name", "description", "published"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
row[key] = data[key]
row["updated_at"] = _now()
@@ -103,7 +105,7 @@ class MemoryAgentStore(AgentStore):
row = self._agents.get(agent_id)
if row is None or row.get("user_id") is not None:
return None
for key in ("name", "description", "published"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
row[key] = data[key]
row["updated_at"] = _now()
@@ -159,7 +161,7 @@ class MemoryAgentStore(AgentStore):
row = self._agents.get(agent_id)
if row is None:
return None
for key in ("name", "description", "published", "is_private"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
row[key] = data[key]
row["updated_at"] = _now()
@@ -198,16 +200,27 @@ class MemoryAgentStore(AgentStore):
admin: bool = False,
sort: str = "time_desc",
owner: str | None = None,
square_id: str | None = None,
square_is_default: bool = False,
) -> tuple[list[dict[str, Any]], int]:
# NOTE: the in-memory store has no tag-assignment data, so ``tag_ids``
# is ignored here. Tag-filter behavior is covered by the SQL repo tests.
owner_key = owner.strip() if owner and owner.strip() else None
square_key = square_id.strip() if square_id and square_id.strip() else None
def _square_ok(a: dict[str, Any]) -> bool:
if square_key is None:
return True
sid = str(a.get("square_id") or "")
return sid == square_key or (square_is_default and sid == "")
matched = [
a
for a in self._agents.values()
if self._matches_scope(a, user_id=user_id, scope=scope, admin=admin)
and (not search or not search.strip() or name_matches(a.get("name") or "", search))
and (owner_key is None or a.get("user_id") == owner_key)
and _square_ok(a)
]
if sort == "time_asc":
matched.sort(key=lambda a: (a.get("created_at") or "", a.get("id") or ""))
@@ -27,6 +27,12 @@ class AgentRow(Base):
# visible to its owner in the "我的" tab, and visible to anyone in the
# private-square listing once the password has been verified.
is_private: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
# Publish square (发布广场) this agent is filed under. A pure organizational
# category with no access control — independent of ``published`` /
# ``is_private``. Empty string = "not assigned" → the listing layer treats
# it as the admin-configured default square. Each agent belongs to at most
# one square (single column), so it can never be published to two squares.
square_id: Mapped[str] = mapped_column(String(64), nullable=False, default="", index=True)
# NULL = not featured on the homepage selector. Non-NULL = admin-curated
# featured rank (lower sorts first). Only ``published=True`` agents are
# eligible; the router enforces that invariant on writes. BIGINT so the
@@ -37,7 +43,7 @@ class AgentRow(Base):
updated_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
class AgentFavoriteRow(Base):
class AgentFavoriteRow(Base):
"""A user's bookmark of a (typically public-square) agent.
Lets a user collect agents from the 广场 (square) into their "我的" tab
@@ -51,22 +57,22 @@ class AgentFavoriteRow(Base):
id: Mapped[str] = mapped_column(String(64), primary_key=True)
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
agent_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
class AgentPinRow(Base):
"""A per-user pin that keeps an agent near the top of that user's lists."""
__tablename__ = "agent_pins"
__table_args__ = (UniqueConstraint("user_id", "agent_id", name="uq_agent_pins_user_agent"),)
id: Mapped[str] = mapped_column(String(64), primary_key=True)
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
agent_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
class AgentSkillRow(Base):
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
class AgentPinRow(Base):
"""A per-user pin that keeps an agent near the top of that user's lists."""
__tablename__ = "agent_pins"
__table_args__ = (UniqueConstraint("user_id", "agent_id", name="uq_agent_pins_user_agent"),)
id: Mapped[str] = mapped_column(String(64), primary_key=True)
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
agent_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
class AgentSkillRow(Base):
"""Denormalized cache of a custom agent's selected skills.
``config.yaml`` under ``.deer-flow/agents/{id}/`` stays the source of truth
@@ -93,6 +93,7 @@ class AgentRepository(AgentStore):
user_id=data.get("user_id"),
published=bool(data.get("published", False)),
is_private=bool(data.get("is_private", False)),
square_id=str(data.get("square_id") or ""),
created_at=now,
updated_at=now,
)
@@ -131,7 +132,7 @@ class AgentRepository(AgentStore):
row = await session.get(AgentRow, agent_id)
if row is None or row.user_id != user_id:
return None
for key in ("name", "description", "published", "is_private"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
setattr(row, key, data[key])
row.updated_at = datetime.now(UTC)
@@ -144,7 +145,7 @@ class AgentRepository(AgentStore):
row = await session.get(AgentRow, agent_id)
if row is None or row.user_id is not None:
return None
for key in ("name", "description", "published", "is_private"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
setattr(row, key, data[key])
row.updated_at = datetime.now(UTC)
@@ -224,7 +225,7 @@ class AgentRepository(AgentStore):
row = await session.get(AgentRow, agent_id)
if row is None:
return None
for key in ("name", "description", "published", "is_private"):
for key in ("name", "description", "published", "is_private", "square_id"):
if key in data:
setattr(row, key, data[key])
row.updated_at = datetime.now(UTC)
@@ -290,6 +291,8 @@ class AgentRepository(AgentStore):
admin: bool = False,
sort: str = "time_desc",
owner: str | None = None,
square_id: str | None = None,
square_is_default: bool = False,
) -> tuple[list[dict[str, Any]], int]:
filters = []
scope_filter = self._scope_filter(user_id=user_id, scope=scope, admin=admin)
@@ -302,6 +305,14 @@ class AgentRepository(AgentStore):
if owner and owner.strip():
# Filter to one publisher. Built-in agents (user_id IS NULL) never match.
filters.append(AgentRow.user_id == owner.strip())
if square_id and square_id.strip():
sid = square_id.strip()
if square_is_default:
# Legacy / unassigned rows (square_id == "") belong to the
# default square, so include them alongside explicit matches.
filters.append(or_(AgentRow.square_id == sid, AgentRow.square_id == ""))
else:
filters.append(AgentRow.square_id == sid)
count_stmt = select(func.count()).select_from(AgentRow)
pin_subq = select(AgentPinRow.agent_id).where(AgentPinRow.user_id == user_id)
@@ -0,0 +1,74 @@
"""Add ``agents.square_id`` and ``skills.square_id`` for the publish-square (发布广场) feature.
A nullable-default (server_default '') string column tagging which admin-
configured publish square an agent / skill is filed under. Pure organizational
category — independent of the ``published`` / ``is_private`` flags. Empty string
means "unassigned" and is resolved to the default square at read time.
Revision ID: 20260611_01
Revises: 20260609_02
Create Date: 2026-06-11
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260611_01"
down_revision = "20260609_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def _has_index(table_name: str, index_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name))
def _add_square_id(table_name: str, index_name: str) -> None:
if _has_table(table_name) and not _has_column(table_name, "square_id"):
op.add_column(
table_name,
sa.Column(
"square_id",
sa.String(length=64),
nullable=False,
server_default="",
),
)
if _has_table(table_name) and not _has_index(table_name, index_name):
op.create_index(index_name, table_name, ["square_id"])
def _drop_square_id(table_name: str, index_name: str) -> None:
if _has_index(table_name, index_name):
op.drop_index(index_name, table_name=table_name)
if _has_column(table_name, "square_id"):
op.drop_column(table_name, "square_id")
def upgrade() -> None:
_add_square_id("agents", "ix_agents_square_id")
_add_square_id("skills", "ix_skills_square_id")
def downgrade() -> None:
_drop_square_id("skills", "ix_skills_square_id")
_drop_square_id("agents", "ix_agents_square_id")
@@ -71,6 +71,7 @@ class MemorySkillStore(SkillStore):
"published": bool(data.get("published", False)),
"detail": data.get("detail"),
"name_zh": data.get("name_zh"),
"square_id": str(data.get("square_id") or ""),
"created_at": _now(),
"updated_at": _now(),
}
@@ -106,6 +107,8 @@ class MemorySkillStore(SkillStore):
record["detail"] = data["detail"]
if "name_zh" in data:
record["name_zh"] = data["name_zh"]
if "square_id" in data:
record["square_id"] = str(data["square_id"] or "")
record["updated_at"] = _now()
return _with_derived(_copy(record)) # type: ignore[arg-type]
@@ -121,6 +124,8 @@ class MemorySkillStore(SkillStore):
record["detail"] = data["detail"]
if "name_zh" in data:
record["name_zh"] = data["name_zh"]
if "square_id" in data:
record["square_id"] = str(data["square_id"] or "")
record["updated_at"] = _now()
return _with_derived(_copy(record)) # type: ignore[arg-type]
@@ -33,6 +33,10 @@ class SkillRow(Base):
# the on-disk SKILL.md) so it can be set for built-in skills too, and so the
# shared source file is never rewritten.
name_zh: Mapped[str | None] = mapped_column(String(128), nullable=True, default=None)
# Publish square (发布广场) this skill is filed under once published. Pure
# organizational category, no access control. Empty string = unassigned →
# the listing layer resolves it to the default square. One square per skill.
square_id: Mapped[str] = mapped_column(String(64), nullable=False, default="", index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
@@ -65,6 +65,7 @@ class SkillRepository(SkillStore):
published=bool(data.get("published", False)),
detail=data.get("detail"),
name_zh=data.get("name_zh"),
square_id=str(data.get("square_id") or ""),
created_at=now,
updated_at=now,
)
@@ -109,6 +110,8 @@ class SkillRepository(SkillStore):
row.detail = data["detail"]
if "name_zh" in data:
row.name_zh = data["name_zh"]
if "square_id" in data:
row.square_id = str(data["square_id"] or "")
row.updated_at = datetime.now(UTC)
await session.commit()
await session.refresh(row)
@@ -127,6 +130,8 @@ class SkillRepository(SkillStore):
row.detail = data["detail"]
if "name_zh" in data:
row.name_zh = data["name_zh"]
if "square_id" in data:
row.square_id = str(data["square_id"] or "")
row.updated_at = datetime.now(UTC)
await session.commit()
await session.refresh(row)