This commit is contained in:
董宏凯 committed 2026-05-15 23:27:48 +08:00
commit e08e7be24c
404 files changed
+113007 -921

No files matched your search

@@ -8,9 +8,10 @@ from deerflow.agents.lead_agent.prompt import apply_prompt_template
from deerflow.agents.memory.summarization_hook import memory_flush_hook
from deerflow.agents.middlewares.clarification_middleware import ClarificationMiddleware
from deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.agents.middlewares.setup_agent_approval_middleware import SetupAgentApprovalMiddleware
from deerflow.agents.middlewares.subagent_limit_middleware import SubagentLimitMiddleware
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.agents.middlewares.prompt_prefix_middleware import PromptPrefixMiddleware
from deerflow.agents.middlewares.setup_agent_approval_middleware import SetupAgentApprovalMiddleware
from deerflow.agents.middlewares.subagent_limit_middleware import SubagentLimitMiddleware
from deerflow.agents.middlewares.summarization_middleware import BeforeSummarizationHook, DeerFlowSummarizationMiddleware
from deerflow.agents.middlewares.title_middleware import TitleMiddleware
from deerflow.agents.middlewares.todo_middleware import TodoMiddleware
@@ -257,6 +258,10 @@ def _build_middlewares(
resolved_app_config = app_config or get_app_config()
middlewares = build_lead_runtime_middlewares(app_config=resolved_app_config, lazy_init=True)
# Inject the admin prompt prefix into the model request (kept out of the
# persisted/displayed message so the user never sees it).
middlewares.append(PromptPrefixMiddleware())
# Add summarization middleware if enabled
summarization_middleware = _create_summarization_middleware(app_config=resolved_app_config)
if summarization_middleware is not None:
@@ -304,10 +309,10 @@ def _build_middlewares(
if custom_middlewares:
middlewares.extend(custom_middlewares)
middlewares.append(SetupAgentApprovalMiddleware())
# ClarificationMiddleware should always be last
middlewares.append(ClarificationMiddleware())
middlewares.append(SetupAgentApprovalMiddleware())
# ClarificationMiddleware should always be last
middlewares.append(ClarificationMiddleware())
return middlewares
@@ -331,9 +336,13 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
requested_model_name: str | None = cfg.get("model_name") or cfg.get("model")
is_plan_mode = cfg.get("is_plan_mode", False)
subagent_enabled = cfg.get("subagent_enabled", False)
max_concurrent_subagents = cfg.get("max_concurrent_subagents", 3)
is_bootstrap = cfg.get("is_bootstrap", False)
agent_id = validate_agent_id(cfg.get("agent_id") or cfg.get("agent_name"))
max_concurrent_subagents = cfg.get("max_concurrent_subagents", 3)
is_bootstrap = cfg.get("is_bootstrap", False)
writing_mode = bool(cfg.get("writing_mode", False))
writing_artifact_path = cfg.get("writing_artifact_path") if writing_mode else None
if not isinstance(writing_artifact_path, str) or not writing_artifact_path.strip():
writing_artifact_path = None
agent_id = validate_agent_id(cfg.get("agent_id") or cfg.get("agent_name"))
agent_config = load_agent_config(agent_id) if not is_bootstrap else None
agent_display_name = agent_config.name if agent_config else agent_id
@@ -352,14 +361,15 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
thinking_enabled = False
logger.info(
"Create Agent(%s) -> thinking_enabled: %s, reasoning_effort: %s, model_name: %s, is_plan_mode: %s, subagent_enabled: %s, max_concurrent_subagents: %s",
agent_id or "default",
thinking_enabled,
reasoning_effort,
model_name,
is_plan_mode,
subagent_enabled,
max_concurrent_subagents,
"Create Agent(%s) -> thinking_enabled: %s, reasoning_effort: %s, model_name: %s, is_plan_mode: %s, subagent_enabled: %s, max_concurrent_subagents: %s, writing_mode: %s",
agent_id or "default",
thinking_enabled,
reasoning_effort,
model_name,
is_plan_mode,
subagent_enabled,
max_concurrent_subagents,
writing_mode,
)
# Inject run metadata for LangSmith trace tagging
@@ -383,8 +393,10 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
"thinking_enabled": thinking_enabled,
"reasoning_effort": reasoning_effort,
"is_plan_mode": is_plan_mode,
"subagent_enabled": subagent_enabled,
"tool_groups": agent_config.tool_groups if agent_config else None,
"subagent_enabled": subagent_enabled,
"writing_mode": writing_mode,
"writing_artifact_path": writing_artifact_path,
"tool_groups": agent_config.tool_groups if agent_config else None,
"available_skills": runtime_available_skills,
}
)
@@ -403,9 +415,11 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
middleware=_build_middlewares(config, model_name=model_name, app_config=resolved_app_config),
system_prompt=apply_prompt_template(
subagent_enabled=subagent_enabled,
max_concurrent_subagents=max_concurrent_subagents,
available_skills=set(["bootstrap"]),
app_config=resolved_app_config,
max_concurrent_subagents=max_concurrent_subagents,
writing_mode=writing_mode,
writing_artifact_path=writing_artifact_path,
available_skills=set(["bootstrap"]),
app_config=resolved_app_config,
),
state_schema=ThreadState,
)
@@ -424,10 +438,12 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
system_prompt=apply_prompt_template(
subagent_enabled=subagent_enabled,
max_concurrent_subagents=max_concurrent_subagents,
agent_id=agent_id,
agent_name=agent_display_name,
available_skills=(set(agent_config.skills or []) if agent_config else None),
app_config=resolved_app_config,
agent_id=agent_id,
agent_name=agent_display_name,
writing_mode=writing_mode,
writing_artifact_path=writing_artifact_path,
available_skills=(set(agent_config.skills or []) if agent_config else None),
app_config=resolved_app_config,
),
state_schema=ThreadState,
)
@@ -69,8 +69,25 @@ _enabled_skills_refresh_version = 0
_enabled_skills_refresh_event = threading.Event()
def _drop_archived_skills(skills: list[Skill]) -> list[Skill]:
"""从注入提示词的技能列表里剔除已归档(usage state=archived)的技能。
技能归档是软状态:SKILL.md 仍留在 custom/<name>/、enabled 标志不变,所以
load_skills(enabled_only=True) 仍会返回它。但归档技能不应再出现在 agent 的系统
提示词里 —— 对 agent 而言它应等同于"不存在"。失败时不过滤(返回原列表)。
"""
try:
from deerflow.skills.usage import STATE_ARCHIVED, all_entries
entries = all_entries()
return [s for s in skills if entries.get(s.name, {}).get("state") != STATE_ARCHIVED]
except Exception:
logger.debug("Failed to filter archived skills for prompt injection", exc_info=True)
return skills
def _load_enabled_skills_sync() -> list[Skill]:
return list(get_or_new_skill_storage().load_skills(enabled_only=True))
return _drop_archived_skills(list(get_or_new_skill_storage().load_skills(enabled_only=True)))
def _start_enabled_skills_refresh_thread() -> None:
@@ -171,7 +188,7 @@ def _get_enabled_skills_for_config(app_config: AppConfig | None = None) -> list[
"""
if app_config is None:
return _get_enabled_skills()
return list(get_or_new_skill_storage(app_config=app_config).load_skills(enabled_only=True))
return _drop_archived_skills(list(get_or_new_skill_storage(app_config=app_config).load_skills(enabled_only=True)))
def _skill_mutability_label(category: SkillCategory | str) -> str:
@@ -481,6 +498,8 @@ You: "Deploying to staging..." [proceed]
{deferred_tools_section}
{writing_mode_section}
{subagent_section}
<working_directory existed="true">
@@ -800,6 +819,8 @@ def apply_prompt_template(
*,
agent_id: str | None = None,
agent_name: str | None = None,
writing_mode: bool = False,
writing_artifact_path: str | None = None,
available_skills: set[str] | None = None,
app_config: AppConfig | None = None,
) -> str:
@@ -835,6 +856,32 @@ def apply_prompt_template(
# Get deferred tools section (tool_search)
deferred_tools_section = get_deferred_tools_prompt_section(app_config=app_config)
current_writing_artifact = (
f"\n**Current Markdown Artifact**\n- Continue editing this existing Markdown file unless the user explicitly asks for a new document: `{writing_artifact_path}`\n"
if writing_artifact_path
else ""
)
writing_mode_section = (
f"""
<writing_mode>
Writing mode is enabled for this run.
**Mandatory Output Contract**
- Treat the user's request as a writing/report-generation task.
- Your final deliverable MUST be a Markdown file, not only an inline chat answer.
- If a current Markdown artifact is provided below, you MUST revise that existing file rather than creating a new file, unless the user explicitly asks for a separate/new document.
- When revising an existing Markdown artifact, read the file first if needed, then overwrite the same path with the complete updated Markdown content.
- Write the deliverable to `/mnt/user-data/outputs/` with a clear `.md` filename, for example `/mnt/user-data/outputs/report.md`.
- Use `write_file` or an equivalent file-writing tool to save the complete Markdown content.
- After writing the file, call `present_files` with the Markdown file path so the user can open it as an artifact/canvas.
- The final chat response should be brief and point to the generated Markdown artifact. Do not duplicate the full report inline unless the user explicitly asks.
- If you revise an existing Markdown artifact, update the Markdown file and present it again.
{current_writing_artifact}
</writing_mode>
"""
if writing_mode
else ""
)
# Build ACP agent section only if ACP agents are configured
acp_section = _build_acp_section(app_config=app_config)
@@ -850,6 +897,7 @@ def apply_prompt_template(
soul=get_agent_soul(storage_agent_id),
skills_section=skills_section,
deferred_tools_section=deferred_tools_section,
writing_mode_section=writing_mode_section,
memory_context=memory_context,
network_policy_section=network_policy_section,
subagent_section=subagent_section,
@@ -0,0 +1,335 @@
"""Middleware that records per-LLM-call metrics for the admin audit page.
Captures **every** provider invocation regardless of the frontend speed-meter
toggle: the goal is a complete admin-side audit log of LLM usage, including
failures. The user-facing speed indicator (controlled by
``LocalSettings.display.streamSpeedMeterEnabled``) is a separate, purely
cosmetic feature — turning it off does not stop this recording.
Each call ends with one row in ``llm_call_metrics``:
- Successes record duration, token counts, and ``tokens_per_sec``.
- Errors record the duration spent before the failure, the exception class as
``error_type`` and a one-line ``error_message``.
Writes go through a best-effort store: a DB outage logs a warning and the
agent runtime keeps streaming. We intentionally place this middleware
*inside* :class:`LLMErrorHandlingMiddleware` (i.e. nested deeper in the
``wrap_model_call`` chain) so we observe the **real** provider call timings —
not the retry-wrapped successful response.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime
from typing import Any, override
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langchain.agents.middleware.types import (
ModelCallResult,
ModelRequest,
ModelResponse,
)
from langchain_core.messages import AIMessage
from langgraph.errors import GraphBubbleUp
from deerflow.persistence.engine import get_session_factory
from deerflow.persistence.llm_metrics import LlmMetricRecord, make_llm_metrics_store
from deerflow.persistence.llm_metrics.base import LlmMetricsStore
from deerflow.runtime.user_context import get_effective_user_id
logger = logging.getLogger(__name__)
def _now() -> datetime:
return datetime.now(UTC)
def _safe_get_thread_id(request: ModelRequest) -> str | None:
state = getattr(request, "state", None)
if isinstance(state, dict):
thread_id = state.get("thread_id")
if isinstance(thread_id, str) and thread_id:
return thread_id
runtime = getattr(request, "runtime", None)
if runtime is None:
return None
config = getattr(runtime, "config", None)
configurable = (config or {}).get("configurable", {}) if isinstance(config, dict) else {}
thread_id = configurable.get("thread_id") if isinstance(configurable, dict) else None
if isinstance(thread_id, str) and thread_id:
return thread_id
return None
def _safe_get_run_id(request: ModelRequest) -> str | None:
runtime = getattr(request, "runtime", None)
if runtime is None:
return None
context = getattr(runtime, "context", None)
if isinstance(context, dict):
for key in ("run_id", "langgraph_run_id"):
value = context.get(key)
if isinstance(value, str) and value:
return value
config = getattr(runtime, "config", None)
if isinstance(config, dict):
metadata = config.get("metadata") if isinstance(config.get("metadata"), dict) else {}
if isinstance(metadata, dict):
for key in ("run_id", "langgraph_run_id"):
value = metadata.get(key)
if isinstance(value, str) and value:
return value
return None
def _safe_get_model_name(request: ModelRequest) -> str | None:
model = getattr(request, "model", None)
for attr in ("model_name", "model", "name"):
value = getattr(model, attr, None)
if isinstance(value, str) and value:
return value
return None
def _safe_get_agent_name(request: ModelRequest) -> str | None:
runtime = getattr(request, "runtime", None)
if runtime is None:
return None
context = getattr(runtime, "context", None)
if isinstance(context, dict):
for key in ("agent_name", "agent_id"):
value = context.get(key)
if isinstance(value, str) and value:
return value
return None
def _coerce_int(value: Any) -> int | None:
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(value)
except (TypeError, ValueError):
return None
return None
def _extract_usage(response: Any) -> dict[str, int]:
"""Pull token counts out of an AIMessage, falling back to provider-native shapes.
The handler in ``wrap_model_call`` actually hands us a
:class:`langchain.agents.middleware.types.ModelResponse` dataclass whose
``.result`` is a ``list[BaseMessage]``. Earlier versions of this helper
only matched ``AIMessage`` and ``list``, which meant we silently dropped
every successful call and stored None for input/output/total. To stay
robust we now also handle ``ModelResponse`` (and ``ExtendedModelResponse``,
which wraps a ModelResponse), and we walk the messages list for the first
``AIMessage``.
LangChain normalises usage into ``message.usage_metadata`` with the keys
``input_tokens`` / ``output_tokens`` / ``total_tokens``. Several
OpenAI-compatible providers (DeepSeek, vLLM, some Azure deployments) leave
that dict partial — typically only ``total_tokens`` is populated — and the
real breakdown sits under ``response_metadata.token_usage`` with the
provider-native key names ``prompt_tokens`` / ``completion_tokens``. We
merge both so the admin audit view always has the most complete numbers
available.
"""
message: AIMessage | None = None
def _find_ai(candidate: Any) -> AIMessage | None:
if isinstance(candidate, AIMessage):
return candidate
if isinstance(candidate, list):
for item in candidate:
found = _find_ai(item)
if found is not None:
return found
return None
message = _find_ai(response)
if message is None:
# ModelResponse / ExtendedModelResponse — defined as dataclasses with a
# ``result`` field holding ``list[BaseMessage]``. Recurse via attribute
# access so we don't tightly couple to the dataclass class itself.
for attr in ("result", "model_response"):
inner = getattr(response, attr, None)
if inner is None:
continue
message = _find_ai(inner)
if message is None and attr == "model_response":
inner_result = getattr(inner, "result", None)
message = _find_ai(inner_result)
if message is not None:
break
if message is None:
return {}
out: dict[str, int] = {}
usage = getattr(message, "usage_metadata", None) or {}
if isinstance(usage, dict):
for key in ("input_tokens", "output_tokens", "total_tokens"):
coerced = _coerce_int(usage.get(key))
if coerced is not None:
out[key] = coerced
response_metadata = getattr(message, "response_metadata", None) or {}
token_usage = response_metadata.get("token_usage") if isinstance(response_metadata, dict) else None
if isinstance(token_usage, dict):
# Map both the LangChain-canonical names and OpenAI-native names; later
# writes win so a more-precise provider-native value can override a
# zero placeholder from usage_metadata.
candidates = {
"input_tokens": ("input_tokens", "prompt_tokens"),
"output_tokens": ("output_tokens", "completion_tokens"),
"total_tokens": ("total_tokens",),
}
for canonical, keys in candidates.items():
for key in keys:
coerced = _coerce_int(token_usage.get(key))
if coerced is not None and coerced > 0:
out[canonical] = coerced
break
# Derive a missing or implausibly-zero field if the other two are present.
# Some providers report ``input_tokens=0`` / ``output_tokens=0`` next to a
# real ``total_tokens`` — treat those zeros as missing so we don't silently
# store nonsense breakdowns.
def _missing_or_zero(key: str) -> bool:
return out.get(key) in (None, 0)
if "total_tokens" not in out and out.get("input_tokens") and out.get("output_tokens"):
out["total_tokens"] = out["input_tokens"] + out["output_tokens"]
if _missing_or_zero("output_tokens") and out.get("total_tokens") and out.get("input_tokens"):
derived = out["total_tokens"] - out["input_tokens"]
if derived > 0:
out["output_tokens"] = derived
if _missing_or_zero("input_tokens") and out.get("total_tokens") and out.get("output_tokens"):
derived = out["total_tokens"] - out["output_tokens"]
if derived > 0:
out["input_tokens"] = derived
return out
def _classify_exception(exc: BaseException) -> tuple[str, str]:
"""Return (error_type, error_message). Message is trimmed to 500 chars."""
name = exc.__class__.__name__
raw = (str(exc) or name).strip()
return name, (raw[:500] if len(raw) > 500 else raw)
class LlmMetricsMiddleware(AgentMiddleware[AgentState]):
"""Wrap each model call to time it and persist a metric row."""
def __init__(self, *, store: LlmMetricsStore | None = None, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._store_override = store
def _store(self) -> LlmMetricsStore | None:
if self._store_override is not None:
return self._store_override
try:
sf = get_session_factory()
except Exception:
return None
return make_llm_metrics_store(sf)
def _build_base_record(self, request: ModelRequest) -> LlmMetricRecord:
return LlmMetricRecord(
id=uuid.uuid4().hex,
created_at=_now(),
user_id=get_effective_user_id(),
thread_id=_safe_get_thread_id(request),
run_id=_safe_get_run_id(request),
agent_name=_safe_get_agent_name(request),
model_name=_safe_get_model_name(request),
)
def _finalize_success(self, record: LlmMetricRecord, response: ModelResponse, started: float) -> None:
elapsed = max(0.0, time.monotonic() - started)
record.duration_ms = int(elapsed * 1000)
usage = _extract_usage(response)
record.input_tokens = usage.get("input_tokens")
record.output_tokens = usage.get("output_tokens")
record.total_tokens = usage.get("total_tokens") or (
(record.input_tokens or 0) + (record.output_tokens or 0) or None
)
if record.output_tokens is not None and elapsed > 0:
record.tokens_per_sec = round(record.output_tokens / elapsed, 3)
record.status = "success"
def _finalize_error(self, record: LlmMetricRecord, exc: BaseException, started: float) -> None:
record.duration_ms = int(max(0.0, time.monotonic() - started) * 1000)
record.status = "error"
record.error_type, record.error_message = _classify_exception(exc)
def _flush(self, record: LlmMetricRecord) -> None:
store = self._store()
if store is None:
return
try:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop is not None and loop.is_running():
# Fire-and-forget — never let metric IO block the request path.
loop.create_task(store.record(record))
else:
asyncio.run(store.record(record))
except Exception:
logger.warning("LlmMetricsMiddleware: failed to flush metric %s", record.id, exc_info=True)
@override
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
record = self._build_base_record(request)
started = time.monotonic()
try:
response = handler(request)
except GraphBubbleUp:
# LangGraph control flow — not a real LLM failure.
raise
except Exception as exc:
self._finalize_error(record, exc, started)
self._flush(record)
raise
self._finalize_success(record, response, started)
self._flush(record)
return response
@override
async def awrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
record = self._build_base_record(request)
started = time.monotonic()
try:
response = await handler(request)
except GraphBubbleUp:
raise
except Exception as exc:
self._finalize_error(record, exc, started)
self._flush(record)
raise
self._finalize_success(record, response, started)
self._flush(record)
return response
@@ -0,0 +1,78 @@
"""Middleware that injects the admin-configured prompt prefix at model-call time.
The prompt-prefix feature lets an admin prepend a fixed instruction to the
user's question before it reaches the LLM. To keep the prefix invisible in the
chat UI, the Gateway does **not** concatenate it into the persisted
``HumanMessage.content``; instead it tags the first human message with
``additional_kwargs["prompt_prefix"]`` (see ``app.gateway.services``).
This middleware reads that tag and prepends the prefix to the message content
*only in the request handed to the model*. The persisted state — and therefore
what the frontend renders — keeps the clean, prefix-free content.
"""
from collections.abc import Awaitable, Callable
from typing import override
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langchain.agents.middleware.types import ModelCallResult, ModelRequest, ModelResponse
from langchain_core.messages import HumanMessage
PROMPT_PREFIX_KEY = "prompt_prefix"
class PromptPrefixMiddleware(AgentMiddleware[AgentState]):
"""Prepends ``additional_kwargs['prompt_prefix']`` to human messages for the LLM only.
The transformation is applied to the model request copy, never written back
to state, so it is naturally idempotent across the multiple model calls of a
single turn.
"""
@staticmethod
def _apply(messages: list) -> list | None:
"""Return a patched copy with prefixes prepended, or None if nothing to do."""
patched: list | None = None
for idx, msg in enumerate(messages):
if not isinstance(msg, HumanMessage):
continue
raw_prefix = (getattr(msg, "additional_kwargs", None) or {}).get(PROMPT_PREFIX_KEY)
prefix = str(raw_prefix).strip() if raw_prefix else ""
if not prefix:
continue
content = msg.content
if isinstance(content, str):
new_content: object = f"{prefix}\n\n{content}".strip("\n")
elif isinstance(content, list):
# Structured content (text blocks + media): prepend a text block.
new_content = [{"type": "text", "text": prefix}, *content]
else:
new_content = f"{prefix}\n\n{content!s}"
if patched is None:
patched = list(messages)
# model_copy preserves the message id so streaming dedup is unaffected.
patched[idx] = msg.model_copy(update={"content": new_content})
return patched
@override
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
patched = self._apply(request.messages)
if patched is not None:
request = request.override(messages=patched)
return handler(request)
@override
async def awrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
patched = self._apply(request.messages)
if patched is not None:
request = request.override(messages=patched)
return await handler(request)
@@ -72,7 +72,7 @@ class SetupAgentApprovalMiddleware(AgentMiddleware[SetupAgentApprovalMiddlewareS
approval_msg = ToolMessage(
id=self._stable_message_id(tool_call_id, args),
content="请确认是否创建/更新这个专家配置。",
content="请确认是否创建/更新这个智能体配置。",
tool_call_id=tool_call_id,
name="setup_agent",
additional_kwargs={"setup_agent_approval": payload},
@@ -96,6 +96,14 @@ def _build_runtime_middlewares(
middlewares.append(LLMErrorHandlingMiddleware(app_config=app_config))
# LLM call metrics — always on, even when the user-facing speed indicator
# is disabled. We append *after* the retry middleware so the metrics
# middleware sits deeper in the wrap chain and observes individual provider
# attempts (including the failed ones).
from deerflow.agents.middlewares.llm_metrics_middleware import LlmMetricsMiddleware
middlewares.append(LlmMetricsMiddleware())
# Guardrail middleware (if configured)
guardrails_config = app_config.guardrails
if guardrails_config.enabled and guardrails_config.provider: