Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(parse): add-feishu-mindnote (#4319)
Syt3s3e086ba641c6
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex 9b6434062..406abaeff 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -49,7 +49,7 @@ Audio/video parsers validate and store the original files. Content understanding| Type | Description ||------|-------------|-| Feishu/Lark | URL-based, supports doc/docx, wiki, sheets, bitable. By default uses app credentials from FEISHU_APP_ID and FEISHU_APP_SECRET; user-token imports can pass `args.feishu_access_token`, and user-token watches also pass `args.feishu_refresh_token` plus an optional `args.feishu_app_id` / `args.feishu_app_secret` pair |+| Feishu/Lark | URL-based, supports doc/docx, wiki, sheets, bitable, and mindnote/mindnotes. By default uses app credentials from FEISHU_APP_ID and FEISHU_APP_SECRET; user-token imports can pass `args.feishu_access_token`, and user-token watches also pass `args.feishu_refresh_token` plus an optional `args.feishu_app_id` / `args.feishu_app_secret` pair. Mindnote and wiki-wrapped Mindnote require `mindnote:node:read` on the token used for import |**Web Pages (recursive web crawler)**@@ -211,6 +211,8 @@ This endpoint is the core entry point for resource management. It supports vario- When `watch_interval > 0`, the watch task binds to `to` if provided; otherwise it binds to the `root_uri` returned by this import. If no stable `root_uri` is available, the request fails and asks for an explicit `to`.- For Connector imports, `is_active=false` creates the paused Watch before submission. Native Feishu and Git imports carry `is_active` through the resource queue and create the Watch after resolving the imported resource URI. In both cases, the initial import still runs once and periodic scheduling remains disabled.- Feishu/Lark app-token imports do not pass `args.feishu_access_token`. OpenViking keeps the existing app credential flow and the SDK obtains an app/tenant token from `app_id` and `app_secret`. This mode supports both one-time imports and `watch_interval > 0`.+- Feishu/Lark Mindnote URLs may use `/mindnote/{token}` or `/mindnotes/{token}`. Wiki URLs that resolve to `obj_type=mindnote` use the same reader. Mindnote uses the same authentication selection as other Feishu imports: `args.feishu_access_token` selects a user token, otherwise OpenViking falls back to the configured app/tenant token. The selected token must have `mindnote:node:read`.+- Mindnote node images use Feishu's Drive media API and the same token type as the Mindnote import. User-token imports forward the user token to media download; app-token imports use the configured app credentials. The selected token must allow `docs:document.media:download`. If media download is unavailable, the text import still succeeds and keeps the original image reference.- Feishu/Lark one-time user-token imports pass `args={"feishu_access_token": "u-..."}` with `watch_interval <= 0`. OpenViking uses that user token only for the current import and does not store it.- Feishu/Lark user-token watches pass `args={"feishu_access_token": "u-...", "feishu_refresh_token": "r-..."}` with `watch_interval > 0`. They may also pass `feishu_app_id` and `feishu_app_secret` together; OpenViking stores the pair in the private watch task state and uses it to refresh that watch's user token.- If the request omits the app pair, user-token watches use `FEISHU_APP_ID` and `FEISHU_APP_SECRET`, or `feishu.app_id` and `feishu.app_secret` in `ov.conf`. Feishu refresh tokens are bound to their issuing app, so whichever app credentials are used must match the supplied user token.@@ -318,6 +320,17 @@ curl -X POST http://localhost:1933/api/v1/resources \}}'+# Add a Feishu Mindnote (a wiki URL backed by Mindnote is also supported)+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "https://example.feishu.cn/mindnote/mindnote_token",+ "args": {+ "feishu_access_token": "u-..."+ }+ }'+# Add a Feishu document with scheduled user-token refreshcurl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \@@ -412,6 +425,12 @@ client.add_resource(options={"args": {"feishu_access_token": "u-..."}},)+# Add a Feishu Mindnote with an explicit user token+client.add_resource(+ path="https://example.feishu.cn/mindnote/mindnote_token",+ options={"args": {"feishu_access_token": "u-..."}},+)+# Add a Feishu document with scheduled user-token refreshclient.add_resource(path="https://example.feishu.cn/docx/doc_token",diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 5c48c4809..73c45f446 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -44,7 +44,7 @@ OpenViking 支持多种资源类型,按照功能分类如下:云文档类| 类型 | 说明 ||------|------|-| 飞书/Lark | URL 方式,支持 doc/docx, wiki, sheets, bitable、Drive 文件和目录集。Wiki 默认仅导入入口文档,设置 `args.feishu_recursive=true` 可递归导入子节点。默认使用 FEISHU_APP_ID 和 FEISHU_APP_SECRET 应用凭证;用户 token 导入可传 `args.feishu_access_token`,用户 token watch 还需传 `args.feishu_refresh_token`,并可选传入 `args.feishu_app_id` / `args.feishu_app_secret` |+| 飞书/Lark | URL 方式,支持 doc/docx、wiki、sheets、bitable、mindnote/mindnotes、Drive 文件和目录集。Wiki 默认仅导入入口文档,设置 `args.feishu_recursive=true` 可递归导入子节点。默认使用 FEISHU_APP_ID 和 FEISHU_APP_SECRET 应用凭证;用户 token 导入可传 `args.feishu_access_token`,用户 token watch 还需传 `args.feishu_refresh_token`,并可选传入 `args.feishu_app_id` / `args.feishu_app_secret`。Mindnote 及 Wiki 中的 Mindnote 要求本次使用的 token 具备 `mindnote:node:read` |网页类(递归网页爬虫)| 类型 | 资源名 | 说明 |@@ -206,6 +206,8 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector- `watch_interval > 0` 时,如果指定了 `to`,监控任务绑定该目标;如果未指定 `to`,监控任务绑定本次导入返回的 `root_uri`。如果无法得到稳定 `root_uri`,请求会报错并要求显式传 `to`。- Connector 导入设置 `is_active=false` 时会在提交前创建暂停状态的 Watch;原生飞书和 Git 导入会通过资源队列透传 `is_active`,解析出最终资源 URI 后再创建 Watch。两种情况下首次导入均执行一次,周期调度保持关闭。- 飞书/Lark 应用 token 导入不传 `args.feishu_access_token`。OpenViking 保持原有应用凭证流程,由 SDK 使用 `app_id` 和 `app_secret` 自动获取 app/tenant token。该模式支持一次性导入和 `watch_interval > 0`。+- 飞书/Lark Mindnote URL 支持 `/mindnote/{token}` 和 `/mindnotes/{token}`;Wiki URL 若解析为 `obj_type=mindnote` 也走同一读取流程。Mindnote 使用与其他飞书导入一致的认证选择:传入 `args.feishu_access_token` 时使用用户 token,否则回退到配置的 app/tenant token。本次使用的 token 需具备 `mindnote:node:read`。+- Mindnote 节点图片通过飞书 Drive 素材接口下载,并沿用本次 Mindnote 导入的 token 类型。用户 token 导入会向媒体下载透传用户 token;app-token 导入使用配置的应用凭证。本次使用的 token 需具备 `docs:document.media:download`。媒体下载不可用时,正文仍会成功导入并保留原始图片引用。- 飞书/Lark 一次性用户 token 导入通过 `args={"feishu_access_token": "u-..."}` 传入,且 `watch_interval <= 0`。OpenViking 只在本次导入使用该用户 token,不保存。- 飞书/Lark 用户 token watch 通过 `args={"feishu_access_token": "u-...", "feishu_refresh_token": "r-..."}` 传入,且 `watch_interval > 0`。还可同时传入 `feishu_app_id` 和 `feishu_app_secret`;OpenViking 会将其保存在 watch task 私有状态中,并用于刷新该 watch 的用户 token。- 请求未传应用凭证时,用户 token watch 回退使用 `FEISHU_APP_ID` 和 `FEISHU_APP_SECRET`,或 `ov.conf` 中的 `feishu.app_id` 和 `feishu.app_secret`。飞书 refresh token 绑定签发它的应用,因此实际使用的应用凭证必须与传入的用户 token 匹配。@@ -323,6 +325,17 @@ curl -X POST http://localhost:1933/api/v1/resources \}}'+# 添加飞书 Mindnote(也可传底层类型为 Mindnote 的 Wiki URL)+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "https://example.feishu.cn/mindnote/mindnote_token",+ "args": {+ "feishu_access_token": "u-..."+ }+ }'+# 使用用户 token 自动刷新添加飞书文档curl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \@@ -417,6 +430,12 @@ client.add_resource(options={"args": {"feishu_access_token": "u-..."}},)+# 使用显式用户 token 添加飞书 Mindnote+client.add_resource(+ path="https://example.feishu.cn/mindnote/mindnote_token",+ options={"args": {"feishu_access_token": "u-..."}},+)+# 使用用户 token 自动刷新添加飞书文档client.add_resource(path="https://example.feishu.cn/docx/doc_token",diff --git a/openviking/parse/accessors/feishu_accessor.py b/openviking/parse/accessors/feishu_accessor.pyindex 98df926f7..5d4837acb 100644--- a/openviking/parse/accessors/feishu_accessor.py+++ b/openviking/parse/accessors/feishu_accessor.py@@ -11,6 +11,7 @@ Included by default in `openviking[bot]` installation.import asyncioimport copy+import htmlimport jsonimport mimetypesimport re@@ -39,6 +40,7 @@ _FEISHU_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(feishu://image/([^)]+)\)")_FEISHU_DOCUMENT_FORBIDDEN = 1770032_FEISHU_WIKI_NODE_PERMISSION_DENIED = 131006_FEISHU_BITABLE_PERMISSION_REQUIRED = 99991672+_FEISHU_SCOPE_PERMISSION_REQUIRED = 99991679_FEISHU_LEGACY_DOC_LOGIN_REQUIRED = 91404_FEISHU_PERMISSION_DENIED_CODES = {_FEISHU_DOCUMENT_FORBIDDEN,@@ -47,9 +49,18 @@ _FEISHU_PERMISSION_DENIED_CODES = {95008,95009,}-_FEISHU_NOT_FOUND_CODES = {91402, 95006, 95007}+_FEISHU_NOT_FOUND_CODES = {91402, 95006, 95007, 3410003}_MAX_MEDIA_DOWNLOAD_CONTEXTS = 8-_FEISHU_DOC_PATH_TYPES = {"doc", "docs", "docx", "wiki", "sheets", "base"}+_FEISHU_DOC_PATH_TYPES = {+ "doc",+ "docs",+ "docx",+ "wiki",+ "sheets",+ "base",+ "mindnote",+ "mindnotes",+}_FEISHU_DRIVE_DOC_TYPES = {"doc": "docs","docx": "docx",@@ -58,6 +69,7 @@ _FEISHU_DRIVE_DOC_TYPES = {"bitable": "base","base": "base","wiki": "wiki",+ "mindnote": "mindnote",}_MAX_PATH_SEGMENT_CHARS = 120_MAX_PATH_SEGMENT_BYTES = 240@@ -65,6 +77,15 @@ _MAX_PATH_SEGMENT_BYTES = 240_MediaDownloadExtras = Dict[str, List[Optional[str]]]+def _redact_feishu_source_url(url: str) -> str:+ """Keep a useful Feishu route in logs without exposing document tokens."""+ parsed = urlparse(str(url))+ path_parts = [part for part in parsed.path.split("/") if part]+ route_parts = path_parts[:2] if path_parts[:2] == ["drive", "folder"] else path_parts[:1]+ route = "/".join(route_parts)+ return f"{parsed.scheme}://{parsed.netloc}/{route}/***" if route else "<feishu-url>"++def _title_as_filename(title: str) -> str:"""Keep a Feishu display title intact while making it one filename segment.@@ -182,6 +203,7 @@ def _raise_from_lark_response(*,operation: str,resource: str | None = None,+ required_scope: str | None = None,) -> NoReturn:code = getattr(response, "code", None)msg = getattr(response, "msg", None) or "Feishu API request failed"@@ -207,6 +229,12 @@ def _raise_from_lark_response(message = (f"Feishu application is missing required Bitable permissions: code={code}, msg={msg}")+ elif code == _FEISHU_SCOPE_PERMISSION_REQUIRED and required_scope:+ public_code = "FAILED_PRECONDITION"+ message = (+ "Feishu user authorization is missing required permission "+ f"{required_scope}: code={code}, msg={msg}"+ )else:if code in _FEISHU_PERMISSION_DENIED_CODES:public_code = "PERMISSION_DENIED"@@ -264,6 +292,7 @@ class FeishuAccessor(DataAccessor):- Wiki pages: https://*.feishu.cn/wiki/{token}- Spreadsheets: https://*.feishu.cn/sheets/{token}- Bitable: https://*.feishu.cn/base/{app_token}+ - Mindnotes: https://*.feishu.cn/mindnote/{mindnote_id}- Drive files: https://*.feishu.cn/file/{file_token}- Drive folders: https://*.feishu.cn/drive/folder/{folder_token}@@ -283,6 +312,7 @@ class FeishuAccessor(DataAccessor):"docx": "_parse_docx","sheets": "_parse_sheets","base": "_parse_bitable",+ "mindnote": "_parse_mindnote",}# Attributes that skip processing (structural containers or metadata)@@ -620,7 +650,12 @@ class FeishuAccessor(DataAccessor):)except Exception as e:- logger.error(f"[FeishuAccessor] Failed to access {source}: {e}", exc_info=True)+ logger.error(+ "[FeishuAccessor] Failed to access %s: %s",+ _redact_feishu_source_url(source_str),+ e,+ exc_info=True,+ )raiseasync def preflight_source(@@ -759,6 +794,13 @@ class FeishuAccessor(DataAccessor):feishu_access_token=feishu_access_token,)return f"Bitable ({len(tables)} tables)"+ if doc_type == "mindnote":+ nodes = self._fetch_mindnote_nodes(+ token,+ feishu_access_token=feishu_access_token,+ )+ title = self._mindnote_title(nodes)+ return _title_as_filename(title)if doc_type == "file":return Noneraise ValueError(@@ -892,7 +934,12 @@ class FeishuAccessor(DataAccessor):return "folder", path_parts[2]if path_parts[0] == "file":return "file", path_parts[1]- doc_type = "doc" if path_parts[0] in {"doc", "docs"} else path_parts[0]+ if path_parts[0] in {"doc", "docs"}:+ doc_type = "doc"+ elif path_parts[0] in {"mindnote", "mindnotes"}:+ doc_type = "mindnote"+ else:+ doc_type = path_parts[0]token = path_parts[1]return doc_type, token@@ -1737,6 +1784,296 @@ class FeishuAccessor(DataAccessor):return doc_type, obj_token, title+ # ========== Mindnote Parsing ==========++ @staticmethod+ def _redact_feishu_identifier(value: str) -> str:+ value = str(value or "")+ if len(value) <= 8:+ return "***"+ return f"{value[:4]}...{value[-4:]}"++ def _fetch_mindnote_nodes(+ self,+ mindnote_id: str,+ *,+ feishu_access_token: Optional[str] = None,+ ) -> List[Dict[str, Any]]:+ """Fetch a complete Mindnote node list."""+ import lark_oapi as lark++ access_token = str(feishu_access_token or "").strip() or None+ client = self._get_client(use_user_token=bool(access_token))+ token_type = lark.AccessTokenType.USER if access_token else lark.AccessTokenType.TENANT+ request = (+ lark.BaseRequest.builder()+ .http_method(lark.HttpMethod.GET)+ .uri(f"/open-apis/mindnote/v1/mindnotes/{mindnote_id}/nodes")+ .token_types({token_type})+ .build()+ )+ response = self._call_api(client.request, request, access_token)+ if not response.success():+ _raise_from_lark_response(+ response,+ operation="fetch Mindnote nodes",+ resource=self._redact_feishu_identifier(mindnote_id),+ required_scope="mindnote:node:read",+ )++ data = self._raw_response_data(response)+ nodes = _getattr_safe(data, "nodes", None)+ if not isinstance(nodes, list):+ raise OpenVikingError(+ "Feishu Mindnote nodes response is missing a valid data.nodes array",+ code="UNAVAILABLE",+ details={+ "operation": "fetch Mindnote nodes",+ "resource": self._redact_feishu_identifier(mindnote_id),+ },+ )+ if any(not isinstance(node, dict) for node in nodes):+ raise OpenVikingError(+ "Feishu Mindnote nodes response contains an invalid node object",+ code="UNAVAILABLE",+ details={+ "operation": "fetch Mindnote nodes",+ "resource": self._redact_feishu_identifier(mindnote_id),+ },+ )+ invalid_fields = {+ field_name+ for node in nodes+ for field_name in ("texts", "notes", "images")+ if node.get(field_name) is not None and not isinstance(node.get(field_name), list)+ }+ if invalid_fields:+ raise OpenVikingError(+ "Feishu Mindnote nodes response contains an invalid list field",+ code="UNAVAILABLE",+ details={+ "operation": "fetch Mindnote nodes",+ "resource": self._redact_feishu_identifier(mindnote_id),+ "invalid_fields": sorted(invalid_fields),+ },+ )+ return nodes++ @classmethod+ def _mindnote_value_text(cls, value: Any) -> str:+ if isinstance(value, str):+ return value+ if not isinstance(value, dict):+ return ""+ for key in ("content", "name", "title"):+ nested = value.get(key)+ if isinstance(nested, str) and nested:+ return nested+ if isinstance(nested, dict):+ content = cls._mindnote_value_text(nested)+ if content:+ return content+ return ""++ @staticmethod+ def _escape_mindnote_text(text: str) -> str:+ escaped = html.escape(str(text), quote=False).replace("\\", "\\\\")+ escaped = re.sub(r"([`*_[\]~])", r"\\\1", escaped)+ return escaped.replace("\r\n", "<br>").replace("\r", "<br>").replace("\n", "<br>")++ @staticmethod+ def _mindnote_inline_code(text: str) -> str:+ text = str(text).replace("\r\n", " ").replace("\r", " ").replace("\n", " ")+ longest_run = max((len(run) for run in re.findall(r"`+", text)), default=0)+ delimiter = "`" * (longest_run + 1)+ padding = " " if text.startswith(("`", " ")) or text.endswith(("`", " ")) else ""+ return f"{delimiter}{padding}{text}{padding}{delimiter}"++ @staticmethod+ def _mindnote_link(label: str, url: str) -> str:+ safe_url = str(url).replace("\\", "\\\\").replace(">", "\\>")+ return f"[{label}](<{safe_url}>)"++ @classmethod+ def _mindnote_element_payload(cls, element: Dict[str, Any], element_type: str) -> Any:+ payload_key = {"user": "mention_user", "doc": "mention_doc"}.get(+ element_type, element_type+ )+ return element.get(payload_key) if element.get(payload_key) is not None else element++ @staticmethod+ def _mindnote_element_type(element: Dict[str, Any]) -> str:+ return str(element.get("element_type") or "text").lower()++ @classmethod+ def _mindnote_user_label(cls, payload: Any) -> str:+ label = cls._mindnote_value_text(payload)+ if label:+ return label+ if isinstance(payload, dict):+ user_id = payload.get("user_id") or payload.get("open_id") or payload.get("id")+ return cls._redact_feishu_identifier(str(user_id or ""))+ return "***"++ @classmethod+ def _mindnote_title(cls, nodes: List[Dict[str, Any]]) -> str:+ roots = [node for node in nodes if not node.get("parent_id")]+ children = [node for node in nodes if node.get("parent_id")]+ for node in roots + children:+ parts: List[str] = []+ for element in node.get("texts") or []:+ if not isinstance(element, dict):+ if element is not None:+ parts.append(str(element))+ continue++ element_type = cls._mindnote_element_type(element)+ payload = cls._mindnote_element_payload(element, element_type)+ if element_type == "user":+ parts.append(f"@{cls._mindnote_user_label(payload)}")+ continue++ parts.append(cls._mindnote_value_text(payload) or cls._mindnote_value_text(element))++ title = " ".join("".join(parts).split())+ if title:+ return title+ return "Mindnote"++ @classmethod+ def _render_mindnote_elements(+ cls,+ elements: List[Any],+ ) -> str:+ rendered: List[str] = []+ for element in elements:+ if not isinstance(element, dict):+ text = cls._escape_mindnote_text(str(element)) if element is not None else ""+ if text:+ rendered.append(text)+ continue++ element_type = cls._mindnote_element_type(element)+ payload = cls._mindnote_element_payload(element, element_type)+ raw_text = cls._mindnote_value_text(payload) or cls._mindnote_value_text(element)+ url = ""+ style: Any = element.get("style")+ if isinstance(payload, dict):+ style = style or payload.get("style")++ if element_type == "user":+ rendered.append(cls._escape_mindnote_text(f"@{cls._mindnote_user_label(payload)}"))+ continue++ if element_type == "link":+ if isinstance(payload, dict):+ url = str(payload.get("url") or payload.get("href") or "")+ elif isinstance(payload, str):+ url = payload+ raw_text = cls._mindnote_value_text(element.get("text")) or payload+ elif element_type == "doc" and isinstance(payload, dict):+ url = str(payload.get("url") or payload.get("href") or "")+ if not raw_text:+ token = str(payload.get("token") or payload.get("obj_token") or "")+ raw_text = cls._redact_feishu_identifier(token) if token else "document"++ text = cls._escape_mindnote_text(raw_text)+ if not text:+ if element_type == "link" and url:+ text = cls._escape_mindnote_text(url)+ else:+ continue++ if isinstance(style, dict):+ if style.get("inline_code") or style.get("code_inline"):+ text = cls._mindnote_inline_code(raw_text)+ if style.get("bold"):+ text = f"**{text}**"+ if style.get("italic"):+ text = f"*{text}*"+ if style.get("strikethrough"):+ text = f"~~{text}~~"+ style_link = style.get("link")+ if not url and isinstance(style_link, dict):+ url = str(style_link.get("url") or style_link.get("href") or "")+ elif not url and isinstance(style_link, str):+ url = style_link+ if url:+ text = cls._mindnote_link(text, url)+ rendered.append(text)+ return "".join(rendered)++ @classmethod+ def _render_mindnote_node(+ cls,+ node: Dict[str, Any],+ depth: int,+ ) -> List[str]:+ indent = " " * depth+ text = cls._render_mindnote_elements(node.get("texts") or [])+ text = text or "*(untitled)*"+ highlight = str(node.get("highlight") or "").strip()+ if highlight:+ color = html.escape(highlight, quote=True)+ text = f'<mark data-color="{color}">{text}</mark>'+ if node.get("finish") is True:+ text = f"✅ {text}"++ lines = [f"{indent}- {text}"]+ note = cls._render_mindnote_elements(node.get("notes") or [])+ if note:+ lines.append(f"{indent} > {note}")+ for image in node.get("images") or []:+ token = str(image.get("token") or "") if isinstance(image, dict) else ""+ if token and re.fullmatch(r"[A-Za-z0-9._-]+", token):+ lines.append(f"{indent} ")+ return lines++ @classmethod+ def _render_mindnote(cls, nodes: List[Dict[str, Any]], title: str) -> str:+ indexed_nodes = list(enumerate(nodes))+ node_ids = {str(node.get("node_id") or "") for node in nodes}+ children: Dict[str, List[Tuple[int, Dict[str, Any]]]] = {}+ roots: List[Tuple[int, Dict[str, Any]]] = []+ for item in indexed_nodes:+ _, node = item+ node_id = str(node.get("node_id") or "")+ parent_id = str(node.get("parent_id") or "")+ if parent_id and parent_id in node_ids and parent_id != node_id:+ children.setdefault(parent_id, []).append(item)+ else:+ roots.append(item)++ visited: set[int] = set()+ lines = [f"# {cls._escape_mindnote_text(title)}", ""]++ def render(starts: List[Tuple[int, Dict[str, Any]]]) -> None:+ stack = [(item, 0) for item in reversed(starts)]+ while stack:+ (index, node), depth = stack.pop()+ if index in visited:+ continue+ visited.add(index)+ lines.extend(cls._render_mindnote_node(node, depth))+ node_id = str(node.get("node_id") or "")+ stack.extend((child, depth + 1) for child in reversed(children.get(node_id, [])))++ render(roots)+ render([item for item in indexed_nodes if item[0] not in visited])+ return "\n".join(lines)++ def _parse_mindnote(+ self,+ mindnote_id: str,+ feishu_access_token: Optional[str] = None,+ ) -> Tuple[str, str]:+ nodes = self._fetch_mindnote_nodes(+ mindnote_id,+ feishu_access_token=feishu_access_token,+ )+ title = self._mindnote_title(nodes)+ return self._render_mindnote(nodes, title), title+def _resolve_wiki_tree_root(self,url: str,diff --git a/tests/parse/test_feishu_accessor.py b/tests/parse/test_feishu_accessor.pyindex ab9f05606..891eed68d 100644--- a/tests/parse/test_feishu_accessor.py+++ b/tests/parse/test_feishu_accessor.py@@ -1129,6 +1129,168 @@ def test_access_writes_downloaded_images_next_to_markdown(monkeypatch):assert not resource.path.parent.exists()[email protected]("path_type", ["mindnote", "mindnotes"])+def test_mindnote_url_is_supported(path_type):+ accessor = FeishuAccessor()+ url = f"https://example.feishu.cn/{path_type}/mindnote_token"++ assert accessor.can_handle(url)+ assert accessor._parse_feishu_url(url) == ("mindnote", "mindnote_token")+++def _mindnote_node(node_id, text, parent_id=None, **extra):+ node = {+ "node_id": node_id,+ "texts": [{"text": {"content": text}}],+ **extra,+ }+ if parent_id is not None:+ node["parent_id"] = parent_id+ return node+++ ("nodes", "expected"),+ [+ (+ [+ _mindnote_node("root", "Root"),+ _mindnote_node("child", "Child", parent_id="root"),+ _mindnote_node("orphan", "Orphan", parent_id="missing"),+ ],+ "# Title\n\n- Root\n - Child\n- Orphan",+ ),+ (+ [+ _mindnote_node("self", "Self", parent_id="self"),+ _mindnote_node("child", "Child", parent_id="self"),+ ],+ "# Title\n\n- Self\n - Child",+ ),+ (+ [+ _mindnote_node("a", "A", parent_id="b"),+ _mindnote_node("b", "B", parent_id="a"),+ ],+ "# Title\n\n- A\n - B",+ ),+ (+ [+ _mindnote_node("dup", "First"),+ _mindnote_node("dup", "Second"),+ _mindnote_node("child", "Child", parent_id="dup"),+ ],+ "# Title\n\n- First\n - Child\n- Second",+ ),+ ],+)+def test_render_mindnote_handles_noncanonical_tree_shapes(nodes, expected):+ assert FeishuAccessor._render_mindnote(nodes, "Title") == expected+++def test_mindnote_preflight_uses_tenant_token_without_user_token(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ nodes = {+ "data": {+ "nodes": [+ _mindnote_node("root", "Tenant Mindnote")+ ]+ }+ }+ request = MagicMock(return_value=_FakeMediaResponse(json.dumps(nodes).encode()))+ accessor = FeishuAccessor()+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request))++ identity = asyncio.run(+ accessor.preflight_source("https://example.feishu.cn/mindnote/mindnote_token")+ )++ assert identity.source_name == "Tenant Mindnote"+ node_request = request.call_args.args[0]+ assert node_request.uri == "/open-apis/mindnote/v1/mindnotes/mindnote_token/nodes"+ assert node_request.token_types == {"tenant"}+ assert len(request.call_args.args) == 1+++def test_access_mindnote_preserves_user_token_for_media(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ nodes = {+ "data": {+ "nodes": [+ _mindnote_node("root", "Launch Plan"),+ {+ "node_id": "child",+ "parent_id": "root",+ "texts": [+ {+ "element_type": "link",+ "link": {"content": "Spec", "url": "https://example.com/spec"},+ }+ ],+ "highlight": "yellow",+ "images": [{"token": "image_token"}],+ },+ ]+ }+ }+ request = MagicMock(+ side_effect=[+ _FakeMediaResponse(json.dumps(nodes).encode()),+ _FakeMediaResponse(b"\x89PNG\r\n\x1a\nimage"),+ ]+ )+ accessor = FeishuAccessor()+ accessor._config = SimpleNamespace(download_images=True)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request))++ resource = asyncio.run(+ accessor.access(+ "https://example.feishu.cn/mindnote/mindnote_token",+ feishu_access_token="u-test",+ )+ )++ try:+ assert resource.path.read_text(encoding="utf-8") == (+ "# Launch Plan\n\n"+ "- Launch Plan\n"+ ' - <mark data-color="yellow">[Spec](<https://example.com/spec>)</mark>\n'+ " "+ )+ assert (resource.path.parent / "images" / "image_token.png").read_bytes() == (+ b"\x89PNG\r\n\x1a\nimage"+ )+ node_request, media_request = [call.args[0] for call in request.call_args_list]+ assert node_request.uri == "/open-apis/mindnote/v1/mindnotes/mindnote_token/nodes"+ assert media_request.uri == "/open-apis/drive/v1/medias/image_token/download"+ assert node_request.token_types == media_request.token_types == {"user"}+ assert all(call.args[1].user_access_token == "u-test" for call in request.call_args_list)+ finally:+ resource.cleanup()+++def test_wiki_mindnote_uses_resolved_object_token(monkeypatch):+ accessor = FeishuAccessor()+ monkeypatch.setattr(+ accessor,+ "_resolve_wiki_node",+ MagicMock(return_value=("mindnote", "mindnote_token", "Wiki Mindnote")),+ )+ parse = MagicMock(return_value=("# Mindnote\n\n- Root", "Root"))+ monkeypatch.setattr(accessor, "_parse_mindnote", parse)++ document = asyncio.run(+ accessor._fetch_document(+ "https://example.feishu.cn/wiki/wiki_token",+ feishu_access_token="u-test",+ )+ )++ parse.assert_called_once_with("mindnote_token", "u-test")+ assert document.doc_type == "mindnote"+ assert document.title == "Wiki Mindnote"++def test_fetch_document_dispatches_all_supported_types(monkeypatch):_install_fake_lark_modules(monkeypatch)accessor = FeishuAccessor()@@ -1136,6 +1298,7 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):"_parse_docx": MagicMock(return_value=("docx body", "Doc")),"_parse_sheets": MagicMock(return_value=("sheet body", "Sheet")),"_parse_bitable": MagicMock(return_value=("base body", "Base")),+ "_parse_mindnote": MagicMock(return_value=("mindnote body", "Mindnote")),}for name, handler in handlers.items():monkeypatch.setattr(accessor, name, handler)@@ -1191,6 +1354,12 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):)sheets = asyncio.run(accessor._fetch_document("https://example.feishu.cn/sheets/sht_token"))base = asyncio.run(accessor._fetch_document("https://example.feishu.cn/base/app_token"))+ mindnote = asyncio.run(+ accessor._fetch_document(+ "https://example.feishu.cn/mindnote/mindnote_token",+ feishu_access_token="u-test",+ )+ )monkeypatch.setattr(accessor,"_resolve_wiki_node",@@ -1203,12 +1372,14 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):docx.doc_type,sheets.doc_type,base.doc_type,+ mindnote.doc_type,wiki.doc_type,) == ("doc","docx","sheets","base",+ "mindnote","base",)assert legacy_doc.title == "Legacy Doc"@@ -1219,6 +1390,7 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):assert handlers["_parse_sheets"].call_args.kwargs["media_download_extras"] is (sheets.media_download_extras)+ handlers["_parse_mindnote"].assert_called_once_with("mindnote_token", "u-test")assert handlers["_parse_bitable"].call_args_list[-1].args == ("wiki_app_token", None)monkeypatch.setattr(accessor, "_probe_docx_document", MagicMock())