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: consume account-scoped Feishu config (#5237)
runyunzhoueb2acdb8b632
diff --git a/docs/design/runtime-configuration-design.md b/docs/design/runtime-configuration-design.mdindex 8dd34e324..1dd874649 100644--- a/docs/design/runtime-configuration-design.md+++ b/docs/design/runtime-configuration-design.md@@ -31,11 +31,11 @@ Current runtime field declarations:| Scope | Field | Lifecycle | Fallback / consumer status || --- | --- | --- | --- || Cluster | `agent_evolution` | Dynamic | Cluster default; consumed by session and Agent Evolution paths |-| Account | `vlm`, `memory`, `feishu`, `agent_evolution` | Dynamic | All four declare Cluster fallback; Agent Evolution is consumed through the manager, while the complete VLM, memory, and Feishu consumer paths are not yet wired |+| Account | `agent_evolution` | Dynamic | Declares whole-section fallback to Cluster `agent_evolution`; consumed through the manager |+| Account | `feishu` | Dynamic | No declarative fallback; an unset section uses Cluster `feishu`, while a set section uses Account values/defaults for every field except the Cluster-owned `domain`. Used by Feishu imports, preflight, and watch token refresh || Account | `github`, `acl` | Dynamic | No Cluster fallback; GitHub and ACL consumers read the Account value through the manager |-| Account | `embedding`, `vectordb` | Create-only | Fallback to Cluster `embedding` and `storage.vectordb`; both fields must be set together when explicitly configured |-`query_planner`, Cluster `embedding`, Cluster `vlm`, Cluster `memory`, and the other plain configuration sections are not currently writable through the runtime configuration API.+Account `vlm`, `memory`, `embedding`, and `vectordb` are not declared on the current Account runtime model and are rejected by both creation-time settings validation and later PATCH requests. `query_planner`, Cluster `embedding`, Cluster `vlm`, Cluster `memory`, Cluster `feishu`, and the other plain Cluster configuration sections are not writable through the runtime configuration API.## 3. RuntimeConfigManager@@ -80,9 +80,9 @@ Validation has two stages:1. Structural validation checks that every path is on the target model's `RuntimeField` surface, rejects unknown paths, and rejects `dynamic=False` paths on a non-creating PATCH.2. The merged result is constructed into the target Pydantic model for type validation and cross-field constraints.-A `dynamic=False` field can be supplied while an Account is created, but any later PATCH touching that field is rejected. `embedding` and `vectordb` are validated as a pair, including their dimensions.+A `dynamic=False` field can be supplied while an Account is created, but any later PATCH touching that field is rejected. The current Account model does not declare any create-only fields.-The API returns the explicit override at the addressed scope. It does not return inherited or effective values. Fallback is a whole-section operation: if an Account supplies `vlm`, omitted properties use the VLM model defaults rather than being merged property-by-property from the Cluster VLM.+The API returns the explicit override at the addressed scope. It does not return inherited or effective values. Declarative fallback is a whole-section operation, currently used by Account `agent_evolution`. Feishu intentionally uses a domain-specific resolver instead: an absent Account Feishu section returns the complete Cluster section; once the Account section exists, only `domain` is copied from Cluster and omitted or reset Account leaves use `FeishuConfig` defaults.## 5. Publication and consumers@@ -99,7 +99,7 @@ Consumer exceptions are logged and swallowed. They do not roll back persistenceCluster publication uses atomic pointer replacement. The new object is built and validated before the singleton is swapped, so concurrent readers see either the old or new object. Account consumers are notified of eviction independently of section filters so they can drop account-local derived state.-The current implementation only wires a subset of declared fields into business consumers. Account GitHub, ACL, and Agent Evolution reads use the manager. Account `vlm`, `memory`, `feishu`, `embedding`, and `vectordb` can be validated and persisted, but their complete business read paths remain follow-up work.+All currently declared Account sections have business consumers: GitHub, ACL, and Agent Evolution read through the manager, while Feishu is resolved for resource imports, source preflight, and watch token refresh. VLM, memory, embedding, and vector database account overrides remain follow-up work and are not accepted by the current API.## 6. Persistence@@ -137,4 +137,4 @@ The focused mechanism tests are:pytest tests/config/test_runtime_config.py```-They cover field discovery, three-state merging, dynamic/create-only validation, lazy Account loading, publication isolation, consumer notification, idle eviction, fallback, and file-source backup behavior.+They cover field discovery, three-state merging, runtime-surface validation, lazy Account loading, publication isolation, consumer notification, idle eviction, fallback, Feishu overlay behavior, and file-source backup behavior.diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex c6206f564..7b9456386 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -421,7 +421,7 @@ active configuration remains unchanged. Structurally valid older overrides usingunsupported Jinja can still be read, replaced or reset, but extraction refuses toexecute them unchecked. Corrupt YAML remains an explicit error.-### runtime_configuration+### Runtime ConfigurationROOT can manage Cluster configuration and any Account configuration. ADMIN canmanage only its own Account layer.@@ -441,26 +441,26 @@ Content-Type: application/jsonthree-state: an absent key is unchanged, `null` deletes that layer's value, anda concrete value updates it.-The Cluster runtime surface currently contains agent_evolution. The Account-surface contains vlm, memory, feishu, agent_evolution, github, and acl as-dynamic fields, plus embedding and vectordb as create-only fields. Cluster-embedding, vlm, query_planner, memory, storage, parser, and retrieval fields-are startup-only because they are not declared as runtime fields.--dynamic=True fields may be set when an Account is created and changed by a-later PATCH. dynamic=False fields may be set only during Account creation;-later PATCH requests that touch them are rejected. embedding and vectordb must-be supplied together when explicitly configured, and their dimensions must-match. Account fields may declare a whole-section Cluster fallback. An Account-section that is explicitly set does not merge individual omitted properties-from the Cluster section; omitted properties use the model defaults.+The Cluster runtime surface currently contains `agent_evolution`. The Account+surface contains `feishu`, `agent_evolution`, `github`, and `acl`, all of which+are dynamic. Account `vlm`, `memory`, `embedding`, and `vectordb` are not on the+current API surface and are rejected even during Account creation. Cluster+`embedding`, `vlm`, `query_planner`, `memory`, `feishu`, storage, parser, and+retrieval fields are startup-only because they are not declared as runtime+fields.++Account Agent Evolution uses whole-section Cluster fallback when unset. Account+Feishu also uses the complete Cluster section when unset. Once an Account Feishu+section is set, `app_id`, `app_secret`, `max_rows_per_sheet`,+`max_records_per_table`, `download_images`, and `request_timeout` come from the+Account section or their Feishu defaults; only `domain` remains Cluster-owned.+GitHub and ACL have no Cluster fallback.The PATCH is validated structurally before the merged configuration is built:-unknown paths and fields outside the runtime surface are rejected, and-create-only fields are rejected on ordinary PATCH. Objects merge recursively;-arrays replace wholesale. A nested null removes only that leaf. To remove a-whole object override, send null at the parent path; an empty object remains an-explicit empty object.+unknown paths and fields outside the runtime surface are rejected. Objects merge+recursively; arrays replace wholesale. A nested null removes only that leaf. To+remove a whole object override, send null at the parent path; an empty object+remains an explicit empty object.Both GET endpoints return only the explicit values persisted at the addressedlayer. They do not expand fallback values. After persistence, the newdiff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 0d7002852..edddfd75a 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -59,11 +59,10 @@ Only fields explicitly declared as runtime fields are exposed by the runtime con| Scope | Configuration | Lifecycle | Effective behavior || --- | --- | --- | --- || Cluster | `agent_evolution` | Dynamic | ROOT can update it through the Admin API; it is used as the cluster default. |-| Account | `vlm`, `memory`, `feishu`, `agent_evolution` | Dynamic | ROOT or the Account ADMIN can update it. The first four sections declare Cluster fallback; currently Agent Evolution is consumed through the runtime manager. |+| Account | `feishu`, `agent_evolution` | Dynamic | ROOT or the Account ADMIN can update them. Agent Evolution falls back to the whole Cluster section. An unset Account Feishu section also uses the Cluster section; once set, only `domain` comes from Cluster and omitted Account fields use Feishu defaults. Both are consumed through the runtime manager. || Account | `github`, `acl` | Dynamic | ROOT or the Account ADMIN can update it. These sections have no Cluster fallback. |-| Account | `embedding`, `vectordb` | Create-only | Can be supplied when creating an Account, but cannot be changed by a later configuration PATCH. They must be configured together when explicitly set. |-Cluster `embedding`, Cluster `vlm`, `query_planner`, Cluster `memory`, storage, parser, retrieval, and other ordinary configuration sections remain startup-only. Account `vlm`, `memory`, `feishu`, `embedding`, and `vectordb` values can currently be validated and persisted, but their complete business consumer integrations are still being rolled out; do not interpret persistence alone as proof that every component has switched.+Cluster `embedding`, Cluster `vlm`, `query_planner`, Cluster `memory`, `feishu`, storage, parser, retrieval, and other ordinary configuration sections remain startup-only. Account `vlm`, `memory`, `embedding`, and `vectordb` are not on the current Account configuration API surface; requests that contain them are rejected.For runtime changes, use the following endpoints:diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 447cf06ba..98dba30f9 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -353,7 +353,7 @@ Events 的默认 embedding 模板引用正文,因此正文变化也可能影{% endfor %}```-### runtime_configuration+### Runtime ConfigurationROOT 可管理 Cluster 配置和任意 Account 配置;ADMIN 只能管理所属账号的 Account 层。@@ -371,21 +371,22 @@ Content-Type: application/json`settings` 始终表示目标层的显式设置值。PATCH 为三态语义:字段缺失表示不修改,`null` 表示删除当前层配置,具体值表示更新。-当前 Cluster 运行时配置面仅包含 agent_evolution。Account 配置面包含-vlm、memory、feishu、agent_evolution、github、acl 这些动态字段,以及-embedding、vectordb 这两个仅创建时可设置的字段。Cluster 的 embedding、vlm、-query_planner、memory、存储、解析器和检索配置没有声明为运行时字段,因此仍然-只能在启动配置中修改。--dynamic=True 的字段可以在创建 Account 时设置,也可以通过后续 PATCH 修改;-dynamic=False 的字段只能在创建 Account 时设置,后续 PATCH 触及时会被拒绝。-显式配置 embedding 和 vectordb 时必须成对提供,并且维度必须一致。Account-字段可以声明整个配置段的 Cluster fallback。Account 一旦显式设置某个配置段,-其中省略的属性不会逐项从 Cluster 配置合并,而是使用该模型的默认值。--PATCH 会先做结构校验,再构造合并后的配置:未知路径、运行时配置面之外的字段会被拒绝,-普通 PATCH 触及仅创建字段时也会被拒绝。对象递归合并,数组整体替换;嵌套 null-只删除对应叶子。删除整个对象覆盖需要在父路径传 null,传空对象仍表示显式空对象。+当前 Cluster 运行时配置面仅包含 `agent_evolution`。Account 配置面包含+`feishu`、`agent_evolution`、`github` 和 `acl`,且均为动态字段。Account 的+`vlm`、`memory`、`embedding` 和 `vectordb` 不在当前 API 范围内,即使创建+Account 时提交也会被拒绝。Cluster 的 `embedding`、`vlm`、`query_planner`、+`memory`、`feishu`、存储、解析器和检索配置没有声明为运行时字段,因此仍然只能+在启动配置中修改。++Account Agent Evolution 未设置时整段回落到 Cluster 配置。Account 未设置+Feishu 时也整段使用 Cluster 配置;一旦设置,`app_id`、`app_secret`、+`max_rows_per_sheet`、`max_records_per_table`、`download_images` 和+`request_timeout` 来自 Account 配置或 Feishu 默认值,只有 `domain` 仍由+Cluster 管理。GitHub 和 ACL 没有 Cluster fallback。++PATCH 会先做结构校验,再构造合并后的配置:未知路径和运行时配置面之外的字段会被拒绝。+对象递归合并,数组整体替换;嵌套 null 只删除对应叶子。删除整个对象覆盖需要在父路径+传 null,传空对象仍表示显式空对象。两个 GET 接口只返回目标层持久化的显式值,不展开 fallback。配置持久化后会发布新配置并等待匹配的进程内 Consumer;Consumer 失败会记录日志但不会回滚已持久化的覆盖,因此接口成功只表示diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex f5eae94de..e7f4b6f54 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -60,11 +60,10 @@ OpenViking 的配置分为两个层级:| 范围 | 配置 | 生命周期 | 生效说明 || --- | --- | --- | --- || Cluster | `agent_evolution` | 动态配置 | ROOT 可通过 Admin API 修改,作为集群默认值使用。 |-| Account | `vlm`、`memory`、`feishu`、`agent_evolution` | 动态配置 | ROOT 或该 Account 的 ADMIN 可修改;这些配置段声明了 Cluster fallback。目前只有 Agent Evolution 已通过运行时管理器接入业务读取。 |+| Account | `feishu`、`agent_evolution` | 动态配置 | ROOT 或该 Account 的 ADMIN 可修改。Agent Evolution 整段回落到 Cluster 配置。Account 未设置 Feishu 时也整段使用 Cluster 配置;一旦设置,则仅 `domain` 来自 Cluster,省略的 Account 字段使用 Feishu 默认值。两者都已通过运行时管理器接入业务读取。 || Account | `github`、`acl` | 动态配置 | ROOT 或该 Account 的 ADMIN 可修改;没有 Cluster fallback。 |-| Account | `embedding`、`vectordb` | 仅创建时配置 | 创建 Account 时可以设置,后续不能通过配置 PATCH 修改;显式设置时必须成对配置。 |-Cluster 的 `embedding`、Cluster 的 `vlm`、`query_planner`、Cluster 的 `memory`、存储、解析器、检索等普通配置仍然是启动配置。Account 的 `vlm`、`memory`、`feishu`、`embedding` 和 `vectordb` 当前可以完成校验和持久化,但业务消费方尚未全部接入;配置成功保存不代表所有组件都已经切换。+Cluster 的 `embedding`、`vlm`、`query_planner`、`memory`、`feishu`、存储、解析器、检索等普通配置仍然是启动配置。Account 的 `vlm`、`memory`、`embedding` 和 `vectordb` 不在当前 Account 配置 API 范围内,包含这些字段的请求会被拒绝。修改运行时配置使用以下接口:diff --git a/openviking/config/account_config.py b/openviking/config/account_config.pyindex 7dcf97f87..548bc9ed2 100644--- a/openviking/config/account_config.py+++ b/openviking/config/account_config.py@@ -22,7 +22,23 @@ from openviking_cli.utils.config.runtime_field import RuntimeFieldclass AccountAclSettings(BaseModel):"""Account-scoped ACL switch."""- enabled: bool = False+ enabled: bool = RuntimeField(default=False)+++class AccountFeishuConfig(BaseModel):+ """Sparse account-level Feishu overrides.++ ``domain`` intentionally does not exist here. It is a cluster deployment+ setting and is selected from the cluster configuration by the business+ resolver.+ """++ app_id: Optional[str] = RuntimeField(default=None)+ app_secret: Optional[str] = RuntimeField(default=None)+ max_rows_per_sheet: Optional[int] = RuntimeField(default=None, gt=0)+ max_records_per_table: Optional[int] = RuntimeField(default=None, gt=0)+ download_images: Optional[bool] = RuntimeField(default=None)+ request_timeout: Optional[float] = RuntimeField(default=None, gt=0)class AccountConfig(BaseModel):@@ -33,7 +49,8 @@ class AccountConfig(BaseModel):unset."""- # These are the only account-level settings with active business consumers.+ # Account-level settings with active business consumers.+ feishu: Optional[AccountFeishuConfig] = RuntimeField(default=None)github: Optional[GitHubConfig] = RuntimeField(default=None)agent_evolution: Optional[AgentEvolutionConfig] = RuntimeField(default=None,@@ -41,7 +58,7 @@ class AccountConfig(BaseModel):)acl: Optional[AccountAclSettings] = RuntimeField(default=None)- # Deferred account-level sections (vlm, memory, feishu, embedding, vectordb)+ # Deferred account-level sections (vlm, memory, embedding, vectordb)# have no active consumers. Ignore historical or newer persisted sections;# validate_patch() still keeps API writes limited to the fields above.model_config = {"arbitrary_types_allowed": True, "extra": "ignore"}diff --git a/openviking/config/feishu.py b/openviking/config/feishu.pynew file mode 100644index 000000000..ab3a7d31d--- /dev/null+++ b/openviking/config/feishu.py@@ -0,0 +1,50 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Business-level resolution for account and cluster Feishu configuration."""++from __future__ import annotations++from dataclasses import replace+from typing import Any++from openviking.config.account_config import AccountConfig+from openviking.config.manager import AccountConfigView+from openviking_cli.utils.config.open_viking_config import OpenVikingConfig+from openviking_cli.utils.config.parser_config import FeishuConfig++_ACCOUNT_FEISHU_FIELDS = (+ "app_id",+ "app_secret",+ "max_rows_per_sheet",+ "max_records_per_table",+ "download_images",+ "request_timeout",+)+++def resolve_feishu_config(+ view: AccountConfigView[OpenVikingConfig, AccountConfig],+) -> FeishuConfig:+ """Resolve one account's Feishu configuration.++ An account without a Feishu section uses the complete cluster configuration.+ Once the section exists, only the API domain remains cluster-owned; omitted+ account fields use ``FeishuConfig`` defaults instead of cluster values.+ """+ cluster_config = view.cluster.feishu+ account_config = view.account.feishu+ if account_config is None:+ return cluster_config++ account_defaults = FeishuConfig(domain=cluster_config.domain)+ updates = {+ field: value+ for field in _ACCOUNT_FEISHU_FIELDS+ if (value := getattr(account_config, field)) is not None+ }+ return replace(account_defaults, **updates)+++async def get_effective_feishu_config(manager: Any, account_id: str) -> FeishuConfig:+ """Resolve Feishu config from one account/cluster publication pair."""+ return await manager.resolve_account(account_id, resolve_feishu_config)diff --git a/openviking/config/manager.py b/openviking/config/manager.pyindex b3304bbd6..22f47a41c 100644--- a/openviking/config/manager.py+++ b/openviking/config/manager.py@@ -42,6 +42,39 @@ logger = get_logger(__name__)# C = cluster config type; A = per-account config type.C = TypeVar("C")A = TypeVar("A")+T = TypeVar("T")+++@dataclass(frozen=True)+class AccountConfigView(Generic[C, A]):+ """Resolve fields against a captured account/cluster publication pair.++ Used only by synchronous selectors, never as a request context. Returned+ models are shared, read-only configuration values.+ """++ _account: A+ _cluster: C++ @property+ def account(self) -> A:+ """Return the captured sparse account configuration."""+ return self._account++ @property+ def cluster(self) -> C:+ """Return the captured cluster configuration."""+ return self._cluster++ def get(self, field: str) -> Any:+ fields = getattr(type(self._account), "model_fields", {})+ if field not in fields:+ raise AttributeError(field)+ value = getattr(self._account, field)+ if value is not None:+ return value+ target = fallback_of(fields[field])+ return resolve_fallback(self._cluster, target) if target is not None else NoneREFRESH_INTERVAL_SECS = 30.0# Accounts unused for this long are evicted and stop being polled.@@ -219,23 +252,34 @@ class RuntimeConfigManager(Generic[C, A]):async def get_account(self, account_id: str, field: str) -> Any:"""Load an account on demand and return one effective config field."""+ return await self.resolve_account(account_id, lambda view: view.get(field))++ async def resolve_account(+ self, account_id: str, resolver: Callable[[AccountConfigView[C, A]], T]+ ) -> T:+ """Select a domain value from one publication pair.++ Selectors must be synchronous and perform no I/O or configuration+ mutations. Loading and cancellation have the same contract as get_account.+ """return await self._dispatcher.run(- lambda: run_to_completion(lambda: self._get_account(account_id, field))+ lambda: run_to_completion(lambda: self._resolve_account(account_id, resolver)))- async def _get_account(self, account_id: str, field: str) -> Any:+ async def _resolve_account(+ self, account_id: str, resolver: Callable[[AccountConfigView[C, A]], T]+ ) -> T:await self._ensure_loaded(account_id)- entry = self._accounts[account_id]- model_fields = getattr(type(entry.config), "model_fields", {})- if field not in model_fields:- raise AttributeError(field)- value = getattr(entry.config, field)- if value is not None:- return value- target = fallback_of(model_fields[field])- if target is None:- return None- return resolve_fallback(self._get_config(), target)+ # No await between capturing the publications and running the selector.+ view = AccountConfigView(self._accounts[account_id].config, self._get_config())+ result = resolver(view)+ import inspect++ if inspect.isawaitable(result):+ if inspect.iscoroutine(result):+ result.close()+ raise TypeError("account configuration resolver must be synchronous")+ return resultasync def get_settings(self, scope: ConfigScope) -> dict:"""Read explicit overrides, never the merged configuration."""diff --git a/openviking/config/validate.py b/openviking/config/validate.pyindex 0317b1ff3..efab237af 100644--- a/openviking/config/validate.py+++ b/openviking/config/validate.py@@ -8,15 +8,15 @@ module enforces the structural rules that do not depend on the concrete configmodel, so a single generic router can serve every section without per-fieldbranches:-1. top-level sections must be declared with :func:`RuntimeField`. If a section- has marked descendants, input paths are restricted to those declarations;- otherwise the whole section is accepted for subsequent model validation;+1. every component of a modified path must be declared with+ :func:`RuntimeField`; marking a section does not implicitly grant write+ access to its ordinary ``Field`` descendants;2. cluster-vs-account scope is confined by *which model is validated against*(``OpenVikingConfig`` for a cluster PATCH, ``AccountConfig`` for an accountPATCH) — there is no per-field scope flag;3. objects merge recursively, arrays replace wholesale (a list value is a leaf);-4. ``None`` is the three-state "delete this override" and is allowed on any- surface leaf path, except a ``dynamic=False`` field on a non-creating PATCH.+4. ``None`` is the three-state "delete this override". Deleting a section is+ allowed only when its whole model subtree is writable for the operation.Type and cross-field validation of the *merged* result still happens later whenthe merged dict is parsed back into the real config model; this layer only gates@@ -25,6 +25,7 @@ the request shape, not the semantic validity of individual values.from __future__ import annotations+import dataclassesimport typesimport typingfrom typing import Any@@ -71,9 +72,10 @@ def validate_patch(if not isinstance(patch, dict):raise ConfigPatchError("patch must be a JSON object")allowed = collect_runtime_field_paths(model)- _walk(patch, (), allowed, model)+ frozen = collect_frozen_paths(model)+ _walk(patch, (), allowed, frozen, model, creating)if not creating:- _reject_frozen(patch, (), collect_frozen_paths(model))+ _reject_frozen(patch, (), frozen)def _reject_frozen(@@ -98,7 +100,9 @@ def _walk(node: dict[str, Any],prefix: tuple[str, ...],allowed: set[tuple[str, ...]],+ frozen: set[tuple[str, ...]],root_model: type[BaseModel],+ creating: bool,) -> None:for key, value in node.items():if not isinstance(key, str):@@ -106,66 +110,87 @@ def _walk(path = prefix + (key,)if path not in allowed:raise ConfigPatchError("field is not modifiable by the config API", path=path)- # None (delete) and non-dict values (scalar / list-replace) are leaves.- if value is None or not isinstance(value, dict):+ if value is None:+ _validate_subtree_delete(path, allowed, frozen, root_model, creating)+ continue+ # Non-dict values (scalar / list-replace) are leaves.+ if not isinstance(value, dict):continue- # Sections with no marked descendants are validated as a whole by the- # model constructor. Keep API input strict even though persisted config- # models intentionally ignore unknown fields for version compatibility.- if _has_children(path, allowed):- _walk(value, path, allowed, root_model)- else:- nested_model = _model_at_path(root_model, path)- if nested_model is not None:- _reject_unknown_model_fields(value, path, nested_model)+ nested_model = _model_at_path(root_model, path)+ if nested_model is not None:+ _walk(value, path, allowed, frozen, root_model, creating)-def _has_children(prefix: tuple[str, ...], allowed: set[tuple[str, ...]]) -> bool:- plen = len(prefix)- return any(len(p) > plen and p[:plen] == prefix for p in allowed)+def _validate_subtree_delete(+ path: tuple[str, ...],+ allowed: set[tuple[str, ...]],+ frozen: set[tuple[str, ...]],+ root_model: type[BaseModel],+ creating: bool,+) -> None:+ """Require every field removed by a section-level ``None`` to be writable."""+ nested_model = _model_at_path(root_model, path)+ if nested_model is None:+ return+ for descendant in _model_field_paths(nested_model, path):+ if descendant not in allowed:+ raise ConfigPatchError(+ "field is not modifiable by the config API", path=descendant+ )+ if not creating and descendant in frozen:+ raise ConfigPatchError(+ "field is create-only and cannot be changed after creation",+ path=descendant,+ )+++def _model_field_paths(+ model: type[Any],+ prefix: tuple[str, ...],+ ancestors: frozenset[type[Any]] = frozenset(),+) -> list[tuple[str, ...]]:+ if model in ancestors:+ return []+ paths: list[tuple[str, ...]] = []+ next_ancestors = ancestors | {model}+ for name, field in _model_fields(model).items():+ path = prefix + (name,)+ paths.append(path)+ nested = _unwrap_model(_field_annotation(field))+ if nested is not None:+ paths.extend(_model_field_paths(nested, path, next_ancestors))+ return pathsdef _model_at_path(root_model: type[BaseModel],path: tuple[str, ...],-) -> type[BaseModel] | None:+) -> type[Any] | None:model = root_modelfor part in path:- field = model.model_fields.get(part)+ field = _model_fields(model).get(part)if field is None:return None- nested = _unwrap_model(field.annotation)+ nested = _unwrap_model(_field_annotation(field))if nested is None:return Nonemodel = nestedreturn model-def _reject_unknown_model_fields(- node: dict[str, Any],- prefix: tuple[str, ...],- model: type[BaseModel],-) -> None:- accepted: dict[str, str] = {}- for field_name, field in model.model_fields.items():- accepted[field_name] = field_name- for alias in (field.alias, field.validation_alias):- if isinstance(alias, str):- accepted[alias] = field_name+def _model_fields(model: type[Any]) -> dict[str, Any]:+ if isinstance(model, type) and issubclass(model, BaseModel):+ return dict(model.model_fields)+ if dataclasses.is_dataclass(model):+ return {field.name: field for field in dataclasses.fields(model)}+ return {}- for key, value in node.items():- field_name = accepted.get(key)- path = prefix + (key,)- if field_name is None:- raise ConfigPatchError("field is not recognized", path=path)- if not isinstance(value, dict):- continue- nested = _unwrap_model(model.model_fields[field_name].annotation)- if nested is not None:- _reject_unknown_model_fields(value, path, nested)++def _field_annotation(field: Any) -> Any:+ return getattr(field, "annotation", getattr(field, "type", None))-def _unwrap_model(annotation: Any) -> type[BaseModel] | None:+def _unwrap_model(annotation: Any) -> type[Any] | None:origin = typing.get_origin(annotation)if origin in (typing.Union, types.UnionType):for arg in typing.get_args(annotation):@@ -175,6 +200,8 @@ def _unwrap_model(annotation: Any) -> type[BaseModel] | None:if nested is not None:return nestedreturn None- if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ if isinstance(annotation, type) and (+ issubclass(annotation, BaseModel) or dataclasses.is_dataclass(annotation)+ ):return annotationreturn Nonediff --git a/openviking/parse/accessors/base.py b/openviking/parse/accessors/base.pyindex 5a85706a6..e780f817f 100644--- a/openviking/parse/accessors/base.py+++ b/openviking/parse/accessors/base.py@@ -102,6 +102,11 @@ class DataAccessor(ABC):"""Abstract base class for data accessors.+ Registry-owned accessor instances may be shared by concurrent requests.+ Implementations must therefore be reentrant: constructor state must be+ immutable or concurrency-safe, and request-scoped mutable state must live+ in local variables or in an operation object created by ``access()``.+Data Accessors are responsible for:- Detecting if they can handle a given source- Fetching the data from the source to a local path@@ -130,6 +135,11 @@ class DataAccessor(ABC):"""Fetch the source and make it available locally.+ The same accessor instance may execute this method concurrently. Do not+ store request-specific credentials, configuration, clients, temporary+ paths, or progress on ``self``. If an implementation needs shared state+ within one access operation, create a request-scoped operation object.+Args:source: Source string (URL, path, etc.) or Path object**kwargs: Additional accessor-specific argumentsdiff --git a/openviking/parse/accessors/feishu_accessor.py b/openviking/parse/accessors/feishu_accessor.pyindex e2484552d..98df926f7 100644--- a/openviking/parse/accessors/feishu_accessor.py+++ b/openviking/parse/accessors/feishu_accessor.py@@ -10,9 +10,9 @@ Included by default in `openviking[bot]` installation."""import asyncio+import copyimport jsonimport mimetypes-import osimport reimport shutilimport tempfile@@ -21,6 +21,8 @@ from pathlib import Pathfrom typing import Any, Dict, List, NoReturn, Optional, Tuple, Unionfrom urllib.parse import parse_qs, unquote, urlparse, urlunparse+from lark_oapi.core.cache import ICache+from openviking.parse.base import format_table_to_markdownfrom openviking.parse.feishu_import import FeishuImportPlan, recursive_wikifrom openviking.utils.exceptions import error_code_from_http_status@@ -28,6 +30,7 @@ from openviking_cli.exceptions import InvalidArgumentError, OpenVikingErrorfrom openviking_cli.utils.logger import get_loggerfrom .base import DataAccessor, LocalResource, SourceType+from .feishu_session import FeishuAccessContext, FeishuApiSessionfrom .mime_types import get_preferred_extensionlogger = get_logger(__name__)@@ -363,11 +366,37 @@ class FeishuAccessor(DataAccessor):})- def __init__(self):- """Initialize Feishu accessor."""- self._client = None- self._user_token_client = None- self._config = None+ def __init__(+ self,+ session: Optional[FeishuApiSession] = None,+ *,+ tenant_token_cache: Optional[ICache] = None,+ ):+ """Initialize a shared selector or a request-scoped worker."""+ self._session = session+ self._tenant_token_cache = tenant_token_cache++ def _new_operation(+ self,+ source: Union[str, Path],+ *,+ config: Any = None,+ ) -> "FeishuAccessor":+ context = FeishuAccessContext.from_request(+ str(source),+ config=config,+ )+ worker = copy.copy(self)+ worker._session = FeishuApiSession(+ context,+ tenant_token_cache=self._tenant_token_cache,+ )+ return worker++ def _require_session(self) -> FeishuApiSession:+ if self._session is None:+ raise RuntimeError("Feishu operation requires a request-scoped API session")+ return self._session@propertydef priority(self) -> int:@@ -388,6 +417,14 @@ class FeishuAccessor(DataAccessor):return self._is_feishu_url(source_str)async def access(self, source: Union[str, Path], **kwargs) -> LocalResource:+ """Bind request-scoped state, then fetch the source."""+ worker = self._new_operation(+ source,+ config=kwargs.get("feishu_config"),+ )+ return await worker._access(source, **kwargs)++ async def _access(self, source: Union[str, Path], **kwargs) -> LocalResource:"""Fetch a Feishu document and save to a temporary Markdown file.@@ -591,12 +628,18 @@ class FeishuAccessor(DataAccessor):source: Union[str, Path],*,feishu_access_token: Optional[str] = None,+ feishu_config: Any = None,feishu_recursive: bool = False,) -> FeishuSourcePreflight:"""Resolve lightweight source identity and root permission before enqueueing."""+ source_str = str(source)+ worker = self._new_operation(+ source_str,+ config=feishu_config,+ )return await asyncio.to_thread(- self._preflight_source_sync,- str(source),+ worker._preflight_source_sync,+ source_str,feishu_access_token,feishu_recursive,)@@ -940,10 +983,9 @@ class FeishuAccessor(DataAccessor):finally:seen.discard(folder_token)- @classmethod- def _import_doc_url(cls, plan: FeishuImportPlan, doc_type: str, token: str) -> str:+ def _import_doc_url(self, plan: FeishuImportPlan, doc_type: str, token: str) -> str:if not plan.source_url:- return cls._build_feishu_doc_url(doc_type, token)+ return self._build_feishu_doc_url(doc_type, token)source = urlparse(plan.source_url)path_type = "docs" if doc_type == "doc" else doc_typequery = source.query if source.path.rstrip("/").endswith(f"/{token}") else ""@@ -1470,11 +1512,11 @@ class FeishuAccessor(DataAccessor):token = str(_getattr_safe(shortcut_info, "target_token", token) or token)return item_type, token, name, url- @staticmethod- def _build_feishu_doc_url(doc_type: str, token: str) -> str:+ def _build_feishu_doc_url(self, doc_type: str, token: str) -> str:if doc_type == "doc":doc_type = "docs"- return f"https://open.feishu.cn/{doc_type}/{token}"+ domain = self._get_config().domain.rstrip("/")+ return f"{domain}/{doc_type}/{token}"@staticmethoddef _unique_child_path(parent: Path, name: str, reserved: Optional[set[Path]] = None) -> Path:@@ -1564,42 +1606,12 @@ class FeishuAccessor(DataAccessor):# ========== Configuration & Client ==========def _get_config(self):- """Get FeishuConfig from OpenViking config."""- if self._config is None:- from openviking_cli.utils.config import get_openviking_config-- self._config = get_openviking_config().feishu- return self._config+ """Return the configuration for the current operation."""+ return self._require_session().context.configdef _get_client(self, *, use_user_token: bool = False):- """Lazy-init lark-oapi client."""- cache_attr = "_user_token_client" if use_user_token else "_client"- client = getattr(self, cache_attr)- if client is None:- try:- import lark_oapi as lark- except ImportError:- raise ImportError(- "lark-oapi is required for Feishu document parsing. "- "Install it with: pip install lark-oapi>=1.0.0"- )- config = self._get_config()- app_id = config.app_id or os.getenv("FEISHU_APP_ID", "")- app_secret = config.app_secret or os.getenv("FEISHU_APP_SECRET", "")- if (not app_id or not app_secret) and not use_user_token:- raise ValueError(- "Feishu credentials not configured. Set FEISHU_APP_ID and "- "FEISHU_APP_SECRET environment variables, or configure in ov.conf."- )- domain = config.domain or "https://open.feishu.cn"- builder = lark.Client.builder().domain(domain)- if app_id and app_secret:- builder = builder.app_id(app_id).app_secret(app_secret)- if use_user_token:- builder = builder.enable_set_token(True)- client = builder.build()- setattr(self, cache_attr, client)- return client+ """Return the request-scoped lark-oapi client."""+ return self._require_session().client(use_user_token=use_user_token)@staticmethoddef _user_request_option(feishu_access_token: Optional[str]):@@ -1611,7 +1623,10 @@ class FeishuAccessor(DataAccessor):def _call_api(self, method, request, feishu_access_token: Optional[str] = None):option = self._user_request_option(feishu_access_token)- return method(request) if option is None else method(request, option)+ if option is not None:+ return method(request, option)+ with self._require_session().tenant_token_cache_scope():+ return method(request)@classmethoddef _raw_feishu_error(cls, raw_resp: Any) -> Optional[Tuple[int, str]]:@@ -1654,8 +1669,13 @@ class FeishuAccessor(DataAccessor):from lark_oapi.core.token import verifyoption = self._user_request_option(feishu_access_token) or RequestOption()- verify(client._config, request, option)- raw_resp = Transport.execute(client._config, request, option)+ if feishu_access_token:+ verify(client._config, request, option)+ raw_resp = Transport.execute(client._config, request, option)+ else:+ with self._require_session().tenant_token_cache_scope():+ verify(client._config, request, option)+ raw_resp = Transport.execute(client._config, request, option)response = BaseResponse()feishu_error = self._raw_feishu_error(raw_resp)diff --git a/openviking/parse/accessors/feishu_session.py b/openviking/parse/accessors/feishu_session.pynew file mode 100644index 000000000..2bb410e8b--- /dev/null+++ b/openviking/parse/accessors/feishu_session.py@@ -0,0 +1,117 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Request-scoped Feishu configuration and API clients."""++import os+from contextlib import contextmanager+from dataclasses import dataclass, field, replace+from typing import Any, Generator, Optional+from urllib.parse import urlparse++from lark_oapi.core.cache import ICache++from openviking_cli.utils.config.parser_config import FeishuConfig++from .feishu_token import (+ resolve_feishu_tenant_token_cache,+)+++def _default_api_domain(source_url: str) -> str:+ host = (urlparse(source_url).hostname or "").lower()+ if host.endswith(("larksuite.com", "larkoffice.com")):+ return "https://open.larksuite.com"+ return "https://open.feishu.cn"+++@dataclass(frozen=True, slots=True)+class FeishuAccessContext:+ """Immutable configuration snapshot for one accessor operation."""++ config: FeishuConfig = field(repr=False)++ @classmethod+ def from_request(+ cls,+ source_url: str,+ *,+ config: Optional[FeishuConfig] = None,+ ) -> "FeishuAccessContext":+ effective_config = config+ if effective_config is None:+ effective_config = replace(+ FeishuConfig(),+ domain=_default_api_domain(source_url),+ )+ return cls(config=effective_config)+++class FeishuApiSession:+ """Own lark-oapi clients for exactly one accessor operation."""++ def __init__(+ self,+ context: FeishuAccessContext,+ *,+ tenant_token_cache: ICache | None = None,+ ):+ self.context = context+ self._clients: dict[bool, Any] = {}+ self._tenant_token_cache = resolve_feishu_tenant_token_cache(tenant_token_cache)++ def client(self, *, use_user_token: bool) -> Any:+ cached = self._clients.get(use_user_token)+ if cached is not None:+ return cached++ try:+ import lark_oapi as lark+ except ImportError:+ raise ImportError(+ "lark-oapi is required for Feishu document parsing. "+ "Install it with: pip install lark-oapi>=1.0.0"+ )++ builder = (+ lark.Client.builder()+ .domain(self.context.config.domain)+ .timeout(self.context.config.request_timeout)+ )+ if use_user_token:+ builder = builder.enable_set_token(True)+ else:+ config = self.context.config+ app_id = config.app_id or os.getenv("FEISHU_APP_ID", "")+ app_secret = config.app_secret or os.getenv("FEISHU_APP_SECRET", "")+ if not app_id or not app_secret:+ raise ValueError(+ "Feishu credentials not configured. Set FEISHU_APP_ID and "+ "FEISHU_APP_SECRET environment variables, or configure in ov.conf."+ )+ builder = (+ builder.app_id(app_id)+ .app_secret(app_secret)+ .cache(self._tenant_token_cache)+ )++ client = builder.build()+ self._clients[use_user_token] = client+ return client++ @contextmanager+ def tenant_token_cache_scope(self) -> Generator[None, None, None]:+ """Bind Account credentials while lark-oapi obtains a tenant token."""+ config = self.context.config+ app_id = config.app_id or os.getenv("FEISHU_APP_ID", "")+ app_secret = config.app_secret or os.getenv("FEISHU_APP_SECRET", "")+ if not app_id or not app_secret:+ raise ValueError(+ "Feishu credentials not configured. Set FEISHU_APP_ID and "+ "FEISHU_APP_SECRET environment variables, or configure in ov.conf."+ )+ with self._tenant_token_cache.sdk_scope(+ app_id=app_id,+ app_secret=app_secret,+ domain=config.domain,+ ):+ yielddiff --git a/openviking/parse/accessors/feishu_token.py b/openviking/parse/accessors/feishu_token.pynew file mode 100644index 000000000..5d2d6466b--- /dev/null+++ b/openviking/parse/accessors/feishu_token.py@@ -0,0 +1,125 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Account-isolated cache adapter for lark-oapi tenant tokens."""++from __future__ import annotations++import hashlib+import threading+import time+from contextlib import contextmanager+from contextvars import ContextVar+from typing import Generator++from lark_oapi.core.cache import ICache++_SDK_TOKEN_MANAGER_LOCK = threading.RLock()+++class InMemoryFeishuTokenCache(ICache):+ """Thread-safe default storage for namespaced tenant tokens."""++ def __init__(self) -> None:+ self._entries: dict[str, tuple[str, int]] = {}+ self._lock = threading.Lock()++ def get(self, key: str) -> str | None:+ with self._lock:+ entry = self._entries.get(key)+ if entry is None:+ return None+ token, expire = entry+ if expire <= time.time():+ del self._entries[key]+ return None+ return token++ def set(self, key: str, value: str, expire: int) -> None:+ with self._lock:+ self._entries[key] = (value, expire)+++class FeishuTenantTokenCache(ICache):+ """lark-oapi ``ICache`` adapter with credential-scoped keys.++ lark-oapi only passes ``self_tenant_token:{app_id}`` to ``ICache`` and+ stores one process-global cache instance. Callers bind the active+ credential namespace around SDK calls, so one adapter safely serves all+ Accounts without exposing a raw secret in the storage key.+ """++ def __init__(self, backend: ICache | None = None) -> None:+ self._backend = backend if backend is not None else InMemoryFeishuTokenCache()+ self._namespace: ContextVar[str | None] = ContextVar(+ "feishu_tenant_token_namespace",+ default=None,+ )++ @contextmanager+ def bind(+ self,+ *,+ app_id: str,+ app_secret: str,+ domain: str,+ ) -> Generator[None, None, None]:+ material = "\0".join((domain.rstrip("/"), app_id, app_secret)).encode("utf-8")+ token = self._namespace.set(hashlib.sha256(material).hexdigest())+ try:+ yield+ finally:+ self._namespace.reset(token)++ @contextmanager+ def sdk_scope(+ self,+ *,+ app_id: str,+ app_secret: str,+ domain: str,+ ) -> Generator[None, None, None]:+ """Install this adapter while lark-oapi obtains a tenant token.++ lark-oapi 1.5 stores its cache in the process-global+ ``TokenManager.cache`` rather than on ``Config``. Keep this adapter+ installed so concurrent SDK calls share its ContextVar isolation+ without serializing their network requests.+ """+ from lark_oapi.core.token import TokenManager++ with self.bind(+ app_id=app_id,+ app_secret=app_secret,+ domain=domain,+ ):+ with _SDK_TOKEN_MANAGER_LOCK:+ TokenManager.cache = self+ yield++ def get(self, key: str) -> str | None:+ namespace = self._namespace.get()+ return self._backend.get(f"{namespace}:{key}") if namespace is not None else None++ def set(self, key: str, value: str, expire: int) -> None:+ namespace = self._namespace.get()+ if namespace is not None:+ self._backend.set(f"{namespace}:{key}", value, expire)+++_DEFAULT_TENANT_TOKEN_CACHE = FeishuTenantTokenCache()+++def default_feishu_tenant_token_cache() -> FeishuTenantTokenCache:+ """Return the process-shared, credential-scoped SDK cache adapter."""+ return _DEFAULT_TENANT_TOKEN_CACHE+++def resolve_feishu_tenant_token_cache(+ cache: ICache | FeishuTenantTokenCache | None,+) -> FeishuTenantTokenCache:+ """Return an adapter, using a supplied SDK cache as its backend."""+ if cache is None:+ return default_feishu_tenant_token_cache()+ if isinstance(cache, FeishuTenantTokenCache):+ return cache+ return FeishuTenantTokenCache(cache)diff --git a/openviking/parse/parsers/directory.py b/openviking/parse/parsers/directory.pyindex 886b8108a..532eb9461 100644--- a/openviking/parse/parsers/directory.py+++ b/openviking/parse/parsers/directory.py@@ -298,6 +298,7 @@ class DirectoryParser(BaseParser):_source=entry.url,resource_name=cf.path.name,feishu_access_token=kwargs.get("feishu_access_token"),+ feishu_config=kwargs.get("feishu_config"),)if kwargs.get("lark_file"):parse_options["lark_file"] = kwargs["lark_file"]diff --git a/openviking/parse/understanding_api.py b/openviking/parse/understanding_api.pyindex 65f482930..f35fe8a15 100644--- a/openviking/parse/understanding_api.py+++ b/openviking/parse/understanding_api.py@@ -376,7 +376,7 @@ class UnderstandingAPI(BaseParser):try:from openviking.resource.feishu_watch_auth import load_feishu_app_credentials- load_feishu_app_credentials()+ load_feishu_app_credentials(config=kwargs.get("feishu_config"))return Trueexcept (FileNotFoundError, ValueError):return False@@ -593,7 +593,9 @@ class UnderstandingAPI(BaseParser):try:from openviking.resource.feishu_watch_auth import FeishuOAuthClient- token = await FeishuOAuthClient.from_config().get_tenant_access_token()+ token = await FeishuOAuthClient.from_config(+ config=kwargs.get("feishu_config")+ ).get_tenant_access_token()except (FileNotFoundError, ValueError) as exc:raise ValueError("exactly one Feishu user or tenant access token is required for parser API imports"diff --git a/openviking/resource/feishu_watch_auth.py b/openviking/resource/feishu_watch_auth.pyindex c4a42f022..0c485c3e8 100644--- a/openviking/resource/feishu_watch_auth.py+++ b/openviking/resource/feishu_watch_auth.py@@ -6,11 +6,17 @@ from __future__ import annotationsimport asyncioimport os-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezonefrom typing import Any, Dict, Optionalimport httpx+from lark_oapi.core.cache import ICache++from openviking.parse.accessors.feishu_token import (+ resolve_feishu_tenant_token_cache,+)+from openviking_cli.utils.config.parser_config import FeishuConfigFEISHU_AUTH_PROVIDER = "feishu"FEISHU_ACCESS_TOKEN_ARG = "feishu_access_token"@@ -52,13 +58,13 @@ class FeishuTenantTokenError(Exception):def load_feishu_app_credentials(*,+ config=None,app_id: Optional[str] = None,app_secret: Optional[str] = None,) -> FeishuAppCredentials:"""Load Feishu app credentials from OpenViking config or environment."""- from openviking_cli.utils.config import get_openviking_config-- config = get_openviking_config().feishu+ if config is None:+ raise ValueError("Feishu credentials require explicit account configuration")if app_id is None and app_secret is None:resolved_app_id = (config.app_id or os.getenv("FEISHU_APP_ID", "")).strip()resolved_app_secret = (config.app_secret or os.getenv("FEISHU_APP_SECRET", "")).strip()@@ -82,6 +88,8 @@ def create_feishu_auth_state(access_token: str,refresh_token: str,app_credentials: Optional[FeishuAppCredentials] = None,+ *,+ persist_app_secret: bool = True,) -> Dict[str, Any]:"""Create the private watch auth state for Feishu user-token watch tasks."""state = {@@ -92,7 +100,8 @@ def create_feishu_auth_state(}if app_credentials is not None:state["app_id"] = app_credentials.app_id- state["app_secret"] = app_credentials.app_secret+ if persist_app_secret:+ state["app_secret"] = app_credentials.app_secretreturn state@@ -100,6 +109,22 @@ def is_feishu_auth_state(auth_state: Optional[Dict[str, Any]]) -> bool:return isinstance(auth_state, dict) and auth_state.get("provider") == FEISHU_AUTH_PROVIDER+def feishu_config_from_auth_state(+ auth_state: Dict[str, Any], current: FeishuConfig+) -> FeishuConfig:+ """Bind a watch execution to the app identity stored at creation.++ Non-identity parsing options keep their current account values. Legacy+ states without a complete app identity retain current-account fallback.+ """+ update: Dict[str, Any] = {}+ for key in ("app_id", "app_secret"):+ value = auth_state.get(key)+ if value is not None:+ update[key] = value+ return replace(current, **update)++def feishu_auth_state_needs_refresh(auth_state: Dict[str, Any],*,@@ -141,28 +166,45 @@ def apply_feishu_refreshed_token(class FeishuOAuthClient:"""Small wrapper around Feishu/Lark user and tenant token operations."""- def __init__(self, credentials: FeishuAppCredentials):+ def __init__(+ self,+ credentials: FeishuAppCredentials,+ *,+ tenant_token_cache: ICache | None = None,+ ):self._credentials = credentials+ self._tenant_token_cache = resolve_feishu_tenant_token_cache(tenant_token_cache)self._client = None@classmethod- def from_config(cls) -> "FeishuOAuthClient":- return cls(load_feishu_app_credentials())+ def from_config(+ cls,+ config,+ *,+ tenant_token_cache: ICache | None = None,+ ) -> "FeishuOAuthClient":+ return cls(+ load_feishu_app_credentials(config=config),+ tenant_token_cache=tenant_token_cache,+ )@classmethod- def from_auth_state(cls, auth_state: Dict[str, Any]) -> "FeishuOAuthClient":- app_id = auth_state.get("app_id")- app_secret = auth_state.get("app_secret")- if app_id is None and app_secret is None:- return cls.from_config()+ def from_auth_state(+ cls,+ auth_state: Dict[str, Any],+ *,+ config,+ tenant_token_cache: ICache | None = None,+ ) -> "FeishuOAuthClient":try:- credentials = load_feishu_app_credentials(app_id=app_id, app_secret=app_secret)+ bound = feishu_config_from_auth_state(auth_state, config)+ credentials = load_feishu_app_credentials(config=bound)except ValueError as exc:raise FeishuTokenRefreshError("Feishu app credentials in watch task are invalid.",permanent=True,) from exc- return cls(credentials)+ return cls(credentials, tenant_token_cache=tenant_token_cache)async def get_tenant_access_token(self) -> str:return await asyncio.to_thread(self._get_tenant_access_token_sync)@@ -183,7 +225,12 @@ class FeishuOAuthClient:config.domain = self._credentials.domainconfig.timeout = self._credentials.request_timeouttry:- token = TokenManager.get_self_tenant_token(config)+ with self._tenant_token_cache.sdk_scope(+ app_id=self._credentials.app_id,+ app_secret=self._credentials.app_secret,+ domain=self._credentials.domain,+ ):+ token = TokenManager.get_self_tenant_token(config)except Exception as exc:raise FeishuTenantTokenError("Failed to obtain Feishu tenant token.") from excif not isinstance(token, str) or not token.strip():@@ -232,16 +279,17 @@ class FeishuOAuthClient:code = payload.get("code")if response.status_code >= 400 or payload.get("error") or code not in (None, 0):+ error = payload.get("error")msg = str(payload.get("error_description")or payload.get("msg")or payload.get("message")- or payload.get("error")+ or erroror f"HTTP {response.status_code}")raise FeishuTokenRefreshError(f"Feishu user token refresh failed: code={code}, msg={msg}",- permanent=_is_permanent_refresh_error(code, msg),+ permanent=_is_permanent_refresh_error(code, f"{error or ''} {msg}"),)access_token = payload.get("access_token")diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pyindex 7c1d941c7..6e24ac095 100644--- a/openviking/resource/watch_scheduler.py+++ b/openviking/resource/watch_scheduler.py@@ -55,6 +55,7 @@ class WatchScheduler:max_concurrency: int = 4,task_timeout: float = DEFAULT_TASK_TIMEOUT,uri_mutation_coordinator: Optional[UriMutationCoordinator] = None,+ runtime_config_manager: Optional[Any] = None,):"""Initialize WatchScheduler.@@ -66,6 +67,7 @@ class WatchScheduler:self._resource_service = resource_serviceself._viking_fs = viking_fsself._uri_mutation_coordinator = uri_mutation_coordinator or UriMutationCoordinator()+ self._runtime_config_manager = runtime_config_managerif check_interval <= 0:raise ValueError("check_interval must be > 0")if max_concurrency <= 0:@@ -584,9 +586,17 @@ class WatchScheduler:return auth_staterefresh_token = auth_state.get("refresh_token")- refreshed = await FeishuOAuthClient.from_auth_state(auth_state).refresh_user_access_token(- refresh_token+ if self._runtime_config_manager is None:+ raise RuntimeError("Runtime config manager is not initialized")+ from openviking.config.feishu import get_effective_feishu_config++ config = await get_effective_feishu_config(+ self._runtime_config_manager,+ task.account_id,)+ refreshed = await FeishuOAuthClient.from_auth_state(+ auth_state, config=config+ ).refresh_user_access_token(refresh_token)updated = apply_feishu_refreshed_token(auth_state, refreshed)if self._watch_manager is not None:await self._watch_manager.update_auth_state(task.task_id, updated)diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 14cc402c9..eba57f31f 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -478,6 +478,7 @@ class OpenVikingService:resource_service=self._resource_service,viking_fs=self._viking_fs,uri_mutation_coordinator=self._uri_mutation_coordinator,+ runtime_config_manager=self._runtime_config_manager,)# Wire up sub-services@@ -501,6 +502,7 @@ class OpenVikingService:skill_processor=self._skill_processor,watch_scheduler=self._watch_scheduler,resource_memory_link_service=self._resource_memory_link_service,+ runtime_config_manager=self._runtime_config_manager,)self._session_service.set_dependencies(vikingdb=self._vikingdb_manager,diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex d2c20d64f..5ceba7756 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -205,6 +205,7 @@ class ResourceService:skill_processor: Optional[SkillProcessor] = None,watch_scheduler: Optional["WatchScheduler"] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,+ runtime_config_manager: Optional[Any] = None,):self._vikingdb = vikingdbself._viking_fs = viking_fs@@ -212,6 +213,7 @@ class ResourceService:self._skill_processor = skill_processorself._watch_scheduler = watch_schedulerself._resource_memory_link_service = resource_memory_link_service+ self._runtime_config_manager = runtime_config_managerself._background_tasks: set[asyncio.Task[Any]] = set()self._connector_delegate: Optional["ConnectorDelegate"] = None@@ -223,6 +225,7 @@ class ResourceService:skill_processor: SkillProcessor,watch_scheduler: Optional["WatchScheduler"] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,+ runtime_config_manager: Optional[Any] = None,) -> None:"""Set dependencies (for deferred initialization)."""self._vikingdb = vikingdb@@ -231,6 +234,7 @@ class ResourceService:self._skill_processor = skill_processorself._watch_scheduler = watch_schedulerself._resource_memory_link_service = resource_memory_link_service+ self._runtime_config_manager = runtime_config_managerdef _get_watch_manager(self) -> Optional["WatchManager"]:if not self._watch_scheduler:@@ -311,7 +315,7 @@ class ResourceService:tags: Optional[List[str]],tag_mode: str,) -> Dict[str, Any]:- watch_kwargs = dict(processor_kwargs)+ watch_kwargs = self._sanitize_watch_processor_kwargs(processor_kwargs)if tags is not None:watch_kwargs["tags"] = tagswatch_kwargs["tag_mode"] = tag_mode@@ -444,11 +448,12 @@ class ResourceService:except Exception as e:logger.warning(f"[ResourceService] Failed to cancel watch task for {to}: {e}")- def _normalize_add_resource_args(+ async def _normalize_add_resource_args(self,args: Optional[Dict[str, Any]],*,watch_interval: float,+ ctx: RequestContext,allowed_reserved_fields: Optional[set[str]] = None,) -> _NormalizedAddResourceArgs:if args is None:@@ -488,11 +493,20 @@ class ResourceService:"args.feishu_refresh_token must be a non-empty string when ""args.feishu_access_token is used with watch_interval > 0.")- app_credentials = self._load_feishu_credentials_for_watch(app_id, app_secret)+ if self._runtime_config_manager is None:+ raise RuntimeError("Runtime config manager is not initialized")+ from openviking.config.feishu import get_effective_feishu_config++ feishu_config = await get_effective_feishu_config(+ self._runtime_config_manager,+ ctx.account_id,+ )+ app_credentials = self._load_feishu_credentials_for_watch(app_id, app_secret, feishu_config)watch_auth_state = create_feishu_auth_state(token,refresh_token.strip(),app_credentials,+ persist_app_secret=app_id is not None or app_secret is not None,)elif refresh_token is not None:raise InvalidArgumentError(@@ -520,7 +534,8 @@ class ResourceService:self,app_id: Any,app_secret: Any,- ) -> Optional[FeishuAppCredentials]:+ config,+ ) -> FeishuAppCredentials:supplied = app_id is not None or app_secret is not Noneif supplied and (not isinstance(app_id, str)@@ -534,6 +549,7 @@ class ResourceService:)try:credentials = load_feishu_app_credentials(+ config=config,app_id=app_id.strip() if supplied else None,app_secret=app_secret.strip() if supplied else None,)@@ -542,7 +558,11 @@ class ResourceService:"Feishu user-token watch requires FEISHU_APP_ID and ""FEISHU_APP_SECRET, or feishu.app_id and feishu.app_secret in ov.conf.") from exc- return credentials if supplied else None+ # A user refresh token is bound to the Feishu application that issued+ # it. Persist the effective app identity even when the caller used the+ # account default, so a later account-config change cannot pair an old+ # refresh token with a different app.+ return credentialsdef _ensure_initialized(self) -> None:"""Ensure all dependencies are initialized."""@@ -728,8 +748,9 @@ class ResourceService:internal_kwargs: Dict[str, Any] = {"parser_backend": parser_backend}if "resolved_extension" in queued_args:internal_kwargs["resolved_extension"] = queued_args.pop("resolved_extension")- normalized_args = self._normalize_add_resource_args(+ normalized_args = await self._normalize_add_resource_args(queued_args,+ ctx=ctx,watch_interval=msg.watch_interval,)internal_kwargs.update(normalized_args.processor_kwargs)@@ -880,21 +901,24 @@ class ResourceService:"""Restore provider-specific request inputs from task-owned auth state."""if not task_auth:return {}, None+ creating_watch = msg.watch_interval > 0 and not msg.skip_watch_managementif is_git_http_auth_state(task_auth):auth_config = git_http_auth_config_from_state(task_auth, msg.path)- watch_auth_state = dict(task_auth) if msg.watch_interval > 0 else None+ watch_auth_state = dict(task_auth) if creating_watch else Nonereturn {"auth_config": auth_config}, watch_auth_stateif is_feishu_auth_state(task_auth):token = task_auth.get("access_token")if not isinstance(token, str) or not token.strip():raise InvalidArgumentError("Stored Feishu task credentials are invalid.")- if msg.watch_interval > 0:+ if creating_watch:refresh_token = task_auth.get("refresh_token")if not isinstance(refresh_token, str) or not refresh_token.strip():raise InvalidArgumentError("Stored Feishu watch credentials are missing a refresh token.")watch_auth_state = dict(task_auth)+ watch_auth_state.pop("domain", None)+ watch_auth_state.pop("request_timeout", None)else:watch_auth_state = Noneauth_kwargs = (@@ -1023,9 +1047,22 @@ class ResourceService:"access_token": token.strip(),})+ task_auth.pop("domain", None)+ task_auth.pop("request_timeout", None)+ if self._runtime_config_manager is None:+ raise RuntimeError("Runtime config manager is not initialized")+ from openviking.config.feishu import get_effective_feishu_config++ feishu_config = await get_effective_feishu_config(+ self._runtime_config_manager,+ ctx.account_id,+ )+ feishu_kwargs = dict(processor_kwargs)+ feishu_kwargs["feishu_config"] = feishu_configpreflight = await FeishuAccessor().preflight_source(path,feishu_access_token=token.strip() if isinstance(token, str) else None,+ feishu_config=feishu_config,**({"feishu_recursive": True} if recursive else {}),)source_name = source_name or preflight.source_name@@ -1039,13 +1076,13 @@ class ResourceService:mode is ParseMode.DEFAULTand self._resource_processor.should_use_understanding_directly(path,- **processor_kwargs,+ **feishu_kwargs,))if direct_understanding:understanding_response_id = await self._resource_processor.submit_understanding(path,- **processor_kwargs,+ **feishu_kwargs,)if watch_auth_state is None:task_auth = {}@@ -1658,8 +1695,9 @@ class ResourceService:allowed_reserved_fields = ConnectorDelegate.supported_args(path, add_type).intersection(_ADD_RESOURCE_ARGS_RESERVED_FIELDS)- normalized_args = self._normalize_add_resource_args(+ normalized_args = await self._normalize_add_resource_args(args,+ ctx=ctx,watch_interval=watch_interval,allowed_reserved_fields=allowed_reserved_fields,)diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.pyindex aa811c8eb..d3df8e8d1 100644--- a/openviking/utils/resource_processor.py+++ b/openviking/utils/resource_processor.py@@ -129,7 +129,20 @@ class ResourceProcessor:ctx: RequestContext,kwargs: dict[str, Any],) -> dict[str, Any]:- """Add account-scoped source credentials without persisting them."""+ """Add account-scoped source configuration without persisting it."""+ from openviking.parse.accessors.feishu_accessor import FeishuAccessor++ if FeishuAccessor._is_feishu_url(source):+ return await self._feishu_source_config_kwargs(ctx, kwargs)+ return await self._github_source_config_kwargs(source, ctx, kwargs)++ async def _github_source_config_kwargs(+ self,+ source: str,+ ctx: RequestContext,+ kwargs: dict[str, Any],+ ) -> dict[str, Any]:+ """Add the account-scoped GitHub token for one request."""github_token = await self.github_token_for(source, ctx)if not github_token:return kwargs@@ -137,6 +150,24 @@ class ResourceProcessor:result["github_token"] = github_tokenreturn result+ async def _feishu_source_config_kwargs(+ self,+ ctx: RequestContext,+ kwargs: dict[str, Any],+ ) -> dict[str, Any]:+ """Add the account-scoped Feishu config for one request."""+ if self.runtime_config_manager is None:+ raise RuntimeError("Runtime config manager is not initialized")+ from openviking.config.feishu import get_effective_feishu_config++ feishu_config = await get_effective_feishu_config(+ self.runtime_config_manager,+ ctx.account_id,+ )+ result = dict(kwargs)+ result["feishu_config"] = feishu_config+ return result+def _get_summarizer(self) -> "Summarizer":"""Lazy initialization of Summarizer."""if self._summarizer is None:diff --git a/openviking_cli/utils/config/agent_evolution_config.py b/openviking_cli/utils/config/agent_evolution_config.pyindex 96f1c720c..461412dc1 100644--- a/openviking_cli/utils/config/agent_evolution_config.py+++ b/openviking_cli/utils/config/agent_evolution_config.py@@ -4,8 +4,10 @@from pydantic import BaseModel+from .runtime_field import RuntimeField+class AgentEvolutionConfig(BaseModel):"""Agent Evolution switch shared by cluster and account configuration."""- enabled: bool = False+ enabled: bool = RuntimeField(default=False)diff --git a/openviking_cli/utils/config/github_config.py b/openviking_cli/utils/config/github_config.pyindex ed3534baf..bbdca192e 100644--- a/openviking_cli/utils/config/github_config.py+++ b/openviking_cli/utils/config/github_config.py@@ -4,8 +4,10 @@from pydantic import BaseModel+from .runtime_field import RuntimeField+class GitHubConfig(BaseModel):"""Configuration for GitHub access."""- token: str = ""+ token: str = RuntimeField(default="")diff --git a/openviking_cli/utils/config/parser_config.py b/openviking_cli/utils/config/parser_config.pyindex a7cd64d4c..26cfcd99c 100644--- a/openviking_cli/utils/config/parser_config.py+++ b/openviking_cli/utils/config/parser_config.py@@ -554,6 +554,9 @@ class FeishuConfig(ParserConfig):30.0 # TODO: not yet passed to lark-oapi client, reserved for future use)+ def __post_init__(self) -> None:+ self.validate()+def validate(self) -> None:"""Validate configuration.@@ -563,16 +566,29 @@ class FeishuConfig(ParserConfig):"""super().validate()- if not self.domain:+ if not isinstance(self.domain, str) or not self.domain.strip():raise ValueError("domain cannot be empty")+ self.domain = self.domain.strip()- if self.max_rows_per_sheet <= 0:+ if (+ isinstance(self.max_rows_per_sheet, bool)+ or not isinstance(self.max_rows_per_sheet, int)+ or self.max_rows_per_sheet <= 0+ ):raise ValueError("max_rows_per_sheet must be positive")- if self.max_records_per_table <= 0:+ if (+ isinstance(self.max_records_per_table, bool)+ or not isinstance(self.max_records_per_table, int)+ or self.max_records_per_table <= 0+ ):raise ValueError("max_records_per_table must be positive")- if self.request_timeout <= 0:+ if (+ isinstance(self.request_timeout, bool)+ or not isinstance(self.request_timeout, (int, float))+ or self.request_timeout <= 0+ ):raise ValueError("request_timeout must be positive")diff --git a/openviking_cli/utils/config/runtime_field.py b/openviking_cli/utils/config/runtime_field.pyindex c62507078..85e089343 100644--- a/openviking_cli/utils/config/runtime_field.py+++ b/openviking_cli/utils/config/runtime_field.py@@ -2,10 +2,11 @@# SPDX-License-Identifier: AGPL-3.0"""Declarative marker for config fields the runtime config API may touch.-A plain top-level Pydantic ``Field`` is not on the config API surface: PATCH-requests targeting it are rejected. Declaring :func:`RuntimeField` opts it in-and records two orthogonal attributes so generic code can decide what the API-may do with it without any per-field branching:+A plain Pydantic ``Field`` is not on the config API surface: PATCH requests+targeting it are rejected. Every component of a writable nested path must use+:func:`RuntimeField`; marking a section does not grant access to its ordinary+``Field`` descendants. ``RuntimeField`` records two orthogonal attributes so+generic code can decide what the API may do without per-field branching:- ``dynamic`` — the field's writable lifecycle, a single boolean covering allmutability. ``True`` (default): writable both at creation and by later PATCH.@@ -144,10 +145,9 @@ def collect_runtime_field_paths(model: type[BaseModel]) -> set[tuple[str, ...]]:"""Collect dotted field paths that are on ``model``'s config surface.Collect explicitly marked paths, including their marked parent sections,- regardless of ``dynamic``. A section with no marked descendants is treated- by the validator as one configurable object; its ordinary model fields are- accepted inside that object. Objects still merge recursively during PATCH.- Sections with marked descendants restrict input to those declared paths.+ regardless of ``dynamic``. Every component of a writable nested path must+ be marked: a ``RuntimeField`` section does not implicitly make ordinary+ ``Field`` descendants writable.Whether a non-creating PATCH may write a path is further gated by``dynamic`` (see :func:`collect_frozen_paths`). Cluster-vs-account scope isdiff --git a/tests/config/test_runtime_config.py b/tests/config/test_runtime_config.pyindex afe0a1937..8108fa1b7 100644--- a/tests/config/test_runtime_config.py+++ b/tests/config/test_runtime_config.py@@ -57,7 +57,7 @@ class MemorySection(BaseModel):class SwitchSection(BaseModel):- enabled: bool+ enabled: bool = RuntimeField()model_config = {"extra": "forbid"}@@ -116,6 +116,30 @@ def _make_manager(source) -> tuple[RuntimeConfigManager, dict]:# -- RuntimeField / path collection -------------------------------------------+def test_account_selector_captures_fallback_pair_and_rejects_async():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ await manager.initialize()+ await manager.patch_cluster({"vlm": {"model": "cluster"}})+ await manager.patch_account("a", {"memory": {"extraction_enabled": False}})+ selected = await manager.resolve_account(+ "a", lambda view: (view.get("vlm"), view.get("memory"), view.get("switch"))+ )+ await manager.patch_cluster({"vlm": {"model": "new"}})+ assert selected[0].model == "cluster"+ assert selected[1].extraction_enabled is False+ assert selected[2] is None+ assert (await manager.get_account("a", "vlm")).model == "new"++ async def invalid(view):+ return view.get("vlm")++ with pytest.raises(TypeError, match="synchronous"):+ await manager.resolve_account("a", invalid)++ asyncio.run(run())++def test_runtime_field_paths_scope_by_model():all_paths = collect_runtime_field_paths(ClusterConfig)assert ("vlm", "model") in all_paths@@ -135,10 +159,12 @@ def test_real_openviking_config_exposes_no_mutable_path():# Agent Evolution is the current cluster runtime surface. Other existing# cluster fields remain startup-only and use plain Field.surface = collect_runtime_field_paths(OpenVikingConfig)- assert surface == {("agent_evolution",)}+ assert ("agent_evolution",) in surface+ assert not any(p[0] == "feishu" for p in surface)assert ("vlm",) not in surfaceassert not any(p[0] == "rerank" for p in surface)assert is_dynamic(OpenVikingConfig.model_fields["agent_evolution"])+ assert not is_runtime_field(OpenVikingConfig.model_fields["feishu"])assert not is_runtime_field(OpenVikingConfig.model_fields["memory"])assert not is_runtime_field(OpenVikingConfig.model_fields["vlm"])assert not is_runtime_field(OpenVikingConfig.model_fields["rerank"])@@ -206,7 +232,10 @@ def test_collect_frozen_paths_includes_nested_create_only_fields():assert collect_frozen_paths(NestedFrozenRoot) == {("child", "frozen")}with pytest.raises(ConfigPatchError, match="child.frozen"):validate_patch(NestedFrozenRoot, {"child": {"frozen": "changed"}})+ with pytest.raises(ConfigPatchError, match="child.frozen"):+ validate_patch(NestedFrozenRoot, {"child": None})validate_patch(NestedFrozenRoot, {"child": {"frozen": "initial"}}, creating=True)+ validate_patch(NestedFrozenRoot, {"child": None}, creating=True)# -- PATCH request validation -------------------------------------------------@@ -216,6 +245,12 @@ def test_validate_patch_accepts_mutable_paths_and_none_delete():validate_patch(ClusterConfig, {"vlm": {"model": "m"}})validate_patch(ClusterConfig, {"vlm": {"model": None}})validate_patch(ClusterConfig, {"memory": {"extraction_enabled": False}})+ validate_patch(ClusterConfig, {"memory": None})+++def test_validate_patch_rejects_section_delete_with_locked_descendant():+ with pytest.raises(ConfigPatchError, match="vlm.temperature"):+ validate_patch(ClusterConfig, {"vlm": None})def test_validate_patch_rejects_locked_field_and_section():@@ -309,12 +344,12 @@ def test_cluster_patch_reset_rebuilds_from_startup_baseline():source = MemoryConfigSource()manager, holder = _make_manager(source)- await manager.patch_cluster({"vlm": {"model": "temporary"}})- assert holder["config"].vlm.model == "temporary"+ await manager.patch_cluster({"memory": {"extraction_enabled": False}})+ assert not holder["config"].memory.extraction_enabled- await manager.patch_cluster({"vlm": None})+ await manager.patch_cluster({"memory": None})assert await source.load(ConfigScope.cluster()) == {}- assert holder["config"].vlm.model is None+ assert holder["config"].memory.extraction_enabledasyncio.run(run())@@ -627,7 +662,24 @@ def test_refresh_does_not_resurrect_evicted_account():def test_account_config_field_attributes():fields = AccountConfig.model_fields- assert set(fields) == {"acl", "agent_evolution", "github"}+ assert set(fields) == {"acl", "agent_evolution", "feishu", "github"}+ assert collect_runtime_field_paths(AccountConfig) == {+ ("acl",),+ ("acl", "enabled"),+ ("agent_evolution",),+ ("agent_evolution", "enabled"),+ ("feishu",),+ ("feishu", "app_id"),+ ("feishu", "app_secret"),+ ("feishu", "download_images"),+ ("feishu", "max_records_per_table"),+ ("feishu", "max_rows_per_sheet"),+ ("feishu", "request_timeout"),+ ("github",),+ ("github", "token"),+ }+ assert is_dynamic(fields["feishu"])+ assert fallback_of(fields["feishu"]) is Noneassert is_dynamic(fields["github"])assert fallback_of(fields["github"]) is Noneassert is_dynamic(fields["agent_evolution"])@@ -668,14 +720,42 @@ def test_account_config_ignores_inactive_sections_during_known_patch():def test_account_patch_rejects_inactive_fields_and_allows_active_fields():validate_patch(AccountConfig, {"github": {"token": "t"}})+ validate_patch(AccountConfig, {"github": None})+ validate_patch(AccountConfig, {"agent_evolution": None})+ validate_patch(AccountConfig, {"acl": None})with pytest.raises(ConfigPatchError, match="github.tokne"):validate_patch(AccountConfig, {"github": {"tokne": "t"}})+ validate_patch(AccountConfig, {"feishu": {"app_id": "app"}})+ with pytest.raises(ConfigPatchError, match="app_secert"):+ validate_patch(AccountConfig, {"feishu": {"app_secert": "app"}})+ with pytest.raises(ConfigPatchError, match="domain"):+ validate_patch(AccountConfig, {"feishu": {"domain": "https://custom.example"}})+ validate_patch(AccountConfig, {"feishu": {"request_timeout": 60}})+ validate_patch(AccountConfig, {"feishu": None})with pytest.raises(ConfigPatchError):validate_patch(AccountConfig, {"vlm": {"model": "m"}})with pytest.raises(ConfigPatchError):validate_patch(AccountConfig, {"embedding": {"dense": {"model": "m"}}}, creating=True)+def test_feishu_cluster_patch_rejects_unknown_fields():+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfig++ with pytest.raises(ConfigPatchError, match="feishu"):+ validate_patch(OpenVikingConfig, {"feishu": {"app_secert": "app"}})+ with pytest.raises(ConfigPatchError, match="feishu"):+ validate_patch(OpenVikingConfig, {"feishu": {"domain": "https://custom.example"}})+++def test_feishu_config_validates_constructor_values():+ from openviking_cli.utils.config.parser_config import FeishuConfig++ with pytest.raises(ValueError, match="request_timeout"):+ FeishuConfig(request_timeout=0)+ with pytest.raises(ValueError, match="domain"):+ FeishuConfig(domain=" ")++def test_manager_resolves_account_override_fallback_and_no_fallback():async def run():manager, holder = _make_manager(MemoryConfigSource())@@ -809,6 +889,96 @@ def test_real_agent_evolution_precedence_and_fallback():asyncio.run(run())+def test_real_feishu_account_override_and_cluster_fallback():+ async def run():+ from openviking.config.binding import manager_over_source+ from openviking.config.feishu import get_effective_feishu_config+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ base = OpenVikingConfig.from_dict(+ {"feishu": {"app_id": "cluster-v1", "app_secret": "cluster-secret"}}+ )+ set_openviking_config(base)+ manager = manager_over_source(MemoryConfigSource(), base_config=base)+ await manager.initialize()+ try:+ assert (+ await get_effective_feishu_config(manager, "ov-a")+ ).app_id == "cluster-v1"++ await manager.patch_account(+ "ov-a", {"feishu": {"app_id": "account-a", "app_secret": "a-secret"}}+ )+ effective_a = await get_effective_feishu_config(manager, "ov-a")+ assert effective_a.app_id == "account-a"+ assert effective_a.domain == base.feishu.domain+ assert (+ await get_effective_feishu_config(manager, "ov-b")+ ).app_id == "cluster-v1"++ await manager.patch_account("ov-a", {"feishu": None})+ assert (+ await get_effective_feishu_config(manager, "ov-a")+ ).app_id == "cluster-v1"+ finally:+ OpenVikingConfigSingleton.reset_instance()++ asyncio.run(run())+++def test_real_feishu_account_section_only_inherits_cluster_domain():+ async def run():+ from openviking.config.binding import manager_over_source+ from openviking.config.feishu import get_effective_feishu_config+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )+ from openviking_cli.utils.config.parser_config import FeishuConfig++ base = OpenVikingConfig.from_dict(+ {+ "feishu": {+ "app_id": "cluster-app",+ "app_secret": "cluster-secret",+ "domain": "https://open.larksuite.com",+ "max_rows_per_sheet": 17,+ "max_records_per_table": 23,+ "download_images": False,+ "request_timeout": 45,+ }+ }+ )+ set_openviking_config(base)+ manager = manager_over_source(MemoryConfigSource(), base_config=base)+ await manager.initialize()+ try:+ await manager.patch_account(+ "ov-a",+ {"feishu": {"app_id": "account-app", "app_secret": "account-secret"}},+ )++ effective = await get_effective_feishu_config(manager, "ov-a")++ defaults = FeishuConfig()+ assert effective.app_id == "account-app"+ assert effective.app_secret == "account-secret"+ assert effective.domain == "https://open.larksuite.com"+ assert effective.max_rows_per_sheet == defaults.max_rows_per_sheet+ assert effective.max_records_per_table == defaults.max_records_per_table+ assert effective.download_images is defaults.download_images+ assert effective.request_timeout == defaults.request_timeout+ finally:+ OpenVikingConfigSingleton.reset_instance()++ asyncio.run(run())++# -- FileConfigSource plaintext read / magic write ----------------------------diff --git a/tests/parse/test_directory_understanding_routing.py b/tests/parse/test_directory_understanding_routing.pyindex c4230754c..754923464 100644--- a/tests/parse/test_directory_understanding_routing.py+++ b/tests/parse/test_directory_understanding_routing.py@@ -59,7 +59,7 @@ def _configure_understanding(max_depth: int = 10,upload_simple_max_bytes: int = 512 * 1024 * 1024,enable_resumable_upload: bool = False,-) -> None:+) -> SimpleNamespace:config = SimpleNamespace(parser_api=SimpleNamespace(enable=enabled,@@ -84,6 +84,7 @@ def _configure_understanding("openviking_cli.utils.config.open_viking_config.get_openviking_config",lambda: config,)+ return configdef _fake_understanding_parse(calls: list[Path]):@@ -180,6 +181,14 @@ async def test_html_url_routes_materialized_pages(monkeypatch, tmp_path: Path, url, depth, enabled, extensions, expected_parser):_configure_understanding(monkeypatch, extensions, enabled=enabled)+ monkeypatch.setattr(+ "openviking.parse.accessors.git_accessor.is_git_repo_url",+ MagicMock(return_value=False),+ )+ monkeypatch.setattr(+ "openviking.parse.accessors.http_accessor.is_code_hosting_blob_url",+ MagicMock(return_value=False),+ )pages = [CrawledPage(url=url, html="<html><h1>Home</h1><p>Home content</p></html>")]if depth:pages.append(diff --git a/tests/parse/test_feishu_accessor.py b/tests/parse/test_feishu_accessor.pyindex a1c6553da..ab9f05606 100644--- a/tests/parse/test_feishu_accessor.py+++ b/tests/parse/test_feishu_accessor.py@@ -5,6 +5,7 @@import asyncioimport jsonimport sys+from contextlib import nullcontextfrom pathlib import Pathfrom types import ModuleType, SimpleNamespacefrom unittest.mock import MagicMock@@ -16,7 +17,9 @@ from openviking.parse.accessors.feishu_accessor import (FeishuAccessor,_FeishuWikiTreeNode,)+from openviking.parse.accessors.feishu_session import FeishuApiSessionfrom openviking_cli.exceptions import OpenVikingError+from openviking_cli.utils.config.parser_config import FeishuConfigclass _SuccessResponse:@@ -30,9 +33,21 @@ class _SuccessResponse:return True+def test_generated_doc_url_uses_account_feishu_domain():+ accessor = FeishuAccessor()._new_operation(+ "https://example.larksuite.com/docx/token",+ config=FeishuConfig(domain="https://open.larksuite.com"),+ )++ assert accessor._build_feishu_doc_url("doc", "token") == (+ "https://open.larksuite.com/docs/token"+ )++class _FakeRequestOption:def __init__(self):self.user_access_token = None+ self.tenant_access_token = None@staticmethoddef builder():@@ -47,10 +62,64 @@ class _FakeRequestOptionBuilder:self._option.user_access_token = tokenreturn self+ def tenant_access_token(self, token):+ self._option.tenant_access_token = token+ return self+def build(self):return self._option+class _FakeClientBuilder:+ def __init__(self):+ self.domain_value = None+ self.timeout_value = None+ self.app_id_value = None+ self.app_secret_value = None+ self.enable_set_token_value = False+ self.cache_value = None++ def domain(self, value):+ self.domain_value = value+ return self++ def timeout(self, value):+ self.timeout_value = value+ return self++ def app_id(self, value):+ self.app_id_value = value+ return self++ def app_secret(self, value):+ self.app_secret_value = value+ return self++ def enable_set_token(self, value):+ self.enable_set_token_value = value+ return self++ def cache(self, value):+ self.cache_value = value+ return self++ def build(self):+ return SimpleNamespace(+ domain=self.domain_value,+ timeout=self.timeout_value,+ app_id=self.app_id_value,+ app_secret=self.app_secret_value,+ enable_set_token=self.enable_set_token_value,+ cache=self.cache_value,+ )+++class _FakeClient:+ @staticmethod+ def builder():+ return _FakeClientBuilder()++class _FakeBaseResponse:def __init__(self):self.code = None@@ -179,6 +248,7 @@ def _install_fake_lark_modules(monkeypatch):_FakeTransport.calls = []lark = ModuleType("lark_oapi")lark.BaseRequest = _FakeBaseRequest+ lark.Client = _FakeClientlark.HttpMethod = SimpleNamespace(GET="GET")lark.AccessTokenType = SimpleNamespace(TENANT="tenant", USER="user")docx_v1 = ModuleType("lark_oapi.api.docx.v1")@@ -205,6 +275,136 @@ def _install_fake_lark_modules(monkeypatch):monkeypatch.setitem(sys.modules, "lark_oapi.core.token", core_token)+def _use_fake_client(monkeypatch, accessor: FeishuAccessor, client):+ monkeypatch.setattr(accessor, "_get_client", lambda **_kwargs: client)+ accessor._session = SimpleNamespace(+ tenant_token_cache_scope=lambda: nullcontext(),+ )+ monkeypatch.setattr(+ FeishuApiSession,+ "tenant_token_cache_scope",+ lambda _self: nullcontext(),+ )+ monkeypatch.setattr(+ accessor,+ "_user_request_option",+ lambda token: _FakeRequestOption.builder().user_access_token(token).build()+ if token+ else None,+ )+++def _feishu_config(**kwargs) -> FeishuConfig:+ return FeishuConfig(**kwargs)+++def _operation(+ accessor: FeishuAccessor,+ *,+ config: FeishuConfig | None = None,+) -> FeishuAccessor:+ return accessor._new_operation(+ "https://example.feishu.cn/docx/doc",+ config=config,+ )+++def test_user_token_client_uses_configured_domain_without_app_credentials(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ accessor = _operation(+ FeishuAccessor(),+ config=_feishu_config(domain="https://open.larksuite.com"),+ )++ client = accessor._get_client(use_user_token=True)++ assert client.domain == "https://open.larksuite.com"+ assert client.app_id is None+ assert client.app_secret is None+ assert client.enable_set_token is True+++def test_tenant_token_client_requires_credentials(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ monkeypatch.delenv("FEISHU_APP_ID", raising=False)+ monkeypatch.delenv("FEISHU_APP_SECRET", raising=False)+ accessor = _operation(FeishuAccessor())++ with pytest.raises(ValueError, match="credentials not configured"):+ accessor._get_client()+++def test_tenant_token_client_uses_environment_credentials(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ monkeypatch.setenv("FEISHU_APP_ID", "env-app")+ monkeypatch.setenv("FEISHU_APP_SECRET", "env-secret")+ accessor = _operation(FeishuAccessor())++ client = accessor._get_client()++ assert client.app_id == "env-app"+ assert client.app_secret == "env-secret"+++def test_tenant_clients_install_account_scoped_sdk_cache(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ accessor = _operation(+ FeishuAccessor(),+ config=_feishu_config(app_id="account-app", app_secret="account-secret"),+ )+ client = accessor._get_client(use_user_token=False)++ assert client.cache is not None+ assert client.enable_set_token is False+++def test_shared_accessor_keeps_concurrent_operation_contexts_isolated(monkeypatch):+ accessor = FeishuAccessor()++ async def return_domain(worker, _source, **_kwargs):+ await asyncio.sleep(0)+ return worker._get_config().domain++ monkeypatch.setattr(FeishuAccessor, "_access", return_domain)++ async def run_concurrently():+ return await asyncio.gather(+ accessor.access(+ "https://one.feishu.cn/docx/one",+ feishu_config=_feishu_config(domain="https://open.one.example"),+ ),+ accessor.access(+ "https://two.feishu.cn/docx/two",+ feishu_config=_feishu_config(domain="https://open.two.example"),+ ),+ )++ assert asyncio.run(run_concurrently()) == [+ "https://open.one.example",+ "https://open.two.example",+ ]+ assert accessor._session is None+++def test_client_cache_is_scoped_to_one_operation(monkeypatch):+ _install_fake_lark_modules(monkeypatch)+ first = _operation(+ FeishuAccessor(),+ config=_feishu_config(app_id="first", app_secret="secret"),+ )+ second = _operation(+ FeishuAccessor(),+ config=_feishu_config(app_id="second", app_secret="secret"),+ )++ first_client = first._get_client()++ assert first._get_client() is first_client+ assert second._get_client() is not first_client+ assert first_client.app_id == "first"+ assert second._get_client().app_id == "second"++def test_feishu_api_lists_paginated_content_with_user_token(monkeypatch):_install_fake_lark_modules(monkeypatch)list_blocks = MagicMock(@@ -231,10 +431,10 @@ def test_feishu_api_lists_paginated_content_with_user_token(monkeypatch):])accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(docx=SimpleNamespace(v1=SimpleNamespace(document_block=SimpleNamespace(list=list_blocks))),request=list_drive,- )+ ))blocks = accessor._fetch_all_blocks("doc_token", feishu_access_token="u-test")children = accessor._list_drive_folder_children(@@ -288,7 +488,7 @@ def test_feishu_api_lists_paginated_wiki_children_with_user_token(monkeypatch):])accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(request=list_wiki_children)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=list_wiki_children))children = accessor._list_wiki_node_children("space",@@ -310,8 +510,10 @@ def test_feishu_api_lists_paginated_wiki_children_with_user_token(monkeypatch):def test_resolve_image_refs_respects_download_images_disabled():- accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=False)+ accessor = _operation(+ FeishuAccessor(),+ config=_feishu_config(download_images=False),+ )markdown = ""updated, images = accessor._resolve_image_refs(markdown)@@ -324,11 +526,11 @@ def test_resolve_image_refs_downloads_media_and_rewrites_markdown(monkeypatch):_install_fake_lark_modules(monkeypatch)request_media = MagicMock(return_value=_FakeMediaResponse(b"\x89PNG\r\n"))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))updated, images = accessor._resolve_image_refs(- "before  after"+ "before  after",)assert updated == "before  after"@@ -347,8 +549,8 @@ def test_resolve_image_refs_uses_content_type_extension(monkeypatch):))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))updated, images = accessor._resolve_image_refs("")@@ -362,8 +564,8 @@ def test_resolve_image_refs_falls_back_to_byte_magic_extension(monkeypatch):webp_bytes = b"RIFF\x00\x00\x00\x00WEBPfake"request_media = MagicMock(return_value=_FakeMediaResponse(webp_bytes, headers={}))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))updated, images = accessor._resolve_image_refs("")@@ -380,8 +582,8 @@ def test_resolve_image_refs_tries_distinct_permission_contexts(monkeypatch):])accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))updated, images = accessor._resolve_image_refs("",@@ -414,9 +616,8 @@ def test_resolve_image_refs_falls_back_to_token_only(])accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)- accessor._user_token_client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))updated, images = accessor._resolve_image_refs("",@@ -447,8 +648,8 @@ def test_resolve_image_refs_bounds_permission_context_attempts(monkeypatch):return_value=_FakeMediaResponse(success=False, code=400, status_code=400))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))+ accessor = _operation(accessor, config=_feishu_config(download_images=True))contexts = [f"context-{index}" for index in range(_MAX_MEDIA_DOWNLOAD_CONTEXTS + 2)]updated, images = accessor._resolve_image_refs(@@ -469,8 +670,7 @@ def test_download_image_uses_tenant_token_without_user_token(monkeypatch):_install_fake_lark_modules(monkeypatch)request_media = MagicMock(return_value=_FakeMediaResponse(b"\x89PNG\r\n"))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))accessor._download_image("img_token_123")@@ -484,10 +684,12 @@ def test_download_image_advertises_user_token_when_provided(monkeypatch):_install_fake_lark_modules(monkeypatch)request_media = MagicMock(return_value=_FakeMediaResponse(b"\x89PNG\r\n"))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)- accessor._user_token_client = SimpleNamespace(request=request_media)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request_media))- accessor._download_image("img_token_123", feishu_access_token="u-test")+ accessor._download_image(+ "img_token_123",+ feishu_access_token="u-test",+ )args = request_media.call_args.argsrequest = args[0]@@ -504,7 +706,7 @@ def test_access_downloads_drive_file_with_user_token(monkeypatch):headers={"content-type": "application/pdf"},)accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(_config=SimpleNamespace())+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(_config=SimpleNamespace()))url = "https://bytedance.larkoffice.com/file/file_token"assert accessor.can_handle(url)@@ -528,7 +730,7 @@ def test_access_downloads_json_drive_file_as_raw_bytes(monkeypatch):headers={"content-type": "application/json"},)accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(_config=SimpleNamespace())+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(_config=SimpleNamespace()))resource = asyncio.run(accessor.access(@@ -558,7 +760,7 @@ def test_access_downloads_json_attachment_with_business_error_fields(monkeypatchheaders={"content-type": "application/json", "content-disposition": disposition},)accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(_config=SimpleNamespace())+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(_config=SimpleNamespace()))resource = asyncio.run(accessor.access("https://example.feishu.cn/file/json_file", feishu_access_token="u-test"))@@ -589,7 +791,7 @@ def test_access_rejects_raw_feishu_error_envelope(monkeypatch, status_code, disp},)accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(_config=SimpleNamespace())+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(_config=SimpleNamespace()))with pytest.raises(OpenVikingError) as exc_info:asyncio.run(@@ -608,7 +810,6 @@ def test_access_materializes_drive_folder_contract(monkeypatch):from openviking.parse.accessors.feishu_accessor import FeishuDocumentaccessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=False)long_name = "文" * 100children = {"root_folder": [@@ -652,7 +853,13 @@ def test_access_materializes_drive_folder_contract(monkeypatch):url = "https://bytedance.larkoffice.com/drive/folder/root_folder"assert accessor.can_handle(url)- resource = asyncio.run(accessor.access(url, feishu_access_token="u-test"))+ resource = asyncio.run(+ accessor.access(+ url,+ feishu_access_token="u-test",+ feishu_config=_feishu_config(download_images=False),+ )+ )try:markdown_files = sorted(resource.path.glob("*.md"))assert {path.read_text(encoding="utf-8") for path in markdown_files} == {@@ -794,7 +1001,11 @@ def test_access_wiki_keeps_existing_single_document_behavior(monkeypatch):from openviking.parse.accessors.feishu_accessor import FeishuDocumentaccessor = FeishuAccessor()- monkeypatch.setattr(accessor, "_resolve_wiki_node", lambda *_args: ("docx", "doc", "Wiki"))+ monkeypatch.setattr(+ accessor,+ "_resolve_wiki_node",+ lambda *_args, **_kwargs: ("docx", "doc", "Wiki"),+ )async def fake_fetch_document(*_args, **_kwargs):return FeishuDocument(@@ -827,7 +1038,6 @@ def test_access_offloads_synchronous_download_to_thread(monkeypatch):_install_fake_lark_modules(monkeypatch)accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)async def fake_fetch_document(*_args, **_kwargs):from openviking.parse.accessors.feishu_accessor import FeishuDocument@@ -856,7 +1066,12 @@ def test_access_offloads_synchronous_download_to_thread(monkeypatch):monkeypatch.setattr(accessor, "_resolve_image_refs", fake_resolve)- resource = asyncio.run(accessor.access("https://example.feishu.cn/docx/doc_token"))+ resource = asyncio.run(+ accessor.access(+ "https://example.feishu.cn/docx/doc_token",+ feishu_config=_feishu_config(download_images=True),+ )+ )try:assert "thread" in ran_on, "_resolve_image_refs was never called"assert ran_on["thread"] != main_thread, (@@ -871,7 +1086,6 @@ def test_access_offloads_synchronous_download_to_thread(monkeypatch):def test_access_writes_downloaded_images_next_to_markdown(monkeypatch):accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=True)async def fake_fetch_document(*_args, **_kwargs):from openviking.parse.accessors.feishu_accessor import FeishuDocument@@ -894,7 +1108,12 @@ def test_access_writes_downloaded_images_next_to_markdown(monkeypatch):),)- resource = asyncio.run(accessor.access("https://example.feishu.cn/docx/doc_token"))+ resource = asyncio.run(+ accessor.access(+ "https://example.feishu.cn/docx/doc_token",+ feishu_config=_feishu_config(download_images=True),+ )+ )try:assert resource.path.name == "document.md"@@ -940,10 +1159,10 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):)))- accessor._user_token_client = SimpleNamespace(+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=raw_request,wiki=SimpleNamespace(v2=SimpleNamespace(space=SimpleNamespace(get_node=get_wiki_node))),- )+ ))assert accessor._resolve_wiki_node("wiki_token", "u-test") == ("doc",@@ -995,11 +1214,10 @@ def test_fetch_document_dispatches_all_supported_types(monkeypatch):assert legacy_doc.title == "Legacy Doc"assert legacy_doc.markdown_content == "# Legacy Doc\n\ndoc body"assert wiki.title == "Wiki Base"- handlers["_parse_docx"].assert_called_once_with("doc_token", "u-test")- handlers["_parse_sheets"].assert_called_once_with(- "sht_token",- None,- media_download_extras=sheets.media_download_extras,+ assert handlers["_parse_docx"].call_args.args == ("doc_token", "u-test")+ assert handlers["_parse_sheets"].call_args.args == ("sht_token", None)+ assert handlers["_parse_sheets"].call_args.kwargs["media_download_extras"] is (+ sheets.media_download_extras)assert handlers["_parse_bitable"].call_args_list[-1].args == ("wiki_app_token", None)@@ -1077,20 +1295,24 @@ def test_fetch_document_honors_bitable_table_and_view(monkeypatch):))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(max_records_per_table=10)- accessor._client = SimpleNamespace(- bitable=SimpleNamespace(- v1=SimpleNamespace(- app_table=SimpleNamespace(list=list_tables),- app_table_field=SimpleNamespace(list=list_fields),- app_table_record=SimpleNamespace(list=list_records),+ _use_fake_client(+ monkeypatch,+ accessor,+ SimpleNamespace(+ bitable=SimpleNamespace(+ v1=SimpleNamespace(+ app_table=SimpleNamespace(list=list_tables),+ app_table_field=SimpleNamespace(list=list_fields),+ app_table_record=SimpleNamespace(list=list_records),+ ))- )+ ),)+ accessor = _operation(accessor, config=_feishu_config(max_records_per_table=10))document = asyncio.run(accessor._fetch_document(- "https://example.feishu.cn/base/app_token?table=tblSales&view=vewPublic"+ "https://example.feishu.cn/base/app_token?table=tblSales&view=vewPublic",))@@ -1105,7 +1327,8 @@ def test_fetch_document_honors_bitable_table_and_view(monkeypatch):list_records.reset_mock()identity = asyncio.run(accessor.preflight_source(- "https://example.feishu.cn/base/app_token?table=tblSales&view=vewPublic"+ "https://example.feishu.cn/base/app_token?table=tblSales&view=vewPublic",+ feishu_config=_feishu_config(max_records_per_table=10),))@@ -1186,21 +1409,22 @@ def test_parse_sheets_handles_grid_and_embedded_bitable(monkeypatch):))accessor = FeishuAccessor()- accessor._config = SimpleNamespace(+ feishu_config = _feishu_config(max_rows_per_sheet=2,max_records_per_table=10,download_images=True,)- accessor._user_token_client = SimpleNamespace(+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=request,bitable=SimpleNamespace(v1=SimpleNamespace(app_table=SimpleNamespace(list=list_tables),app_table_field=SimpleNamespace(list=list_fields),app_table_record=SimpleNamespace(list=list_records),- )+ ))),)+ accessor = _operation(accessor, config=feishu_config)media_download_extras = {}markdown, title = accessor._parse_sheets(@@ -1349,16 +1573,20 @@ def test_parse_bitable_uses_user_token_and_formats_records(monkeypatch):])accessor = FeishuAccessor()- accessor._config = SimpleNamespace(max_records_per_table=10)- accessor._user_token_client = SimpleNamespace(- bitable=SimpleNamespace(- v1=SimpleNamespace(- app_table=SimpleNamespace(list=list_tables),- app_table_field=SimpleNamespace(list=list_fields),- app_table_record=SimpleNamespace(list=list_records),+ _use_fake_client(+ monkeypatch,+ accessor,+ SimpleNamespace(+ bitable=SimpleNamespace(+ v1=SimpleNamespace(+ app_table=SimpleNamespace(list=list_tables),+ app_table_field=SimpleNamespace(list=list_fields),+ app_table_record=SimpleNamespace(list=list_records),+ ))- )+ ),)+ accessor = _operation(accessor, config=_feishu_config(max_records_per_table=10))markdown, title = accessor._parse_bitable("app_token", "u-test")@@ -1381,7 +1609,7 @@ def test_embedded_sheet_uses_same_user_token(monkeypatch):))accessor = FeishuAccessor()- accessor._user_token_client = SimpleNamespace(request=inspect_block)+ _use_fake_client(monkeypatch, accessor, SimpleNamespace(request=inspect_block))read_range = MagicMock(return_value=[["name", "amount"], ["A", "1"]])monkeypatch.setattr(accessor, "_read_sheet_range", read_range)block = SimpleNamespace(@@ -1407,7 +1635,6 @@ def test_embedded_sheet_uses_same_user_token(monkeypatch):def test_access_keeps_raw_title_but_exposes_safe_original_filename(monkeypatch):accessor = FeishuAccessor()- accessor._config = SimpleNamespace(download_images=False)async def fake_fetch_document(*_args, **_kwargs):from openviking.parse.accessors.feishu_accessor import FeishuDocument@@ -1422,7 +1649,12 @@ def test_access_keeps_raw_title_but_exposes_safe_original_filename(monkeypatch):monkeypatch.setattr(accessor, "_fetch_document", fake_fetch_document)- resource = asyncio.run(accessor.access("https://example.feishu.cn/docx/doc_token"))+ resource = asyncio.run(+ accessor.access(+ "https://example.feishu.cn/docx/doc_token",+ feishu_config=_feishu_config(download_images=False),+ )+ )try:assert resource.meta["feishu_title"] == "API Docs/Overview"assert resource.meta["original_filename"] == "API Docs_Overview"diff --git a/tests/parse/test_feishu_parser_api.py b/tests/parse/test_feishu_parser_api.pyindex 9b22a6954..e6eb72ba8 100644--- a/tests/parse/test_feishu_parser_api.py+++ b/tests/parse/test_feishu_parser_api.py@@ -26,6 +26,21 @@ from openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.utils.media_processor import UnifiedResourceProcessorfrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.session.user_id import UserIdentifier+from openviking_cli.utils.config.parser_config import FeishuConfig+++def _runtime_config_manager(feishu_config=None):+ config = feishu_config or FeishuConfig()++ async def resolve_account(_account_id, resolver):+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(feishu=config),+ )+ )++ return SimpleNamespace(resolve_account=resolve_account)@pytest.mark.asyncio@@ -114,15 +129,15 @@ async def test_feishu_parser_api_bypasses_accessor():@pytest.mark.asyncioasync def test_feishu_parser_api_uses_app_credentials_for_tenant_token(monkeypatch):oauth_client = SimpleNamespace(get_tenant_access_token=AsyncMock(return_value="t-test"))- monkeypatch.setattr(- "openviking.resource.feishu_watch_auth.FeishuOAuthClient.from_config",- Mock(return_value=oauth_client),- )+ from_config = Mock(return_value=oauth_client)+ monkeypatch.setattr("openviking.resource.feishu_watch_auth.FeishuOAuthClient.from_config", from_config)api = _understanding_api_for_parse()+ feishu_config = FeishuConfig(app_id="app", app_secret="secret")- auth = await api._resolve_lark_file({})+ auth = await api._resolve_lark_file({"feishu_config": feishu_config})assert auth == {"tenant_access_token": "t-test"}+ from_config.assert_called_once_with(config=feishu_config)oauth_client.get_tenant_access_token.assert_awaited_once_with()@@ -515,6 +530,7 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token(fail=AsyncMock(),)queue_manager = SimpleNamespace(enqueue=AsyncMock())+ feishu_config = FeishuConfig(app_id="account-app", app_secret="account-secret")monkeypatch.setattr("openviking.service.task_tracker.get_task_tracker",Mock(return_value=task_tracker),@@ -528,6 +544,7 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token(viking_fs=SimpleNamespace(),resource_processor=resource_processor,skill_processor=SimpleNamespace(),+ runtime_config_manager=_runtime_config_manager(feishu_config),)monkeypatch.setattr(service,@@ -538,10 +555,15 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token("openviking.service.resource_service.is_git_repo_url",Mock(return_value=False),)+ monkeypatch.setattr(+ "openviking.connector.delegate.ConnectorDelegate.supported_args",+ Mock(return_value=set()),+ )monkeypatch.setattr("openviking.service.resource_service.uuid4", Mock(return_value="task-1"))- async def preflight(_self, _source, *, feishu_access_token=None):+ async def preflight(_self, _source, *, feishu_access_token=None, **kwargs):assert feishu_access_token == "u-secret"+ assert kwargs["feishu_config"] is feishu_configreturn SimpleNamespace(source_name=preflight_name, source_format="file")async def plan_source_job_target(*, source_info, **_kwargs):@@ -579,6 +601,7 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token(submit_understanding.assert_awaited_once_with(source,feishu_access_token="u-secret",+ feishu_config=feishu_config,custom_option="forwarded",)payload = queue_manager.enqueue.await_args.args[1]@@ -586,6 +609,7 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token(assert "u-secret" not in json.dumps(payload)assert payload["understanding_response_id"] == "response-1"assert payload["args"] == {"custom_option": "forwarded"}+ assert "feishu_config" not in str(payload)queued_msg = AddResourceMsg.from_dict(payload)service._execute_resource_ingestion = AsyncMock(@@ -763,6 +787,7 @@ async def test_uat_producer_cancellation_respects_queue_ownership(),resource_processor=resource_processor,skill_processor=SimpleNamespace(),+ runtime_config_manager=_runtime_config_manager(),)monkeypatch.setattr(service,@@ -773,8 +798,12 @@ async def test_uat_producer_cancellation_respects_queue_ownership("openviking.service.resource_service.is_git_repo_url",Mock(return_value=False),)+ monkeypatch.setattr(+ "openviking.connector.delegate.ConnectorDelegate.supported_args",+ Mock(return_value=set()),+ )- async def preflight(_self, _source, *, feishu_access_token=None):+ async def preflight(_self, _source, *, feishu_access_token=None, **_kwargs):assert feishu_access_token == "u-secret"return SimpleNamespace(source_name=None, source_format="file")@@ -822,13 +851,15 @@ async def test_uat_producer_cancellation_respects_queue_ownership(("resolved_extension", ".pdf"),],)-def test_internal_parser_fields_are_reserved_from_public_args(field, value):+async def test_internal_parser_fields_are_reserved_from_public_args(field, value):service = ResourceService()with pytest.raises(InvalidArgumentError, match=field):- service._normalize_add_resource_args(+ await service._normalize_add_resource_args({field: value},watch_interval=0,+ ctx=RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER),)@@ -1298,13 +1329,14 @@ def test_feishu_direct_submission_requires_configured_auth(monkeypatch):source = "https://example.larkoffice.com/docx/doxcnToken"assert api.can_submit_url_directly(source, feishu_access_token="u-test")+ assert not api.can_submit_url_directly(source)monkeypatch.setattr("openviking.resource.feishu_watch_auth.load_feishu_app_credentials",Mock(side_effect=ValueError("missing credentials")),)- assert not api.can_submit_url_directly(source)+ assert not api.can_submit_url_directly(source, feishu_config=FeishuConfig())def test_normalize_lark_file_accepts_exactly_one_token():diff --git a/tests/parse/test_feishu_token.py b/tests/parse/test_feishu_token.pynew file mode 100644index 000000000..96eda27ac--- /dev/null+++ b/tests/parse/test_feishu_token.py@@ -0,0 +1,84 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for account-isolated Feishu tenant-token caching."""++import json++from openviking.parse.accessors.feishu_token import resolve_feishu_tenant_token_cache+++class RecordingCache:+ def __init__(self):+ self.values = {}+ self.keys = []++ def get(self, key):+ self.keys.append(key)+ return self.values.get(key)++ def set(self, key, value, expire):+ self.keys.append(key)+ self.values[key] = value+++def test_sdk_tenant_token_cache_isolated_by_full_credentials(monkeypatch):+ from lark_oapi.core.http import Transport+ from lark_oapi.core.model import Config, RawResponse+ from lark_oapi.core.token import TokenManager++ calls = []++ def fake_execute(config, request):+ calls.append((config.app_id, config.app_secret, request.uri))+ response = RawResponse()+ response.status_code = 200+ response.content = json.dumps(+ {+ "code": 0,+ "tenant_access_token": f"token-for-{config.app_secret}",+ "expire": 7200,+ }+ ).encode()+ return response++ monkeypatch.setattr(Transport, "execute", fake_execute)+ cache = RecordingCache()+ scoped_cache = resolve_feishu_tenant_token_cache(cache)+ monkeypatch.setattr(TokenManager, "cache", TokenManager.cache)++ account_a = Config()+ account_a.app_id = "shared-app"+ account_a.app_secret = "secret-a"+ account_a.domain = "https://open.feishu.cn"+ account_b = Config()+ account_b.app_id = "shared-app"+ account_b.app_secret = "secret-b"+ account_b.domain = "https://open.feishu.cn"++ with scoped_cache.sdk_scope(+ app_id=account_a.app_id,+ app_secret=account_a.app_secret,+ domain=account_a.domain,+ ):+ assert TokenManager.cache is scoped_cache+ assert TokenManager.get_self_tenant_token(account_a) == "token-for-secret-a"+ with scoped_cache.sdk_scope(+ app_id=account_b.app_id,+ app_secret=account_b.app_secret,+ domain=account_b.domain,+ ):+ assert TokenManager.cache is scoped_cache+ assert TokenManager.get_self_tenant_token(account_b) == "token-for-secret-b"+ with scoped_cache.sdk_scope(+ app_id=account_a.app_id,+ app_secret=account_a.app_secret,+ domain=account_a.domain,+ ):+ assert TokenManager.get_self_tenant_token(account_a) == "token-for-secret-a"+ assert TokenManager.cache is scoped_cache+ assert calls == [+ ("shared-app", "secret-a", "/open-apis/auth/v3/tenant_access_token/internal"),+ ("shared-app", "secret-b", "/open-apis/auth/v3/tenant_access_token/internal"),+ ]+ assert len(cache.values) == 2+ assert all("secret-" not in key for key in cache.keys)diff --git a/tests/parse/test_feishu_unified_import.py b/tests/parse/test_feishu_unified_import.pyindex 55cd8f8d3..68198ab0d 100644--- a/tests/parse/test_feishu_unified_import.py+++ b/tests/parse/test_feishu_unified_import.py@@ -15,10 +15,25 @@ from openviking.parse.parsers.directory import DirectoryParserfrom openviking.parse.understanding_api import UnderstandingAPIfrom openviking.utils.media_processor import UnifiedResourceProcessorfrom openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.utils.config.parser_config import FeishuConfigfrom tests.parse.test_add_directory import FakeVikingFSfrom tests.parse.test_directory_understanding_routing import _configure_understanding+def _runtime_config_manager(feishu_config=None):+ config = feishu_config or FeishuConfig()++ async def resolve_account(_account_id, resolver):+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(feishu=config),+ )+ )++ return SimpleNamespace(resolve_account=resolve_account)++@pytest.mark.parametrize("path,options",[@@ -48,7 +63,11 @@ async def test_downloaded_file_routes_by_extension_but_normalized_markdown_does_tmp_path / name,SourceType.FEISHU,"https://example.feishu.cn/file/t",- meta={"feishu_content_kind": kind},+ meta={+ "feishu_content_kind": kind,+ "resolved_extension": Path(name).suffix,+ "resolved_name": name,+ },)await router.parse(resource)api.parse.assert_awaited_once()@@ -244,6 +263,11 @@ async def test_async_source_plan_does_not_submit_collection_or_file_url(should_use_understanding_directly=router.should_use_understanding_directly,submit_understanding=submit,),+ runtime_config_manager=_runtime_config_manager(),+ )+ monkeypatch.setattr(+ "openviking.service.resource_service.is_git_repo_url",+ Mock(return_value=False),)preflight = AsyncMock(return_value=SimpleNamespace(@@ -271,6 +295,52 @@ async def test_async_source_plan_does_not_submit_collection_or_file_url(assert preflight.await_args.kwargs["feishu_recursive"]+async def test_direct_understanding_receives_effective_account_feishu_config(monkeypatch):+ from openviking.parse.mode import ParseMode+ from openviking.server.identity import RequestContext, Role+ from openviking.service.resource_service import ResourceService+ from openviking_cli.session.user_id import UserIdentifier+ config = FeishuConfig(app_id="account-app", app_secret="account-secret")+ seen = {}++ def should_submit(source, **kwargs):+ seen["route"] = kwargs["feishu_config"]+ return True++ async def submit(source, **kwargs):+ seen["submit"] = kwargs["feishu_config"]+ return "response-1"++ monkeypatch.setattr("openviking.service.resource_service.is_git_repo_url", lambda _path: False)+ monkeypatch.setattr(+ FeishuAccessor,+ "preflight_source",+ AsyncMock(return_value=SimpleNamespace(source_format="file", source_name="Doc")),+ )+ service = ResourceService(+ viking_fs=SimpleNamespace(),+ skill_processor=SimpleNamespace(),+ resource_processor=SimpleNamespace(+ should_use_understanding_directly=should_submit,+ submit_understanding=submit,+ ),+ runtime_config_manager=_runtime_config_manager(config),+ )+ plan = await service._prepare_standard_source_plan(+ path="https://example.feishu.cn/docx/doc",+ ctx=RequestContext(user=UserIdentifier("account", "user"), role=Role.USER),+ mode=ParseMode.DEFAULT,+ allow_local_path_resolution=False,+ processor_kwargs={},+ watch_auth_state=None,+ )++ assert seen == {"route": config, "submit": config}+ assert plan.understanding_response_id == "response-1"+ assert "feishu_config" not in plan.processor_args++@pytest.mark.asyncioasync def test_checkpoint_is_written_before_polling():from openviking.parse.understanding_api import UnderstandingAPIError@@ -305,6 +375,10 @@ async def test_different_extensions_cannot_share_an_output_name(monkeypatch, tmp"_download_drive_file",lambda *a, **k: (b"%PDF-1.7", "application/pdf", "Report.pdf"),)+ accessor = accessor._new_operation(+ "https://example.feishu.cn/docx/doc",+ config=FeishuConfig(),+ )plan = FeishuImportPlan(tmp_path, use_understanding=True)await accessor._write_import_content("docx", "doc", "Report", "", tmp_path, plan)await accessor._write_import_content("file", "pdf", "Report.pdf", "", tmp_path, plan)@@ -324,10 +398,8 @@ def test_pagination_budget_stops_before_next_page(monkeypatch):@pytest.mark.asyncio@pytest.mark.parametrize("backend", [None, "understanding"])async def test_folder_processor_routes_each_content_and_keeps_tree(monkeypatch, backend):- _configure_understanding(monkeypatch, ["pdf"])- from openviking_cli.utils.config.open_viking_config import get_openviking_config-- get_openviking_config().parser_api.enable_feishu_url = True+ config = _configure_understanding(monkeypatch, ["pdf"])+ config.parser_api.enable_feishu_url = Trueaccessor = FeishuAccessor()monkeypatch.setattr(accessor, "_drive_folder_display_name", lambda *a, **k: "Root")monkeypatch.setattr(@@ -480,7 +552,7 @@ async def test_resume_polls_original_response_without_resubmitting():@pytest.mark.asyncioasync def test_drive_wiki_reference_resolves_backing_content(monkeypatch, tmp_path):accessor = FeishuAccessor()- monkeypatch.setattr(accessor, "_resolve_wiki_node", lambda *a: ("base", "app", "Table"))+ monkeypatch.setattr(accessor, "_resolve_wiki_node", lambda *a, **k: ("base", "app", "Table"))plan = FeishuImportPlan(tmp_path, use_understanding=True)url = "https://example.feishu.cn/wiki/ref?table=t&view=v"await accessor._write_import_content("wiki", "ref", "Table", url, tmp_path, plan)@@ -609,10 +681,8 @@ async def test_directory_failure_cleans_unmerged_artifacts(async def test_feishu_collection_obeys_understanding_depth(monkeypatch, tmp_path, kind, extensions, depth):- from openviking_cli.utils.config.open_viking_config import get_openviking_config-- _configure_understanding(monkeypatch, extensions, max_depth=1)- get_openviking_config().parser_api.enable_feishu_url = True+ config = _configure_understanding(monkeypatch, extensions, max_depth=1)+ config.parser_api.enable_feishu_url = Trueparent = tmp_path.joinpath(*[f"level-{i}" for i in range(depth)])parent.mkdir(parents=True)plan = FeishuImportPlan(tmp_path, use_understanding=kind == "url")@@ -809,14 +879,13 @@ async def test_wiki_failed_root_enumeration_is_not_an_empty_success(monkeypatch)@pytest.mark.asyncio@pytest.mark.parametrize("backend", [None, "understanding"])async def test_recursive_wiki_processor_routes_each_content_and_keeps_tree(monkeypatch, backend):- _configure_understanding(monkeypatch, ["pdf"])- from openviking_cli.utils.config.open_viking_config import get_openviking_config-- get_openviking_config().parser_api.enable_feishu_url = True+ config = _configure_understanding(monkeypatch, ["pdf"])+ config.parser_api.enable_feishu_url = Trueaccessor, _ = wiki_accessor(monkeypatch)resources = []async def access(source, **options):+ options.pop("feishu_config", None)resource = await accessor.access(source, **options)resources.append(resource)return resource@@ -843,12 +912,16 @@ async def test_recursive_wiki_processor_routes_each_content_and_keeps_tree(monkereturn resultmonkeypatch.setattr(UnderstandingAPI, "parse", parse_api)+ account_feishu = FeishuConfig(+ app_id="account-app", app_secret="account-secret"+ )try:result = await processor.process("https://example.larksuite.com/wiki/root?table=t&view=v",feishu_recursive=True,feishu_access_token="secret",parser_backend=backend,+ feishu_config=account_feishu,)assert result.meta["failed_files"] == []assert result.meta["file_count"] == 3@@ -860,6 +933,7 @@ async def test_recursive_wiki_processor_routes_each_content_and_keeps_tree(monke"https://example.larksuite.com/wiki/leaf",}assert all(options["feishu_access_token"] == "secret" for _, options in cloud_calls)+ assert all(options["feishu_config"] is account_feishu for _, options in cloud_calls)binary_options = next(options for source, options in calls if not source.startswith("https:"))diff --git a/tests/resource/test_feishu_watch_auth.py b/tests/resource/test_feishu_watch_auth.pyindex 6c9084c54..a0a97bc0e 100644--- a/tests/resource/test_feishu_watch_auth.py+++ b/tests/resource/test_feishu_watch_auth.py@@ -15,27 +15,32 @@ from openviking.resource.feishu_watch_auth import (FeishuAppCredentials,FeishuOAuthClient,FeishuRefreshedToken,+ FeishuTokenRefreshError,apply_feishu_refreshed_token,create_feishu_auth_state,feishu_auth_state_needs_refresh,)+from openviking_cli.utils.config.parser_config import FeishuConfigdef test_oauth_client_uses_watch_app_credentials(monkeypatch):seen = {}- def fake_load_credentials(*, app_id=None, app_secret=None):- seen.update(app_id=app_id, app_secret=app_secret)+ def fake_load_credentials(*, config=None, app_id=None, app_secret=None):+ seen.update(app_id=config.app_id, app_secret=config.app_secret)return FeishuAppCredentials(- app_id=app_id,- app_secret=app_secret,+ app_id=config.app_id,+ app_secret=config.app_secret,domain="https://open.feishu.cn",request_timeout=30,)monkeypatch.setattr(feishu_watch_auth, "load_feishu_app_credentials", fake_load_credentials)- client = FeishuOAuthClient.from_auth_state({"app_id": "cli-test", "app_secret": "secret-test"})+ client = FeishuOAuthClient.from_auth_state(+ {"app_id": "cli-test", "app_secret": "secret-test"},+ config=FeishuConfig(),+ )assert seen == {"app_id": "cli-test", "app_secret": "secret-test"}assert client._credentials.app_id == "cli-test"@@ -64,6 +69,25 @@ def test_feishu_auth_state_refresh_window():assert feishu_auth_state_needs_refresh(near_expiry, now=now) is True+def test_account_default_watch_state_does_not_pin_app_secret():+ credentials = FeishuAppCredentials(+ app_id="account-app",+ app_secret="account-secret",+ domain="https://open.feishu.cn",+ request_timeout=30,+ )++ state = create_feishu_auth_state(+ "u-token",+ "r-token",+ credentials,+ persist_app_secret=False,+ )++ assert state["app_id"] == "account-app"+ assert "app_secret" not in state++@pytest.mark.parametrize(("domain", "token_url"),[@@ -114,6 +138,33 @@ def test_refresh_user_token_uses_oauth_v3_and_rotates_refresh_token(monkeypatch,)+def test_refresh_user_token_marks_invalid_client_as_permanent(monkeypatch):+ monkeypatch.setattr(+ httpx,+ "post",+ lambda *_args, **_kwargs: httpx.Response(+ 401,+ json={+ "error": "invalid_client",+ "error_description": "client authentication failed",+ },+ ),+ )+ client = FeishuOAuthClient(+ FeishuAppCredentials(+ app_id="old-app",+ app_secret="new-app-secret",+ domain="https://open.feishu.cn",+ request_timeout=12,+ )+ )++ with pytest.raises(FeishuTokenRefreshError, match="client authentication failed") as exc_info:+ client._refresh_user_access_token_sync("header.payload.signature")++ assert exc_info.value.permanent is True++def test_refresh_user_token_keeps_legacy_endpoint_for_ur_tokens(monkeypatch):response = MagicMock()response.success.return_value = True@@ -160,10 +211,14 @@ def test_refresh_user_token_keeps_legacy_endpoint_for_ur_tokens(monkeypatch):def test_get_tenant_access_token_uses_configured_app(monkeypatch):+ from lark_oapi.core.token import TokenManager++ monkeypatch.setattr(TokenManager, "cache", TokenManager.cache)seen = {}def fake_get_token(config):seen["config"] = config+ seen["cache"] = TokenManager.cachereturn " t-test "monkeypatch.setattr(@@ -184,3 +239,4 @@ def test_get_tenant_access_token_uses_configured_app(monkeypatch):assert seen["config"].app_secret == "secret-test"assert seen["config"].domain == "https://open.feishu.cn"assert seen["config"].timeout == 12+ assert seen["cache"] is client._tenant_token_cachediff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.pyindex 48dd337af..845249c0d 100644--- a/tests/service/test_resource_service_watch.py+++ b/tests/service/test_resource_service_watch.py@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock, MagicMock, Mockimport pytestimport pytest_asyncio+from openviking.parse.mode import ParseModefrom openviking.resource.feishu_watch_auth import FeishuAppCredentialsfrom openviking.resource.watch_manager import WatchManagerfrom openviking.server.identity import RequestContext, Role@@ -108,6 +109,22 @@ def disable_task_tracker(monkeypatch: pytest.MonkeyPatch) -> None:)+def runtime_config_manager():+ from openviking_cli.utils.config.parser_config import FeishuConfig++ async def resolve_account(account_id, resolver):+ assert account_id+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(feishu=FeishuConfig()),+ )+ )++ return SimpleNamespace(resolve_account=resolve_account)++@pytest.fixture(autouse=True)def isolate_service_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:task_tracker = NoopTaskTracker()@@ -117,6 +134,10 @@ def isolate_service_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:)monkeypatch.setattr(resource_service_module, "is_git_repo_url", lambda _path: False)monkeypatch.setattr("openviking.connector.routing.is_git_repo_url", lambda _path: False)+ monkeypatch.setattr(+ "openviking.connector.delegate.ConnectorDelegate.supported_args",+ Mock(return_value=set()),+ )@pytest_asyncio.fixture@@ -127,7 +148,9 @@ async def watch_manager() -> AsyncGenerator[WatchManager, None]:@pytest_asyncio.fixture-async def resource_service(watch_manager: WatchManager) -> AsyncGenerator[ResourceService, None]:+async def resource_service(+ watch_manager: WatchManager, runtime_config_manager+) -> AsyncGenerator[ResourceService, None]:"""Create ResourceService instance with watch support."""scheduler = MagicMock()scheduler.watch_manager = watch_manager@@ -139,6 +162,7 @@ async def resource_service(watch_manager: WatchManager) -> AsyncGenerator[Resourresource_processor=MockResourceProcessor(),skill_processor=MockSkillProcessor(),watch_scheduler=scheduler,+ runtime_config_manager=runtime_config_manager,)service._enqueue_add_resource_job = AsyncMock(return_value=SimpleNamespace(task_id="test-task"))yield service@@ -465,7 +489,7 @@ class TestAddResourceArgs:monkeypatch.setattr(resource_service_module,"load_feishu_app_credentials",- lambda app_id=None, app_secret=None: FeishuAppCredentials(+ lambda config=None, app_id=None, app_secret=None: FeishuAppCredentials(app_id=app_id or "configured-app",app_secret=app_secret or "configured-secret",domain="https://open.feishu.cn",@@ -478,8 +502,9 @@ class TestAddResourceArgs:return_value=(to_uri, None, False, False))- async def preflight(_self, _source, *, feishu_access_token=None):+ async def preflight(_self, _source, *, feishu_access_token=None, **kwargs):assert feishu_access_token == "u-test"+ assert kwargs["feishu_config"].domain == "https://open.feishu.cn"return SimpleNamespace(source_name=None, source_format="file")monkeypatch.setattr(@@ -541,6 +566,183 @@ class TestAddResourceArgs:}assert "auth_state" not in task.to_dict()+ @pytest.mark.asyncio+ async def test_feishu_account_default_watch_does_not_store_app_secret(+ self,+ monkeypatch: pytest.MonkeyPatch,+ resource_service: ResourceService,+ request_context: RequestContext,+ ):+ monkeypatch.setattr(+ resource_service_module,+ "load_feishu_app_credentials",+ lambda config=None, app_id=None, app_secret=None: FeishuAppCredentials(+ app_id="account-app",+ app_secret="account-secret",+ domain="https://open.feishu.cn",+ request_timeout=30,+ ),+ )++ normalized = await resource_service._normalize_add_resource_args(+ {+ "feishu_access_token": "u-test",+ "feishu_refresh_token": "r-test",+ },+ ctx=request_context,+ watch_interval=30,+ )++ assert normalized.watch_auth_state == {+ "provider": "feishu",+ "access_token": "u-test",+ "refresh_token": "r-test",+ "expires_at": None,+ "app_id": "account-app",+ }++ def test_feishu_watch_refresh_restores_access_token_without_refresh_token(+ self,+ resource_service: ResourceService,+ ):+ msg = SimpleNamespace(+ path="https://example.feishu.cn/docx/doc_token",+ watch_interval=30.0,+ skip_watch_management=True,+ understanding_response_id=None,+ understanding_file_id=None,+ )++ auth_kwargs, watch_auth_state = resource_service._restore_source_task_auth(+ msg,+ {+ "provider": "feishu",+ "access_token": "u-refreshed",+ "domain": "https://open.feishu.cn",+ },+ )++ assert auth_kwargs == {"feishu_access_token": "u-refreshed"}+ assert watch_auth_state is None++ @pytest.mark.asyncio+ async def test_feishu_watch_refresh_preflight_uses_cluster_domain(+ self,+ monkeypatch: pytest.MonkeyPatch,+ resource_service: ResourceService,+ request_context: RequestContext,+ ):+ from openviking_cli.utils.config.parser_config import FeishuConfig++ async def resolve_account(account_id, resolver):+ assert account_id == request_context.account_id+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(+ feishu=FeishuConfig(domain="https://open.feishu.cn")+ ),+ )+ )++ seen = {}++ async def preflight(+ _self,+ _source,+ *,+ feishu_access_token=None,+ feishu_config=None,+ **_kwargs,+ ):+ seen["access_token"] = feishu_access_token+ seen["config_domain"] = feishu_config.domain+ return SimpleNamespace(source_name=None, source_format="file")++ resource_service._runtime_config_manager = SimpleNamespace(+ resolve_account=resolve_account+ )+ monkeypatch.setattr(+ "openviking.parse.accessors.feishu_accessor.FeishuAccessor.preflight_source",+ preflight,+ )++ plan = await resource_service._prepare_standard_source_plan(+ path="https://example.feishu.cn/docx/doc_token",+ ctx=request_context,+ mode=ParseMode.DEFAULT,+ allow_local_path_resolution=False,+ processor_kwargs={+ "feishu_access_token": "u-refreshed",+ },+ watch_auth_state={+ "provider": "feishu",+ "access_token": "u-refreshed",+ "domain": "https://open.larksuite.com",+ },+ )++ assert seen == {+ "access_token": "u-refreshed",+ "config_domain": "https://open.feishu.cn",+ }+ assert "domain" not in plan.task_auth++ @pytest.mark.asyncio+ async def test_feishu_watch_binds_account_app_identity_without_secret(+ self,+ monkeypatch: pytest.MonkeyPatch,+ resource_service: ResourceService,+ request_context: RequestContext,+ ):+ from openviking_cli.utils.config.parser_config import FeishuConfig++ async def resolve_account(account_id, resolver):+ assert account_id == request_context.account_id+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(+ feishu=SimpleNamespace(+ app_id="account-app",+ app_secret="account-secret",+ max_rows_per_sheet=None,+ max_records_per_table=None,+ download_images=None,+ request_timeout=None,+ )+ ),+ cluster=SimpleNamespace(feishu=FeishuConfig()),+ )+ )++ resource_service._runtime_config_manager = SimpleNamespace(+ resolve_account=resolve_account+ )+ disable_task_tracker(monkeypatch)+ to_uri = "viking://resources/feishu-account-watch"+ resource_service._plan_source_job_target = AsyncMock(+ return_value=(to_uri, None, False, False)+ )+ monkeypatch.setattr(+ "openviking.parse.accessors.feishu_accessor.FeishuAccessor.preflight_source",+ AsyncMock(return_value=SimpleNamespace(source_name=None, source_format="file")),+ )++ await resource_service.add_resource(+ path="https://example.feishu.cn/docx/doc_token",+ ctx=request_context,+ to=to_uri,+ watch_interval=30,+ args={+ "feishu_access_token": "user-token",+ "feishu_refresh_token": "refresh-token",+ },+ )++ auth_state = resource_service._enqueue_add_resource_job.await_args.kwargs["task_auth"]+ assert auth_state["app_id"] == "account-app"+ assert "app_secret" not in auth_state+@pytest.mark.asyncio@pytest.mark.parametrize(("target", "is_active"),@@ -563,7 +765,7 @@ class TestAddResourceArgs:return_value=(to_uri, None, False, False))- async def preflight(_self, _source, *, feishu_access_token=None):+ async def preflight(_self, _source, *, feishu_access_token=None, **_kwargs):return SimpleNamespace(source_name="Feishu", source_format="file")monkeypatch.setattr(@@ -611,7 +813,7 @@ class TestAddResourceArgs:):to_uri = "viking://resources/failed_feishu"- async def fail_preflight(_self, _source, *, feishu_access_token=None):+ async def fail_preflight(_self, _source, *, feishu_access_token=None, **_kwargs):raise RuntimeError("preflight unavailable")monkeypatch.setattr(diff --git a/tests/service/test_watch_recovery.py b/tests/service/test_watch_recovery.pyindex 53e81b69a..5b9b7c208 100644--- a/tests/service/test_watch_recovery.py+++ b/tests/service/test_watch_recovery.py@@ -6,13 +6,18 @@ import asyncioimport jsonfrom datetime import datetime, timedeltafrom pathlib import Path+from types import SimpleNamespacefrom typing import AsyncGeneratorfrom unittest.mock import AsyncMockimport pytestimport pytest_asyncio-from openviking.resource.feishu_watch_auth import FeishuOAuthClient, FeishuRefreshedToken+from openviking.resource.feishu_watch_auth import (+ FeishuOAuthClient,+ FeishuRefreshedToken,+ FeishuTokenRefreshError,+)from openviking.resource.git_watch_auth import create_git_http_auth_statefrom openviking.resource.watch_manager import WatchManagerfrom openviking.resource.watch_scheduler import WatchScheduler@@ -445,11 +450,26 @@ class TestResourceExistenceCheck:await scheduler.start()feishu_client = FakeFeishuOAuthClient()- def from_auth_state(_cls, auth_state):+ def from_auth_state(_cls, auth_state, *, config=None):assert auth_state["app_id"] == "cli-test"assert auth_state["app_secret"] == "secret-test"return feishu_client+ async def resolve_account(account_id, resolver):+ from openviking_cli.utils.config.parser_config import FeishuConfig++ assert account_id == task.account_id+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(+ feishu=FeishuConfig(domain="https://open.feishu.cn")+ ),+ )+ )++ scheduler._runtime_config_manager = SimpleNamespace(resolve_account=resolve_account)+monkeypatch.setattr(FeishuOAuthClient,"from_auth_state",@@ -476,6 +496,8 @@ class TestResourceExistenceCheck:assert feishu_client.calls == ["r-old"]assert resource_service.refresh_resource.await_args.kwargs["feishu_access_token"] == "u-new"+ assert "feishu_auth_domain" not in resource_service.refresh_resource.await_args.kwargs+ assert "feishu_config" not in resource_service.refresh_resource.await_args.kwargsupdated_task = await watch_manager.get_task(task.task_id)assert updated_task is not None@@ -483,6 +505,67 @@ class TestResourceExistenceCheck:assert updated_task.auth_state["refresh_token"] == "r-new"assert updated_task.auth_state["expires_at"] is not None+ @pytest.mark.asyncio+ async def test_feishu_permanent_refresh_failure_deactivates_watch(+ self,+ monkeypatch: pytest.MonkeyPatch,+ temp_storage: Path,+ ):+ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )+ resource_service.refresh_resource = AsyncMock()+ scheduler = WatchScheduler(resource_service=resource_service, viking_fs=None)+ await scheduler.start()++ class FailingFeishuOAuthClient:+ async def refresh_user_access_token(self, _refresh_token):+ raise FeishuTokenRefreshError("invalid client credentials", permanent=True)++ monkeypatch.setattr(+ FeishuOAuthClient,+ "from_auth_state",+ classmethod(lambda _cls, _auth_state, *, config: FailingFeishuOAuthClient()),+ )++ async def resolve_account(_account_id, resolver):+ from openviking_cli.utils.config.parser_config import FeishuConfig++ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(feishu=FeishuConfig()),+ )+ )++ scheduler._runtime_config_manager = SimpleNamespace(resolve_account=resolve_account)+ watch_manager = scheduler.watch_manager+ task = await watch_manager.create_task(+ path="https://example.feishu.cn/docx/doc_token",+ to_uri="viking://resources/feishu-user-watch",+ watch_interval=30.0,+ auth_state={+ "provider": "feishu",+ "access_token": "u-old",+ "refresh_token": "r-old",+ "expires_at": None,+ "app_id": "old-app",+ },+ )++ await scheduler._execute_task(task)++ updated_task = await watch_manager.get_task(task.task_id)+ assert updated_task is not None+ assert updated_task.is_active is False+ assert updated_task.last_status == "failed"+ assert updated_task.last_error == "invalid client credentials"+ resource_service.refresh_resource.assert_not_awaited()+@pytest.mark.asyncioasync def test_git_token_watch_restores_task_auth_for_refresh(self, temp_storage: Path, request_context: RequestContextdiff --git a/tests/utils/test_resource_processor_processing_mode.py b/tests/utils/test_resource_processor_processing_mode.pyindex 3f9cd90fd..90b557e9c 100644--- a/tests/utils/test_resource_processor_processing_mode.py+++ b/tests/utils/test_resource_processor_processing_mode.py@@ -18,6 +18,7 @@ from openviking.storage.index_action import FieldPatchfrom openviking.utils.ingest_options import IngestOptionsfrom openviking.utils.resource_processor import ResourceProcessorfrom openviking_cli.session.user_id import UserIdentifier+from openviking_cli.utils.config.parser_config import FeishuConfigclass _FakeVikingDB:@@ -116,6 +117,42 @@ async def test_github_token_is_not_injected_into_ssh_sources(monkeypatch, ctx, smanager.get_account.assert_not_awaited()+async def test_feishu_source_config_uses_cluster_domain(ctx):+ async def resolve_account(account_id, resolver):+ assert account_id == "account-1"+ return resolver(+ SimpleNamespace(+ account=SimpleNamespace(feishu=None),+ cluster=SimpleNamespace(+ feishu=FeishuConfig(+ app_id="current-app",+ app_secret="current-secret",+ domain="https://open.feishu.cn",+ download_images=False,+ )+ ),+ )+ )++ manager = SimpleNamespace(resolve_account=resolve_account)+ processor = ResourceProcessor(+ _FakeVikingDB(),+ runtime_config_manager=manager,+ )++ kwargs = await processor._source_config_kwargs(+ "https://example.feishu.cn/docx/doc",+ ctx,+ {},+ )++ assert kwargs["feishu_config"].app_id == "current-app"+ assert kwargs["feishu_config"].app_secret == "current-secret"+ assert kwargs["feishu_config"].domain == "https://open.feishu.cn"+ assert kwargs["feishu_config"].download_images is False++@pytest.mark.asyncioasync def test_flat_file_refreshes_parent_semantics_and_vectorizes_via_summary(monkeypatch,