deerflow2/backend/packages/harness/deerflow/config
Xinmin Zeng be0eae9825
fix(runtime): suppress tool execution when provider safety-terminates with tool_calls (#3035)
* fix(runtime): suppress tool execution when provider safety-terminates with tool_calls

When a provider stops generation for safety reasons (OpenAI/Moonshot
finish_reason=content_filter, Anthropic stop_reason=refusal, Gemini
finish_reason=SAFETY/BLOCKLIST/PROHIBITED_CONTENT/SPII/RECITATION/
IMAGE_SAFETY/...), the response may still carry truncated tool_calls.
LangChain's tool router treats any non-empty tool_calls as executable,
so partial arguments (e.g. write_file with a half-finished markdown)
get dispatched and the agent loops on retry.

Add SafetyFinishReasonMiddleware at after_model: detect safety
termination via a pluggable detector registry, clear both structured
tool_calls and raw additional_kwargs.tool_calls / function_call,
preserve response_metadata.finish_reason for downstream observers,
stamp additional_kwargs.safety_termination for traces, append a
user-facing explanation to message content (list-aware for thinking
blocks), and emit a safety_termination custom stream event so SSE
consumers can reconcile any "tool starting..." UI.

Default detectors cover OpenAI-compatible content_filter, Anthropic
refusal, and Gemini safety enums (text + image). Custom providers are
added via reflection (same pattern as guardrails). Wired into both
lead-agent and subagent runtimes.

Closes #3028

* fix(runtime): persist safety_termination as a middleware audit event

Address review on #3035: the SSE custom event is great for live
consumers but invisible to post-run audit. RunEventStore should carry
its own row so operators can answer "which runs were safety-suppressed
today?" from a single SQL query without joining the message body.

Worker now exposes the run-scoped RunJournal via
runtime.context["__run_journal"] (sentinel key, internal channel).
SafetyFinishReasonMiddleware calls the previously-unused
RunJournal.record_middleware, which emits

  event_type = "middleware:safety_termination"
  category   = "middleware"
  content    = {name, hook, action, changes={
                  detector, reason_field, reason_value,
                  suppressed_tool_call_count,
                  suppressed_tool_call_names,
                  suppressed_tool_call_ids,
                  message_id, extras}}

Tool *arguments* are deliberately excluded — those are the very content
the provider filtered and persisting them would defeat the purpose of
the safety filter (per review note in #3035).

Graceful skips when journal is absent (subagent runtime, unit tests,
no-event-store local dev). Journal exceptions never propagate into the
agent loop.

Refs #3028

* fix(runtime): satisfy ruff format + address Copilot review

- ruff format on safety_finish_reason_config.py and e2e demo (CI lint
  failed on ruff format --check; backend Makefile lint target runs
  ruff check AND ruff format --check).
- Docstring on SafetyFinishReasonConfig now says resolve_variable to
  match the actual loader used in from_config (the wording was
  resolve_class previously; behavior is unchanged — resolve_variable
  mirrors how guardrails.provider is loaded).
- Switch the AIMessage type check in SafetyFinishReasonMiddleware._apply
  from getattr(last, "type") == "ai" to isinstance(last, AIMessage),
  matching TokenUsageMiddleware / TodoMiddleware / ViewImageMiddleware
  / SummarizationMiddleware which are the dominant pattern.

Refs #3028
2026-05-22 21:20:28 +08:00
..
__init__.py feat(loop-detection): make loop detection configurable with per-tool frequency overrides (#2711) 2026-05-07 16:15:15 +08:00
acp_config.py feat(acp): add env field to ACPAgentConfig for subprocess env injection (#1447) 2026-03-27 20:03:30 +08:00
agents_api_config.py fix: disable custom-agent management API by default (#2161) 2026-04-14 00:03:38 +08:00
agents_config.py feat(agent): add custom-agent self-updates with user isolation (#2713) 2026-05-05 23:17:42 +08:00
app_config.py fix(runtime): suppress tool execution when provider safety-terminates with tool_calls (#3035) 2026-05-22 21:20:28 +08:00
checkpointer_config.py fix(packaging): add postgres extra for store/checkpointer supportFix postgres extra install guidance (#2584) 2026-05-09 09:49:08 +08:00
database_config.py feat(persistence):Unified persistence layer with event store, feedback, and rebase cleanup (#2134) 2026-04-26 11:09:55 +08:00
extensions_config.py Fix env resolution in MCP config lists (#2556) 2026-05-21 07:27:00 +08:00
guardrails_config.py feat(guardrails): add pre-tool-call authorization middleware with pluggable providers (#1240) 2026-03-23 18:07:33 +08:00
loop_detection_config.py feat(loop-detection): make loop detection configurable with per-tool frequency overrides (#2711) 2026-05-07 16:15:15 +08:00
memory_config.py feat(persistence): per-user filesystem isolation, run-scoped APIs, and state/history simplification (#2153) 2026-04-26 11:13:01 +08:00
model_config.py feat(config): add when_thinking_disabled support for model configs (#1970) 2026-04-09 18:49:00 +08:00
paths.py feat(agent): add custom-agent self-updates with user isolation (#2713) 2026-05-05 23:17:42 +08:00
run_events_config.py feat(persistence): add unified persistence layer with event store, token tracking, and feedback (#1930) 2026-04-26 11:05:47 +08:00
runtime_paths.py fix(harness): resolve runtime paths from project root (#2642) 2026-05-01 22:19:50 +08:00
safety_finish_reason_config.py fix(runtime): suppress tool execution when provider safety-terminates with tool_calls (#3035) 2026-05-22 21:20:28 +08:00
sandbox_config.py fix: add output truncation to ls_tool to prevent context window overflow (#1896) 2026-04-06 15:09:57 +08:00
skill_evolution_config.py Implement skill self-evolution and skill_manage flow (#1874) 2026-04-06 22:07:11 +08:00
skills_config.py fix(harness): restore legacy skills path fallback (#2694) (#2696) 2026-05-03 23:40:59 +08:00
stream_bridge_config.py fix(config): reset config-backed singletons on hot reload (#2588) 2026-05-06 10:17:55 +08:00
subagents_config.py fix(config): reset config-backed singletons on hot reload (#2588) 2026-05-06 10:17:55 +08:00
summarization_config.py fix(middleware): avoid rescuing non-skill tool outputs during summarization (#2458) 2026-04-24 21:19:46 +08:00
title_config.py fix(tracing): propagate session_id and user_id into Langfuse traces (#2944) 2026-05-21 16:49:31 +08:00
token_usage_config.py enable token usage by default (#2841) 2026-05-10 22:00:57 +08:00
tool_config.py refactor: split backend into harness (deerflow.*) and app (app.*) (#1131) 2026-03-14 22:55:52 +08:00
tool_search_config.py feat(tools): add tool_search for deferred MCP tool loading (#1176) 2026-03-17 20:43:55 +08:00
tracing_config.py fix(tracing): propagate session_id and user_id into Langfuse traces (#2944) 2026-05-21 16:49:31 +08:00