feat: 岗位职责迁至业务链席位,并支持 WeKnora 嵌入页知识库切换

将岗位职责从智能体配置迁移到业务链席位 JSON,会商面板只读展示;WeKnora 嵌入 iframe 支持在授权可见范围内切换知识库并重新签发会话。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-19 22:26:40 +08:00
1 parent e860357563
commit e881c242fe
16 files changed
+434 -257

No files matched your search

@@ -69,11 +69,6 @@ class AgentResponse(BaseModel):
description="会商席位「技能识别强化」开关 (config.yaml). True = 本智能体作为会商席位时强化技能识别 (与业务链条同名开关取 OR). None/False = 关 (默认).",
)
job_responsibilities: str | None = Field(
default=None,
description="岗位职责 (config.yaml). Shown above 常用问题 in the agent configuration panel. None/empty = not set.",
)
llmwiki_knowledge_base_ids: list[str] | None = Field(
default=None,
description="DeerFlow LLMWiki mapping ids this agent may offer for conversation retrieval.",
@@ -131,7 +126,6 @@ class AgentCreateRequest(BaseModel):
common_questions: list[CommonQuestion] | None = Field(default=None, description="Recommended questions (常用问题) persisted to config.yaml. Each item is {title, prompt}; legacy strings are coerced.")
template_name: str | None = Field(default=None, description="入库模板名 persisted to config.yaml. Enables publishing markdown artifacts to the external knowledge-ingest API.")
seat_skill_directive: bool | None = Field(default=None, description="会商席位「技能识别强化」开关 persisted to config.yaml. None/False = off (默认).")
job_responsibilities: str | None = Field(default=None, description="岗位职责 persisted to config.yaml. Empty/None = not set.")
llmwiki_knowledge_base_ids: list[str] | None = Field(
default=None,
max_length=100,
@@ -154,7 +148,6 @@ class AgentUpdateRequest(BaseModel):
common_questions: list[CommonQuestion] | None = Field(default=None, description="Updated recommended questions (常用问题, config.yaml). Each item is {title, prompt}; legacy strings are coerced.")
template_name: str | None = Field(default=None, description="Updated 入库模板名 (config.yaml). Empty string clears it.")
seat_skill_directive: bool | None = Field(default=None, description="Updated 会商席位「技能识别强化」开关 (config.yaml).")
job_responsibilities: str | None = Field(default=None, description="Updated 岗位职责 (config.yaml). Empty string clears it.")
llmwiki_knowledge_base_ids: list[str] | None = Field(
default=None,
max_length=100,
@@ -294,7 +287,6 @@ def _write_agent_config(
common_questions: list[CommonQuestion] | None = None,
template_name: str | None = None,
seat_skill_directive: bool | None = None,
job_responsibilities: str | None = None,
llmwiki_knowledge_base_ids: list[str] | None = None,
) -> None:
agent_dir = get_paths().agent_dir(agent_id)
@@ -327,8 +319,6 @@ def _write_agent_config(
# 会商席位技能识别强化开关:仅当显式设置时写入(None = 不写, 由 AgentConfig 默认为关)。
if seat_skill_directive is not None:
config_data["seat_skill_directive"] = bool(seat_skill_directive)
if job_responsibilities is not None and job_responsibilities.strip():
config_data["job_responsibilities"] = job_responsibilities.strip()
if llmwiki_knowledge_base_ids is not None:
config_data["llmwiki_knowledge_base_ids"] = list(
dict.fromkeys(item.strip() for item in llmwiki_knowledge_base_ids if item.strip())
@@ -346,7 +336,6 @@ def _load_config_extras(agent_id: str) -> dict[str, Any]:
"common_questions": None,
"template_name": None,
"seat_skill_directive": None,
"job_responsibilities": None,
"llmwiki_knowledge_base_ids": None,
}
try:
@@ -362,7 +351,6 @@ def _load_config_extras(agent_id: str) -> dict[str, Any]:
"common_questions": cfg.common_questions,
"template_name": cfg.template_name,
"seat_skill_directive": cfg.seat_skill_directive,
"job_responsibilities": cfg.job_responsibilities,
"llmwiki_knowledge_base_ids": cfg.llmwiki_knowledge_base_ids,
}
@@ -531,7 +519,6 @@ def _record_to_response(
"common_questions": None,
"template_name": None,
"seat_skill_directive": None,
"job_responsibilities": None,
"llmwiki_knowledge_base_ids": None,
}
if include_extras:
@@ -558,7 +545,6 @@ def _record_to_response(
common_questions=extras.get("common_questions"),
template_name=extras.get("template_name"),
seat_skill_directive=extras.get("seat_skill_directive"),
job_responsibilities=extras.get("job_responsibilities"),
llmwiki_knowledge_base_ids=extras.get("llmwiki_knowledge_base_ids"),
featured_order=record.get("featured_order"),
)
@@ -891,7 +877,6 @@ async def create_agent_endpoint(request: AgentCreateRequest, http_request: Reque
common_questions=request.common_questions,
template_name=request.template_name,
seat_skill_directive=request.seat_skill_directive,
job_responsibilities=request.job_responsibilities,
llmwiki_knowledge_base_ids=llmwiki_ids,
)
_write_agent_soul(agent_id, request.soul)
@@ -974,14 +959,13 @@ async def update_agent(agent_id: str, request: AgentUpdateRequest, http_request:
next_common_questions = request.common_questions if "common_questions" in fields_set else existing_extras["common_questions"]
next_template_name = request.template_name if "template_name" in fields_set else existing_extras["template_name"]
next_seat_skill_directive = request.seat_skill_directive if "seat_skill_directive" in fields_set else existing_extras["seat_skill_directive"]
next_job_responsibilities = request.job_responsibilities if "job_responsibilities" in fields_set else existing_extras["job_responsibilities"]
next_llmwiki_ids = (
await _validate_llmwiki_bindings(http_request, request.llmwiki_knowledge_base_ids)
if "llmwiki_knowledge_base_ids" in fields_set
else existing_extras["llmwiki_knowledge_base_ids"]
)
config_dirty = bool(update_data) or any(key in fields_set for key in ("skills", "model", "tool_groups", "common_questions", "template_name", "seat_skill_directive", "job_responsibilities", "llmwiki_knowledge_base_ids"))
config_dirty = bool(update_data) or any(key in fields_set for key in ("skills", "model", "tool_groups", "common_questions", "template_name", "seat_skill_directive", "llmwiki_knowledge_base_ids"))
if config_dirty:
_write_agent_config(
agent_id,
@@ -993,7 +977,6 @@ async def update_agent(agent_id: str, request: AgentUpdateRequest, http_request:
common_questions=next_common_questions,
template_name=next_template_name,
seat_skill_directive=next_seat_skill_directive,
job_responsibilities=next_job_responsibilities,
llmwiki_knowledge_base_ids=next_llmwiki_ids,
)
# Keep the listing cache in lock-step with config.yaml, but only
@@ -9,7 +9,7 @@ import re
import time
from dataclasses import replace
from typing import Any, Literal
from urllib.parse import quote, urlencode, urlsplit
from urllib.parse import quote, unquote, urlencode, urlsplit
import httpx
from fastapi import APIRouter, BackgroundTasks, File, HTTPException, Query, Request, UploadFile
@@ -27,11 +27,21 @@ from app.gateway.llmwiki_deposit import (
ensure_conversation_deposit_mapping,
)
from app.gateway.weknora_embed import (
WEKNORA_EMBED_COOKIE as _WEKNORA_EMBED_COOKIE,
WEKNORA_EMBED_API_PREFIX as _WEKNORA_EMBED_API_PREFIX,
)
from app.gateway.weknora_embed import (
WEKNORA_EMBED_COOKIE as _WEKNORA_EMBED_COOKIE,
)
from app.gateway.weknora_embed import (
WEKNORA_EMBED_TTL_SECONDS as _WEKNORA_EMBED_TTL_SECONDS,
)
from app.gateway.weknora_embed import (
WeKnoraEmbedContext,
)
from app.gateway.weknora_embed import (
sign_weknora_embed_payload as _sign_embed_payload,
)
from app.gateway.weknora_embed import (
verify_weknora_embed_cookie as _verify_embed_cookie,
)
from deerflow.config.agents_config import load_agent_config
@@ -292,21 +302,9 @@ def _admin_session_cache_key(runtime: Any) -> str:
def _extract_weknora_token(payload: dict[str, Any]) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
source = payload.get("data") if isinstance(payload.get("data"), dict) else payload
token = str(source.get("token") or source.get("access_token") or payload.get("token") or payload.get("access_token") or "")
refresh_token = str(
source.get("refresh_token")
or source.get("refreshToken")
or payload.get("refresh_token")
or payload.get("refreshToken")
or ""
)
refresh_token = str(source.get("refresh_token") or source.get("refreshToken") or payload.get("refresh_token") or payload.get("refreshToken") or "")
user = source.get("user") if isinstance(source.get("user"), dict) else payload.get("user")
tenant = (
source.get("tenant")
if isinstance(source.get("tenant"), dict)
else source.get("active_tenant")
if isinstance(source.get("active_tenant"), dict)
else payload.get("tenant")
)
tenant = source.get("tenant") if isinstance(source.get("tenant"), dict) else source.get("active_tenant") if isinstance(source.get("active_tenant"), dict) else payload.get("tenant")
return token, refresh_token, user if isinstance(user, dict) else None, tenant if isinstance(tenant, dict) else None
@@ -377,6 +375,79 @@ async def _read_embed_context(request: Request) -> WeKnoraEmbedContext:
ctx,
can_write=writable is not None,
is_conversation_deposit=_is_conversation_deposit_mapping(readable),
allowed_weknora_ids=_embed_allowed_weknora_ids(ctx),
)
def _embed_allowed_weknora_ids(ctx: WeKnoraEmbedContext) -> tuple[str, ...]:
"""Return the signed knowledge-base allowlist, always retaining the active base."""
return tuple(dict.fromkeys(value for value in (ctx.weknora_id, *ctx.allowed_weknora_ids) if value))
def _embed_context_payload(ctx: WeKnoraEmbedContext) -> dict[str, Any]:
return {
"mapping_id": ctx.mapping_id,
"weknora_id": ctx.weknora_id,
"user_id": ctx.user_id,
"is_admin": ctx.is_admin,
"can_write": ctx.can_write,
"is_conversation_deposit": ctx.is_conversation_deposit,
"allowed_weknora_ids": list(_embed_allowed_weknora_ids(ctx)),
"exp": ctx.exp,
}
def _weknora_id_from_platform_path(path: str) -> str | None:
prefix = "/platform/knowledge-bases/"
if not path.startswith(prefix):
return None
raw_id = path.removeprefix(prefix)
if not raw_id or "/" in raw_id:
return None
return unquote(raw_id)
async def _switch_embed_context(
request: Request,
ctx: WeKnoraEmbedContext,
weknora_id: str,
) -> WeKnoraEmbedContext:
"""Resolve a permitted native-UI switch to the exact cmzs mapping.
The embedded WeKnora UI uses a service-admin token, so every target remains
constrained to an ID signed into this short-lived session and is checked
again against the cmzs visibility rules before its page can be proxied.
"""
if weknora_id not in _embed_allowed_weknora_ids(ctx):
raise HTTPException(status_code=403, detail="Knowledge base is outside the embedded session scope")
store = _store(request)
mapped = await store.get_by_weknora_id(weknora_id)
if mapped is None:
raise HTTPException(status_code=403, detail="Knowledge base is not managed by cmzs")
readable = await store.get_authorized(
str(mapped["id"]),
ctx.user_id,
write=False,
is_admin=ctx.is_admin,
)
if readable is None or str(readable.get("weknora_id") or "") != weknora_id:
raise HTTPException(status_code=403, detail="Knowledge base is no longer authorized")
writable = None
if not _is_conversation_deposit_mapping(readable):
writable = await store.get_authorized(
str(readable["id"]),
ctx.user_id,
write=True,
is_admin=ctx.is_admin,
)
return replace(
ctx,
mapping_id=str(readable["id"]),
weknora_id=weknora_id,
can_write=writable is not None,
is_conversation_deposit=_is_conversation_deposit_mapping(readable),
)
@@ -431,12 +502,7 @@ def _body_kb_id(body: Any) -> str:
def _request_kb_id(request: Request, body: Any) -> str:
return _body_kb_id(body) or str(
request.query_params.get("kb_id")
or request.query_params.get("knowledge_base_id")
or request.query_params.get("source_kb_id")
or ""
)
return _body_kb_id(body) or str(request.query_params.get("kb_id") or request.query_params.get("knowledge_base_id") or request.query_params.get("source_kb_id") or "")
async def _admin_json(runtime: Any, path: str, *, token: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
@@ -533,12 +599,7 @@ async def _authorize_weknora_api_proxy(
raise HTTPException(status_code=403, detail="Global WeKnora knowledge collection is not allowed")
action = tail[1]
if read_method and action == "batch":
ids = [
item.strip()
for raw in request.query_params.getlist("ids")
for item in raw.split(",")
if item.strip()
]
ids = [item.strip() for raw in request.query_params.getlist("ids") for item in raw.split(",") if item.strip()]
if not ids:
raise HTTPException(status_code=403, detail="Batch operation must include document ids")
for document_id in ids:
@@ -574,14 +635,19 @@ async def _authorize_weknora_api_proxy(
# A few read-only metadata endpoints are required by the original detail
# page to render upload controls and current-tenant state. They do not
# expose other knowledge-base contents.
if read_method and tail and tail[0] in {
"models",
"system",
"storage-backends",
"vector-stores",
"web-search-providers",
"mcp-services",
}:
if (
read_method
and tail
and tail[0]
in {
"models",
"system",
"storage-backends",
"vector-stores",
"web-search-providers",
"mcp-services",
}
):
return
raise HTTPException(status_code=403, detail="This WeKnora endpoint is blocked in embedded detail mode")
@@ -598,27 +664,29 @@ def _filter_knowledge_base_list_response(response: httpx.Response, ctx: WeKnoraE
if not isinstance(payload, dict):
return None
def keep_current(value: Any) -> Any:
allowed_weknora_ids = set(_embed_allowed_weknora_ids(ctx))
def keep_allowed(value: Any) -> Any:
if isinstance(value, list):
return [item for item in value if isinstance(item, dict) and str(item.get("id") or "") == ctx.weknora_id]
return [item for item in value if isinstance(item, dict) and str(item.get("id") or "") in allowed_weknora_ids]
if isinstance(value, dict):
result = dict(value)
for key in ("items", "list", "knowledge_bases", "knowledge", "records", "data"):
if isinstance(result.get(key), list):
result[key] = keep_current(result[key])
result[key] = keep_allowed(result[key])
result["total"] = len(result[key])
return result
return value
if isinstance(payload.get("data"), list):
payload["data"] = keep_current(payload["data"])
payload["data"] = keep_allowed(payload["data"])
payload["total"] = len(payload["data"])
elif isinstance(payload.get("data"), dict):
payload["data"] = keep_current(payload["data"])
payload["data"] = keep_allowed(payload["data"])
else:
for key in ("items", "list", "knowledge_bases", "records"):
if isinstance(payload.get(key), list):
payload[key] = keep_current(payload[key])
payload[key] = keep_allowed(payload[key])
payload["total"] = len(payload[key])
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
@@ -654,7 +722,7 @@ def _with_public_prefix(prefix: str, path: str) -> str:
def _without_public_prefix(prefix: str, path: str) -> str:
if prefix and path.startswith(f"{prefix}/"):
return path[len(prefix):]
return path[len(prefix) :]
if prefix and path == prefix:
return "/"
return path
@@ -826,6 +894,7 @@ def _weknora_embed_injection(
"user": user,
"tenant": tenant,
"weknoraId": ctx.weknora_id,
"allowedWeKnoraIds": list(_embed_allowed_weknora_ids(ctx)),
"publicPrefix": public_prefix,
"apiPrefix": _with_public_prefix(public_prefix, _WEKNORA_EMBED_API_PREFIX),
}
@@ -896,8 +965,7 @@ html.deerflow-weknora-embed .document-header {{
padding-right: 32px !important;
background: var(--td-bg-color-page) !important;
}}
html.deerflow-weknora-embed .breadcrumb-link:first-child,
html.deerflow-weknora-embed .breadcrumb-link.dropdown {{
html.deerflow-weknora-embed .breadcrumb-link:first-child {{
pointer-events: none !important;
cursor: default !important;
}}
@@ -1223,11 +1291,24 @@ html.deerflow-source-detail-open [data-deerflow-source-detail-panel="true"] [cla
}}
const allowedPath = cfg.allowedPath;
const allowedWeKnoraIds = new Set(
[cfg.weknoraId, ...(Array.isArray(cfg.allowedWeKnoraIds) ? cfg.allowedWeKnoraIds : [])]
.filter(Boolean)
);
const knowledgeBasePathPrefix = (cfg.publicPrefix || "") + "/platform/knowledge-bases/";
function isAllowedKnowledgeBasePath(pathname) {{
if (!pathname.startsWith(knowledgeBasePathPrefix)) return false;
const encodedId = pathname.slice(knowledgeBasePathPrefix.length);
if (!encodedId || encodedId.includes("/")) return false;
try {{ return allowedWeKnoraIds.has(decodeURIComponent(encodedId)); }} catch (_) {{ return false; }}
}}
function allowedUrl(url) {{
try {{
const next = new URL(url, location.origin);
if (next.origin !== location.origin) return null;
if (next.pathname === allowedPath) return next.pathname + next.search + next.hash;
if (next.pathname === allowedPath || isAllowedKnowledgeBasePath(next.pathname)) {{
return next.pathname + next.search + next.hash;
}}
const query = new URLSearchParams(location.search);
if (cfg.tab && !query.has("tab")) query.set("tab", cfg.tab);
return allowedPath + (query.toString() ? "?" + query.toString() : "") + location.hash;
@@ -1236,10 +1317,21 @@ html.deerflow-source-detail-open [data-deerflow-source-detail-panel="true"] [cla
}}
}}
function enforceLocation() {{
if (location.pathname !== allowedPath) {{
if (location.pathname !== allowedPath && !isAllowedKnowledgeBasePath(location.pathname)) {{
history.replaceState(history.state, "", allowedPath + location.search + location.hash);
}}
}}
function reloadForKnowledgeBaseSwitch(target, replace) {{
try {{
const next = new URL(target, location.origin);
if (next.pathname === location.pathname || !isAllowedKnowledgeBasePath(next.pathname)) return false;
if (replace) location.replace(next.href);
else location.assign(next.href);
return true;
}} catch (_) {{
return false;
}}
}}
function purgeGuides() {{
document
.querySelectorAll(
@@ -1339,8 +1431,16 @@ html.deerflow-source-detail-open [data-deerflow-source-detail-panel="true"] [cla
}}
const rawPushState = history.pushState.bind(history);
const rawReplaceState = history.replaceState.bind(history);
history.pushState = (state, title, url) => rawPushState(state, title, url ? allowedUrl(url) : location.href);
history.replaceState = (state, title, url) => rawReplaceState(state, title, url ? allowedUrl(url) : location.href);
history.pushState = (state, title, url) => {{
const target = url ? allowedUrl(url) : location.href;
if (url && target && reloadForKnowledgeBaseSwitch(target, false)) return;
return rawPushState(state, title, target);
}};
history.replaceState = (state, title, url) => {{
const target = url ? allowedUrl(url) : location.href;
if (url && target && reloadForKnowledgeBaseSwitch(target, true)) return;
return rawReplaceState(state, title, target);
}};
window.addEventListener("popstate", enforceLocation);
document.addEventListener("click", (event) => {{
const anchor = event.target && event.target.closest ? event.target.closest("a[href]") : null;
@@ -1349,6 +1449,7 @@ html.deerflow-source-detail-open [data-deerflow-source-detail-panel="true"] [cla
if (target && new URL(anchor.href, location.origin).pathname !== allowedPath) {{
event.preventDefault();
event.stopPropagation();
if (reloadForKnowledgeBaseSwitch(target, false)) return;
history.replaceState(history.state, "", target);
}}
}}, true);
@@ -1365,7 +1466,7 @@ html.deerflow-source-detail-open [data-deerflow-source-detail-panel="true"] [cla
hideWeKnoraShell();
tickSourceDetail();
if (ready) return;
if (!force && (location.pathname !== allowedPath || !hasDetailShell())) return;
if (!force && (!isAllowedKnowledgeBasePath(location.pathname) && location.pathname !== allowedPath || !hasDetailShell())) return;
ready = true;
root.classList.add("deerflow-weknora-ready");
}}
@@ -1553,10 +1654,7 @@ async def _proxy_weknora_request(
def _is_conversation_deposit_mapping(row: dict[str, Any]) -> bool:
return (
str(row.get("owner_user_id") or "") == CONVERSATION_DEPOSIT_OWNER_USER_ID
and str(row.get("name") or "").strip() == CONVERSATION_DEPOSIT_KB_NAME
)
return str(row.get("owner_user_id") or "") == CONVERSATION_DEPOSIT_OWNER_USER_ID and str(row.get("name") or "").strip() == CONVERSATION_DEPOSIT_KB_NAME
_LEGACY_BRAND_PATTERN = re.compile(r"deer[\s_-]*flow", re.IGNORECASE)
@@ -1612,13 +1710,7 @@ def _mapping_view(row: dict[str, Any], remote: dict[str, Any] | None, *, actor_u
source = remote or {}
is_conversation_deposit = _is_conversation_deposit_mapping(row)
is_owner = row.get("owner_user_id") == actor_user_id
description = (
CONVERSATION_DEPOSIT_KB_DESCRIPTION
if is_conversation_deposit
else source.get("description")
if source.get("description") is not None
else row.get("description") or ""
)
description = CONVERSATION_DEPOSIT_KB_DESCRIPTION if is_conversation_deposit else source.get("description") if source.get("description") is not None else row.get("description") or ""
return {
"id": row["id"],
"remote_status": "available" if remote is not None else "missing",
@@ -1871,19 +1963,28 @@ async def _prepare_weknora_embed_session(
) -> tuple[str, dict[str, Any]]:
_runtime_for_iframe_proxy(request)
row, user_id, is_admin = await _authorized_mapping(request, mapping_id, write=False)
visible_rows = await _store(request).list_visible(
user_id,
scope="all",
# The iframe must mirror the knowledge-base picker, not grant an
# administrator an unlisted user's private knowledge bases.
is_admin=False,
)
writable = None
if not _is_conversation_deposit_mapping(row):
writable = await _store(request).get_authorized(mapping_id, user_id, write=True, is_admin=is_admin)
weknora_id = str(row["weknora_id"])
return weknora_id, {
"mapping_id": mapping_id,
"weknora_id": weknora_id,
"user_id": user_id,
"is_admin": is_admin,
"can_write": writable is not None,
"is_conversation_deposit": _is_conversation_deposit_mapping(row),
"exp": int(time.time()) + _WEKNORA_EMBED_TTL_SECONDS,
}
ctx = WeKnoraEmbedContext(
mapping_id=mapping_id,
weknora_id=weknora_id,
user_id=user_id,
is_admin=is_admin,
can_write=writable is not None,
is_conversation_deposit=_is_conversation_deposit_mapping(row),
allowed_weknora_ids=tuple(dict.fromkeys(value for value in (weknora_id, *(str(item.get("weknora_id") or "") for item in visible_rows)) if value)),
exp=int(time.time()) + _WEKNORA_EMBED_TTL_SECONDS,
)
return weknora_id, _embed_context_payload(ctx)
@router.post("/api/llmwiki/knowledge-bases/{mapping_id}/weknora/session")
@@ -1932,8 +2033,21 @@ async def open_weknora_detail_frame(
async def proxy_weknora_platform_page(request: Request, proxied_path: str = "") -> Response:
ctx = await _read_embed_context(request)
requested = f"/platform/{proxied_path}".rstrip("/")
allowed_path = f"/platform/knowledge-bases/{ctx.weknora_id}"
allowed_path = f"/platform/knowledge-bases/{quote(ctx.weknora_id, safe='')}"
if requested != allowed_path:
requested_weknora_id = _weknora_id_from_platform_path(requested)
if requested_weknora_id is not None:
selected_ctx = await _switch_embed_context(request, ctx, requested_weknora_id)
response = await _proxy_weknora_request(
request,
target_base_url=_runtime_for_iframe_proxy(request).web_base_url,
upstream_path=f"/platform/knowledge-bases/{quote(requested_weknora_id, safe='')}",
ctx=selected_ctx,
is_api=False,
tab=request.query_params.get("tab") or "wiki",
)
_set_weknora_embed_cookie(request, response, _embed_context_payload(selected_ctx))
return response
static_upstream_path = _weknora_static_fallback_upstream_path(request)
if static_upstream_path is not None:
runtime = _runtime_for_iframe_proxy(request)
@@ -2151,11 +2265,7 @@ async def list_knowledge_bases(
except WeKnoraError as exc:
_raise_upstream(exc)
deposit_remote = next(
(
item
for item in remote_items
if str(item.get("name") or "").strip() == CONVERSATION_DEPOSIT_KB_NAME
),
(item for item in remote_items if str(item.get("name") or "").strip() == CONVERSATION_DEPOSIT_KB_NAME),
None,
)
if deposit_remote is not None:
@@ -2165,11 +2275,7 @@ async def list_knowledge_bases(
client,
remote_knowledge_bases=remote_items,
)
description_was_synchronized = (
previous_mapping is None
or not _is_conversation_deposit_mapping(previous_mapping)
or str(previous_mapping.get("description") or "") != CONVERSATION_DEPOSIT_KB_DESCRIPTION
)
description_was_synchronized = previous_mapping is None or not _is_conversation_deposit_mapping(previous_mapping) or str(previous_mapping.get("description") or "") != CONVERSATION_DEPOSIT_KB_DESCRIPTION
if deposit_mapping is not None and description_was_synchronized:
remote_id = str(deposit_mapping["weknora_id"])
remote[remote_id] = {
@@ -2409,13 +2515,7 @@ async def list_wiki_pages(
query=query.strip(),
)
raw_pages = result.get("pages") if isinstance(result, dict) else []
pages = [
view
for page_item in (raw_pages if isinstance(raw_pages, list) else [])
if isinstance(page_item, dict)
for view in [_wiki_page_view(page_item)]
if view is not None
]
pages = [view for page_item in (raw_pages if isinstance(raw_pages, list) else []) if isinstance(page_item, dict) for view in [_wiki_page_view(page_item)] if view is not None]
return {**result, "pages": pages}
except WeKnoraError as exc:
_raise_upstream(exc)
@@ -2557,11 +2657,7 @@ async def search_llmwiki(request: Request, body: SearchRequest) -> dict[str, Any
mapping = local_by_remote.get(str(result.get("knowledge_base_id") or ""))
if mapping is None:
continue
visible_result = (
_sanitize_conversation_deposit_value(result)
if _is_conversation_deposit_mapping(mapping)
else result
)
visible_result = _sanitize_conversation_deposit_value(result) if _is_conversation_deposit_mapping(mapping) else result
params = urlencode({"knowledge_base_id": mapping["id"], "chunk_id": visible_result.get("chunk_id") or ""})
visible.append(
{
@@ -2665,28 +2761,13 @@ async def get_source_context(
if sanitize_deposit and wiki_page is not None:
wiki_page = _sanitize_conversation_deposit_value(wiki_page)
focus_chunk = next((chunk for chunk in chunks if str(chunk.get("id") or "") == chunk_id), {})
document_id = str(
focus_chunk.get("knowledge_id")
or focus_chunk.get("document_id")
or focus_chunk.get("knowledgeId")
or ""
)
document_title = str(
focus_chunk.get("knowledge_title")
or focus_chunk.get("title")
or focus_chunk.get("file_name")
or focus_chunk.get("filename")
or ""
)
document_id = str(focus_chunk.get("knowledge_id") or focus_chunk.get("document_id") or focus_chunk.get("knowledgeId") or "")
document_title = str(focus_chunk.get("knowledge_title") or focus_chunk.get("title") or focus_chunk.get("file_name") or focus_chunk.get("filename") or "")
normalized_chunks = [
{
"id": str(chunk.get("id") or ""),
"chunk_index": int(chunk.get("chunk_index") or 0),
"content": str(
_sanitize_conversation_deposit_value(chunk.get("content") or "")
if sanitize_deposit
else chunk.get("content") or ""
),
"content": str(_sanitize_conversation_deposit_value(chunk.get("content") or "") if sanitize_deposit else chunk.get("content") or ""),
"is_focus": str(chunk.get("id") or "") == chunk_id,
}
for chunk in chunks
@@ -71,6 +71,9 @@ class ChainSeatSchema(BaseModel):
# 岗位协同专用的席位岗位归属。字段保存在既有 seats JSON 中,普通圆桌编排
# 忽略它;显式声明可确保 Pydantic 在 create/update 的 model_dump() 时不剥掉。
position_id: str | None = Field(default=None, max_length=64)
# 该席位在业务链中的岗位职责。会商智能体配置面板只读展示此字段;
# 保存在既有 seats JSON 中,无需迁移。空/None = 未填写。
job_responsibilities: str | None = Field(default=None, max_length=4000)
class ChainResponse(BaseModel):
@@ -76,6 +76,7 @@ class WeKnoraEmbedContext:
can_write: bool
exp: int
is_conversation_deposit: bool = False
allowed_weknora_ids: tuple[str, ...] = ()
def is_weknora_embed_proxy_path(path: str) -> bool:
@@ -109,9 +110,7 @@ def verify_weknora_embed_cookie(raw: str | None) -> WeKnoraEmbedContext:
if not raw or "." not in raw:
raise HTTPException(status_code=401, detail="WeKnora iframe session is missing")
body, sig = raw.rsplit(".", 1)
expected = _b64url_encode(
hmac.new(WEKNORA_PROXY_SECRET.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest()
)
expected = _b64url_encode(hmac.new(WEKNORA_PROXY_SECRET.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest())
if not hmac.compare_digest(sig, expected):
raise HTTPException(status_code=401, detail="WeKnora iframe session is invalid")
try:
@@ -120,6 +119,8 @@ def verify_weknora_embed_cookie(raw: str | None) -> WeKnoraEmbedContext:
raise HTTPException(status_code=401, detail="WeKnora iframe session is invalid") from None
if int(payload.get("exp") or 0) < int(time.time()):
raise HTTPException(status_code=401, detail="WeKnora iframe session has expired")
raw_allowed_ids = payload.get("allowed_weknora_ids")
allowed_weknora_ids = tuple(dict.fromkeys(str(item).strip() for item in raw_allowed_ids if isinstance(item, (str, int)) and str(item).strip())) if isinstance(raw_allowed_ids, list) else ()
return WeKnoraEmbedContext(
mapping_id=str(payload.get("mapping_id") or ""),
weknora_id=str(payload.get("weknora_id") or ""),
@@ -128,6 +129,7 @@ def verify_weknora_embed_cookie(raw: str | None) -> WeKnoraEmbedContext:
can_write=bool(payload.get("can_write")),
exp=int(payload.get("exp") or 0),
is_conversation_deposit=bool(payload.get("is_conversation_deposit")),
allowed_weknora_ids=allowed_weknora_ids,
)