mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(scheduler): enable subagents for scheduled tasks (#8598)
Persist an opt-in for automatic and manually triggered scheduled runs. Carry unattended guidance through ordinary and durable delegation, and keep continuation discovery separate from batch argument validation. Cover the Gateway-to-worker path, including queued batches recovered after restart, and add the opt-in with Alembic revision 0062. Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
e0886e9677
commit
f189099c09
@ -153,6 +153,7 @@ class ScheduledTaskCreateRequest(BaseModel):
|
||||
thread_id: ThreadId | None = None
|
||||
context_mode: str = "fresh_thread_per_run"
|
||||
assistant_id: str | None = Field(default=None, min_length=1)
|
||||
subagent_enabled: bool = False
|
||||
title: str = Field(min_length=1)
|
||||
prompt: str = Field(min_length=1)
|
||||
schedule_type: str
|
||||
@ -172,6 +173,7 @@ class ScheduledTaskUpdateRequest(BaseModel):
|
||||
context_mode: str | None = None
|
||||
thread_id: ThreadId | None = None
|
||||
assistant_id: str | None = Field(default=None, min_length=1)
|
||||
subagent_enabled: bool | None = None
|
||||
title: str | None = Field(default=None, min_length=1)
|
||||
prompt: str | None = Field(default=None, min_length=1)
|
||||
# Allowed; when it changes, schedule_spec is required.
|
||||
@ -284,6 +286,7 @@ async def create_scheduled_task(request: Request, body: ScheduledTaskCreateReque
|
||||
created = await repo.create(
|
||||
task_id=f"task-{uuid.uuid4().hex}",
|
||||
user_id=str(user.id),
|
||||
subagent_enabled=body.subagent_enabled,
|
||||
**definition,
|
||||
)
|
||||
except ValueError as exc:
|
||||
|
||||
@ -3354,6 +3354,7 @@ async def launch_scheduled_thread_run(
|
||||
metadata: dict[str, Any] | None = None,
|
||||
origin: dict[str, Any] | None = None,
|
||||
title: str | None = None,
|
||||
subagent_enabled: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Start one scheduled occurrence as an internal run.
|
||||
|
||||
@ -3387,6 +3388,11 @@ async def launch_scheduled_thread_run(
|
||||
graph_input: dict[str, Any] = {"messages": [message]}
|
||||
if title:
|
||||
graph_input["title"] = title
|
||||
context: dict[str, Any] = {"non_interactive": True}
|
||||
if owner_user_id:
|
||||
context["user_id"] = owner_user_id
|
||||
if subagent_enabled:
|
||||
context["subagent_enabled"] = True
|
||||
body = RunCreateRequest(
|
||||
assistant_id=assistant_id,
|
||||
input=graph_input,
|
||||
@ -3397,7 +3403,7 @@ async def launch_scheduled_thread_run(
|
||||
# runtime-context consumers without a ContextVar fallback (e.g.
|
||||
# user-scoped GuardrailMiddleware providers) see the owning user;
|
||||
# ``inject_authenticated_user_context`` skips the internal user.
|
||||
context=({"non_interactive": True, "user_id": owner_user_id} if owner_user_id else {"non_interactive": True}),
|
||||
context=context,
|
||||
webhook=None,
|
||||
checkpoint_id=None,
|
||||
checkpoint=None,
|
||||
|
||||
@ -788,6 +788,7 @@ class ScheduledTaskService:
|
||||
result = await self._launch_run(
|
||||
thread_id=execution_thread_id,
|
||||
assistant_id=task.get("assistant_id"),
|
||||
subagent_enabled=task.get("subagent_enabled", False),
|
||||
prompt=prompt,
|
||||
owner_user_id=task.get("user_id"),
|
||||
metadata=metadata,
|
||||
|
||||
@ -1873,6 +1873,7 @@ POST /api/scheduled-tasks/preview-cron
|
||||
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `subagent_enabled` | boolean | Opt in to delegation for automatic and manual runs. Defaults to false on create. PATCH omission or null preserves the setting. Agent allowlists and runtime capacity limits still apply. |
|
||||
| `goal_objective` | string \| null | What one run must achieve (at most 4000 characters after whitespace normalization); requires `fresh_thread_per_run`. |
|
||||
| `max_runs` | integer \| null | Safety cap: automatic runs over the task's lifetime (trial runs excluded); at least 1. |
|
||||
| `end_at` | date-time \| null | Safety cap: no automatic run after this time. Without a UTC offset it is wall-clock time in the task's timezone. |
|
||||
|
||||
@ -3,9 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from deerflow.subagents.config import SubagentConfig
|
||||
|
||||
ASK_CLARIFICATION_TOOL_NAME = "ask_clarification"
|
||||
|
||||
@ -66,6 +69,16 @@ class RunInteractionPolicy:
|
||||
return frozenset()
|
||||
return frozenset({ASK_CLARIFICATION_TOOL_NAME})
|
||||
|
||||
def apply_to_subagent(self, config: SubagentConfig) -> SubagentConfig:
|
||||
"""Snapshot unattended guidance and tool restrictions for child execution."""
|
||||
if self.allows_clarification:
|
||||
return config
|
||||
return replace(
|
||||
config,
|
||||
system_prompt="\n\n".join(filter(None, (self.clarification_system, config.system_prompt))),
|
||||
disallowed_tools=list(dict.fromkeys([*(config.disallowed_tools or []), *sorted(self.disabled_tool_names)])),
|
||||
)
|
||||
|
||||
@property
|
||||
def thinking_guidance(self) -> str:
|
||||
if self.allows_clarification:
|
||||
|
||||
@ -1014,12 +1014,16 @@ def _assemble_lead_agent(
|
||||
skill_storage: SkillStorage | None = None,
|
||||
) -> LeadAgentAssembly:
|
||||
# Lazy import to avoid circular dependency
|
||||
from deerflow_extension_api.agent_runs import AGENT_RUNS_CONTEXT_KEY
|
||||
|
||||
from deerflow.tools import get_available_tools
|
||||
from deerflow.tools.builtins import setup_agent, update_agent
|
||||
from deerflow.tools.builtins.batch_task_tool import restrict_batch_continuation
|
||||
from deerflow.tools.builtins.tool_search import assemble_deferred_tools, build_mcp_routing_middleware, get_mcp_routing_hints_prompt_section
|
||||
from deerflow.tools.conversation import CONVERSATION_READER_CONTEXT_KEY
|
||||
|
||||
cfg = _get_runtime_config(config)
|
||||
batch_continuation_available = cfg.get(AGENT_RUNS_CONTEXT_KEY) is not None
|
||||
resolved_app_config = app_config
|
||||
mode = (config.get("configurable", {}) or {}).get(
|
||||
INTERNAL_CHECKPOINT_MODE_KEY,
|
||||
@ -1244,7 +1248,7 @@ def _assemble_lead_agent(
|
||||
)
|
||||
chat_model = create_chat_model(name=model_name, thinking_enabled=thinking_enabled, app_config=resolved_app_config, attach_tracing=False)
|
||||
raw_tools = get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, app_config=resolved_app_config, chat_model=chat_model) + [setup_agent]
|
||||
configured_tools = raw_tools
|
||||
configured_tools = restrict_batch_continuation(raw_tools, available=batch_continuation_available)
|
||||
configured_tools = [tool for tool in configured_tools if tool.name not in interaction_policy.disabled_tool_names]
|
||||
authorization_candidates = [*configured_tools]
|
||||
if skill_setup.describe_skill_tool:
|
||||
@ -1415,7 +1419,7 @@ def _assemble_lead_agent(
|
||||
raise ValueError("A child model selection requires enabled subagents and a configured model name.")
|
||||
authorize_selected_model(selected_child_model, context=cfg, app_config=resolved_app_config)
|
||||
raw_tools = bind_selected_task_model(raw_tools, selected_child_model)
|
||||
configured_tools = raw_tools + extra_tools
|
||||
configured_tools = restrict_batch_continuation(raw_tools, available=batch_continuation_available) + extra_tools
|
||||
configured_tools = [tool for tool in configured_tools if tool.name not in interaction_policy.disabled_tool_names]
|
||||
authorization_candidates = [*configured_tools]
|
||||
if skill_setup.describe_skill_tool:
|
||||
|
||||
@ -0,0 +1,18 @@
|
||||
"""Persist the per-task opt-in to subagent delegation."""
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from deerflow.persistence.migrations._helpers import safe_add_column, safe_drop_column
|
||||
|
||||
revision = "0063_scheduled_task_subagents"
|
||||
down_revision = "0062_mcp_agent_grants"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
safe_add_column("scheduled_tasks", sa.Column("subagent_enabled", sa.Boolean(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
safe_drop_column("scheduled_tasks", "subagent_enabled")
|
||||
@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from datetime import UTC, datetime
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, DateTime, Integer, String, Text
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
@ -26,6 +26,7 @@ class ScheduledTaskRow(Base):
|
||||
standing_notes: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
|
||||
context_mode: Mapped[str] = mapped_column(String(32), default="fresh_thread_per_run")
|
||||
assistant_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
subagent_enabled: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
prompt: Mapped[str] = mapped_column(Text)
|
||||
schedule_type: Mapped[str] = mapped_column(String(16))
|
||||
|
||||
@ -112,6 +112,7 @@ class ScheduledTaskRepository:
|
||||
@staticmethod
|
||||
def _row_to_dict(row: ScheduledTaskRow) -> dict[str, Any]:
|
||||
data = row.to_dict(exclude={"last_occurrence_seq", "unmet_streak_after_seq"})
|
||||
data["subagent_enabled"] = row.subagent_enabled is True
|
||||
data["schedule_spec"] = _canonical_schedule_spec(row.schedule_type, row.schedule_spec)
|
||||
for key in _TIMESTAMP_KEYS:
|
||||
if data.get(key) is not None:
|
||||
@ -163,6 +164,7 @@ class ScheduledTaskRepository:
|
||||
standing_notes: list[str] | None = None,
|
||||
stop_condition: str | None = None,
|
||||
notification_group_connection_id: str | None = None,
|
||||
subagent_enabled: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
if goal_objective is not None:
|
||||
normalize_goal_objective(goal_objective)
|
||||
@ -186,6 +188,7 @@ class ScheduledTaskRepository:
|
||||
standing_notes=list(standing_notes) if standing_notes is not None else None,
|
||||
context_mode=context_mode,
|
||||
assistant_id=assistant_id,
|
||||
subagent_enabled=subagent_enabled,
|
||||
title=title,
|
||||
prompt=prompt,
|
||||
schedule_type=schedule_type,
|
||||
|
||||
@ -57,12 +57,11 @@ to the runtime hard gate so the model never conflates deterministic
|
||||
execution evidence with task acceptance.
|
||||
|
||||
All functions are pure (sandbox IO only through the injected reader/prober);
|
||||
the async caller offloads the whole check with ``asyncio.to_thread``.
|
||||
the async caller offloads the whole check and drains it on cancellation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import csv
|
||||
@ -461,7 +460,12 @@ def _probe_file_size(runtime: Any, resolved: str, thread_data: Mapping[str, Any]
|
||||
try:
|
||||
from deerflow.sandbox.tools import _resolve_local_read_path, ensure_sandbox_initialized, is_local_sandbox
|
||||
|
||||
sandbox = None if is_local_sandbox(runtime) else ensure_sandbox_initialized(runtime)
|
||||
if is_local_sandbox(runtime):
|
||||
# Lazy acquisition followed a lexical scope check. Apply the
|
||||
# same canonical scope check as for an initialized local sandbox.
|
||||
if sandbox is not None and _resolve_scoped_path(resolved, thread_data, resolve_symlinks=True) is None:
|
||||
return None
|
||||
host_path = _resolve_local_read_path(resolved, thread_data)
|
||||
if host_path == resolved:
|
||||
# A mount-mapped virtual path: only the provider's mount
|
||||
@ -469,7 +473,7 @@ def _probe_file_size(runtime: Any, resolved: str, thread_data: Mapping[str, Any]
|
||||
return None
|
||||
stat_result = os.stat(host_path)
|
||||
return stat_result.st_size if stat.S_ISREG(stat_result.st_mode) else None
|
||||
sandbox = ensure_sandbox_initialized(runtime)
|
||||
assert sandbox is not None
|
||||
root = "/".join(resolved.split("/")[:4]) # the /mnt/user-data/{workspace|outputs} mount root
|
||||
output = sandbox.execute_command(
|
||||
f"/usr/bin/env -i /bin/sh -c {shlex.quote(_SIZE_PROBE_INNER_SCRIPT)} probe {shlex.quote(resolved)} {shlex.quote(root)}",
|
||||
@ -805,23 +809,19 @@ def _check_file_leaf(
|
||||
if family == "file_csv_columns" and csv_columns is None:
|
||||
base["detail"] = "csv-columns requires a nonempty JSON array of unique nonempty strings"
|
||||
return base
|
||||
if admission_denied is True:
|
||||
base["detail"] = "sandbox access denied; file unverified"
|
||||
return base
|
||||
local = is_local_sandbox(runtime)
|
||||
if local:
|
||||
if admission_denied is True:
|
||||
# The async entry point already denied sandbox:execute on the
|
||||
# event loop that owns loop-affine providers; do not reconstruct
|
||||
# the provider in this worker thread.
|
||||
if local and admission_denied is None:
|
||||
from deerflow.authz.sandbox_authz import authorize_sandbox_execution, safe_app_config
|
||||
|
||||
# Authorize before canonicalization or metadata probes.
|
||||
try:
|
||||
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
|
||||
except SandboxError:
|
||||
base["detail"] = "sandbox access denied; file unverified"
|
||||
return base
|
||||
if admission_denied is None:
|
||||
from deerflow.authz.sandbox_authz import authorize_sandbox_execution, safe_app_config
|
||||
|
||||
# Authorize before canonicalization or metadata probes can disclose file existence or size.
|
||||
try:
|
||||
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
|
||||
except SandboxError:
|
||||
base["detail"] = "sandbox access denied; file unverified"
|
||||
return base
|
||||
|
||||
# Symlink escapes are a local-sandbox concern (host-visible links); remote
|
||||
# providers resolve paths inside the sandbox where the parent cannot
|
||||
@ -2200,13 +2200,13 @@ def check_acceptance_criteria(
|
||||
"""Check each decidable criterion against recorded execution evidence.
|
||||
|
||||
Returns ``None`` when no usable criterion exists (caller stamps nothing).
|
||||
Synchronous: the async call site offloads via ``asyncio.to_thread`` —
|
||||
``content_reader`` performs sandbox IO. The shared normalizer keeps the
|
||||
The async call site offloads the synchronous sandbox IO and drains it
|
||||
before cleanup. The shared normalizer keeps the
|
||||
checked list identical to the persisted and delegated list.
|
||||
|
||||
``admission_denied`` carries a ``sandbox:execute`` decision already made
|
||||
by an async entry point (``check_acceptance_criteria_async``): ``True``
|
||||
denies every local file leaf without probing, ``False`` skips the worker
|
||||
denies every file leaf without probing, ``False`` skips the worker
|
||||
gate, and ``None`` (default) runs the live gate per leaf. The worker never
|
||||
reconstructs a loop-affine authorization provider off the event loop.
|
||||
"""
|
||||
@ -2270,20 +2270,21 @@ async def check_acceptance_criteria_async(
|
||||
Custom authorization providers may create loop-affine clients in
|
||||
``__init__``, so the admission decision must be made here — before the
|
||||
checklist is offloaded to a worker — not reconstructed inside the worker.
|
||||
A denied decision travels with the offloaded call and degrades every local
|
||||
file leaf to UNVERIFIED without probing; the worker performs no second
|
||||
provider construction.
|
||||
The decision applies even when the sandbox kind is unknown before lazy
|
||||
acquisition. Drain the checklist before the parent releases its sandbox.
|
||||
"""
|
||||
from deerflow.authz.sandbox_authz import authorize_sandbox_execution_async, safe_app_config_async
|
||||
from deerflow.sandbox.exceptions import SandboxError
|
||||
from deerflow.sandbox.tools import _SANDBOX_AUTHORIZATION_CHECKED, is_local_sandbox
|
||||
from deerflow.sandbox.lease import run_sync_lifecycle_operation
|
||||
from deerflow.sandbox.tools import _SANDBOX_AUTHORIZATION_CHECKED
|
||||
|
||||
criteria = normalize_acceptance_criteria(acceptance_criteria)
|
||||
if not criteria:
|
||||
return None
|
||||
|
||||
admission_denied: bool | None = None
|
||||
if is_local_sandbox(runtime) and any(parse_file_criterion(criterion) is not None for criterion in criteria):
|
||||
token = None
|
||||
if any(parse_file_criterion(criterion) is not None for criterion in criteria):
|
||||
try:
|
||||
await authorize_sandbox_execution_async(
|
||||
context=getattr(runtime, "context", None) or {},
|
||||
@ -2293,34 +2294,21 @@ async def check_acceptance_criteria_async(
|
||||
admission_denied = True
|
||||
else:
|
||||
admission_denied = False
|
||||
token = _SANDBOX_AUTHORIZATION_CHECKED.set(True)
|
||||
|
||||
if admission_denied is False:
|
||||
# Carry the allow decision into the worker: the content read's own
|
||||
# re-authorization (ensure_sandbox_initialized) must not reconstruct a
|
||||
# loop-affine provider off the loop. Context variables propagate into
|
||||
# asyncio.to_thread workers, same handoff as sandbox tool scopes.
|
||||
token = _SANDBOX_AUTHORIZATION_CHECKED.set(True)
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
check_acceptance_criteria,
|
||||
criteria,
|
||||
runtime=runtime,
|
||||
thread_data=thread_data,
|
||||
bash_executions=bash_executions,
|
||||
admission_denied=False,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
return await run_sync_lifecycle_operation(
|
||||
check_acceptance_criteria,
|
||||
criteria,
|
||||
runtime=runtime,
|
||||
thread_data=thread_data,
|
||||
bash_executions=bash_executions,
|
||||
admission_denied=admission_denied,
|
||||
)
|
||||
finally:
|
||||
if token is not None:
|
||||
_SANDBOX_AUTHORIZATION_CHECKED.reset(token)
|
||||
|
||||
return await asyncio.to_thread(
|
||||
check_acceptance_criteria,
|
||||
criteria,
|
||||
runtime=runtime,
|
||||
thread_data=thread_data,
|
||||
bash_executions=bash_executions,
|
||||
admission_denied=admission_denied,
|
||||
)
|
||||
|
||||
|
||||
def validate_acceptance_verdict(value: object) -> AcceptanceVerdict | None:
|
||||
"""Structural check for a persisted verdict (read side trusts nothing)."""
|
||||
|
||||
@ -14,9 +14,11 @@ from typing import Annotated, Any, cast
|
||||
from deerflow_extension_api.agent_runs import AGENT_RUNS_CONTEXT_KEY
|
||||
from langchain.tools import InjectedToolCallId, tool
|
||||
from langchain_core.messages import ToolMessage
|
||||
from langchain_core.tools import BaseTool, StructuredTool
|
||||
from langgraph.types import Command
|
||||
from pydantic import BaseModel, Field, StrictInt
|
||||
from pydantic import BaseModel, Field, StrictInt, create_model
|
||||
|
||||
from deerflow.agents.interaction_policy import resolve_run_interaction_policy
|
||||
from deerflow.authz.principal import normalize_authz_attributes
|
||||
from deerflow.config.tool_output_config import ToolOutputConfig
|
||||
from deerflow.knowledge_scope import KNOWLEDGE_SCOPE_RUNTIME_KEY, execution_scope
|
||||
@ -120,6 +122,13 @@ def bind_batch_tools(
|
||||
return tuple(_bind_batch_tool(tool, provider, app_config) for tool in (batch_task, batch_status, cancel_batch, read_batch_result))
|
||||
|
||||
|
||||
def restrict_batch_continuation(tools: list[BaseTool], *, available: bool) -> list[BaseTool]:
|
||||
"""Hide the follow-up argument from the model when authority is absent."""
|
||||
if available:
|
||||
return tools
|
||||
return [_BatchTaskWithoutAdvertisedContinuation(**dict(tool)) if tool.name == batch_task.name and tool.args_schema is batch_task.args_schema else tool for tool in tools]
|
||||
|
||||
|
||||
def _result(tool_call_id: str, *, content: str, batch: dict[str, Any] | None = None, error: bool = False) -> Command:
|
||||
metadata: dict[str, Any] = {"subagent_batch_error": error}
|
||||
if batch is not None:
|
||||
@ -229,6 +238,9 @@ async def batch_task(
|
||||
error=True,
|
||||
)
|
||||
|
||||
interaction_policy = resolve_run_interaction_policy({"configurable": runtime.config.get("configurable", {}) if runtime is not None else {}, "context": context})
|
||||
config = interaction_policy.apply_to_subagent(config)
|
||||
|
||||
parent_skills = metadata.get("available_skills")
|
||||
if parent_skills is not None:
|
||||
config = replace(config, skills=_merge_skill_allowlists(list(parent_skills), config.skills))
|
||||
@ -303,6 +315,17 @@ async def batch_task(
|
||||
)
|
||||
|
||||
|
||||
_BATCH_MODEL_SCHEMA = cast(type[BaseModel], batch_task.tool_call_schema)
|
||||
_BATCH_MODEL_FIELDS: dict[str, Any] = {name: (field.annotation, field) for name, field in _BATCH_MODEL_SCHEMA.model_fields.items() if name != "continuation"}
|
||||
_BATCH_MODEL_SCHEMA_WITHOUT_CONTINUATION = create_model(batch_task.name, __doc__=batch_task.description, **_BATCH_MODEL_FIELDS)
|
||||
|
||||
|
||||
class _BatchTaskWithoutAdvertisedContinuation(StructuredTool):
|
||||
@property
|
||||
def tool_call_schema(self) -> type[BaseModel]:
|
||||
return _BATCH_MODEL_SCHEMA_WITHOUT_CONTINUATION
|
||||
|
||||
|
||||
@tool("batch_status", parse_docstring=True)
|
||||
async def batch_status(runtime: Runtime, batch_id: str) -> str:
|
||||
"""Return a compact durable batch progress snapshot.
|
||||
|
||||
@ -18,6 +18,7 @@ from langchain_core.messages import ToolMessage
|
||||
from langgraph.config import get_stream_writer
|
||||
from langgraph.types import Command
|
||||
|
||||
from deerflow.agents.interaction_policy import resolve_run_interaction_policy
|
||||
from deerflow.agents.middlewares.receipt_verification import verify_receipt_citations
|
||||
from deerflow.authz.principal import normalize_authz_attributes
|
||||
from deerflow.community.ragflow.sources import cited_source_artifact
|
||||
@ -35,7 +36,7 @@ from deerflow.sandbox.security import LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE, is_h
|
||||
from deerflow.subagents import SubagentExecutor, get_available_subagent_names, get_subagent_config
|
||||
from deerflow.subagents.acceptance_checks import check_acceptance_criteria_async, render_acceptance_section
|
||||
from deerflow.subagents.capacity import SubagentExecutionCapacity, configured_subagent_queue_timeout_seconds
|
||||
from deerflow.subagents.config import resolve_subagent_model_name
|
||||
from deerflow.subagents.config import SubagentConfig, resolve_subagent_model_name
|
||||
from deerflow.subagents.context_snapshot import ParentContextSnapshot
|
||||
from deerflow.subagents.executor import (
|
||||
SubagentStatus,
|
||||
@ -106,7 +107,7 @@ def _preflight_delegation_checks(
|
||||
context_mode: str,
|
||||
runtime_app_config: Any | None,
|
||||
allowed_subagents: Any | None,
|
||||
) -> tuple[Any | None, str | None]:
|
||||
) -> tuple[SubagentConfig, None] | tuple[None, str]:
|
||||
"""Read-only preflight (validate-then-mutate).
|
||||
|
||||
Runs every precondition check in one pass before any side-effecting
|
||||
@ -133,8 +134,6 @@ def _preflight_delegation_checks(
|
||||
after all checks pass, so a rejected recovery request does not consume the
|
||||
source task (see issue #7633).
|
||||
"""
|
||||
config: Any | None = None
|
||||
|
||||
if context_mode not in {"isolated", "snapshot"}:
|
||||
return None, f"Unknown context_mode '{context_mode}'. Use isolated or snapshot."
|
||||
|
||||
@ -1002,6 +1001,7 @@ async def task_tool(
|
||||
status="failed",
|
||||
error=preflight_error,
|
||||
)
|
||||
assert preflight_config is not None
|
||||
config = preflight_config
|
||||
# Rejected delegations must not serialize the retained history. Capture
|
||||
# after delegation validation, before child setup (including tool loading).
|
||||
@ -1104,6 +1104,9 @@ async def task_tool(
|
||||
if overrides:
|
||||
config = replace(config, **overrides)
|
||||
|
||||
interaction_policy = resolve_run_interaction_policy({"configurable": runtime.config.get("configurable", {}) if runtime is not None else {}, "context": parent_context})
|
||||
config = interaction_policy.apply_to_subagent(config)
|
||||
|
||||
# Get available tools (excluding task tool to prevent nesting)
|
||||
# Lazy import to avoid circular dependency
|
||||
from deerflow.tools import get_available_tools
|
||||
|
||||
@ -608,16 +608,24 @@ class TestAsyncAdmission:
|
||||
|
||||
@pytest.mark.parametrize("allow", [True, False])
|
||||
@pytest.mark.parametrize("content", [None, b"x" * 60_000], ids=["missing", "large"])
|
||||
def test_loop_affine_provider_decides_on_the_loop(self, tmp_path, monkeypatch, allow, content):
|
||||
@pytest.mark.parametrize("initialized", [True, False], ids=["initialized", "lazy"])
|
||||
def test_loop_affine_provider_decides_on_the_loop(self, tmp_path, monkeypatch, allow, content, initialized):
|
||||
"""Metadata-only leaves keep their definitive verdicts under a provider
|
||||
that can only be constructed on a running event loop."""
|
||||
import asyncio
|
||||
|
||||
from deerflow.config import paths
|
||||
from deerflow.sandbox.local import LocalSandboxProvider
|
||||
|
||||
monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path / "home"))
|
||||
monkeypatch.setattr(paths, "_paths", None)
|
||||
constructed_on = self._install_loop_affine_provider(monkeypatch, allow=allow)
|
||||
provider = LocalSandboxProvider()
|
||||
monkeypatch.setattr("deerflow.sandbox.tools.get_sandbox_provider", lambda: provider)
|
||||
if content is not None:
|
||||
(tmp_path / "report.md").write_bytes(content)
|
||||
runtime = SimpleNamespace(
|
||||
state={"sandbox": {"sandbox_id": "local"}},
|
||||
state={"sandbox": {"sandbox_id": "local"}} if initialized else {},
|
||||
context={"thread_id": "thread-1", "user_id": "user-1", "user_role": "user"},
|
||||
)
|
||||
|
||||
@ -667,6 +675,45 @@ class TestAsyncAdmission:
|
||||
assert leaf["detail"] == "sandbox access denied; file unverified"
|
||||
probe.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_acceptance_drains_file_probe(self, tmp_path, monkeypatch):
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from deerflow.subagents import acceptance_checks as checks
|
||||
|
||||
self._install_loop_affine_provider(monkeypatch, allow=True)
|
||||
loop = asyncio.get_running_loop()
|
||||
started = asyncio.Event()
|
||||
finish = threading.Event()
|
||||
cleaned_up = asyncio.Event()
|
||||
|
||||
def probe(*_args):
|
||||
loop.call_soon_threadsafe(started.set)
|
||||
assert finish.wait(timeout=5)
|
||||
raise FileNotFoundError
|
||||
|
||||
monkeypatch.setattr(checks, "_probe_file_size", probe)
|
||||
runtime = SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={"user_id": "user-1", "user_role": "user"})
|
||||
|
||||
async def check_then_cleanup():
|
||||
try:
|
||||
await check_acceptance_criteria_async(["file:report.md exists"], runtime=runtime, thread_data={"workspace_path": str(tmp_path)})
|
||||
finally:
|
||||
cleaned_up.set()
|
||||
|
||||
task = asyncio.create_task(check_then_cleanup())
|
||||
try:
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not cleaned_up.is_set()
|
||||
finally:
|
||||
finish.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert cleaned_up.is_set()
|
||||
|
||||
def test_evidence_only_criteria_skip_admission(self, monkeypatch):
|
||||
authorize = Mock(side_effect=AssertionError("evidence-only criteria need no sandbox admission"))
|
||||
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution_async", authorize)
|
||||
|
||||
@ -4,6 +4,7 @@ from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import ToolMessage
|
||||
from langchain_core.utils.function_calling import convert_to_openai_tool
|
||||
from langgraph.types import Command
|
||||
|
||||
from deerflow.mcp_scope import (
|
||||
@ -52,6 +53,20 @@ def _message(command: Command) -> ToolMessage:
|
||||
return messages[0]
|
||||
|
||||
|
||||
def test_batch_schema_advertises_continuation_only_with_run_capability():
|
||||
tools = list(tool_module.bind_batch_tools(AsyncMock()))
|
||||
limited = tool_module.restrict_batch_continuation(tools, available=False)
|
||||
interactive = tool_module.restrict_batch_continuation(tools, available=True)
|
||||
|
||||
def properties(bound_tools):
|
||||
batch = next(tool for tool in bound_tools if tool.name == "batch_task")
|
||||
return convert_to_openai_tool(batch)["function"]["parameters"]["properties"]
|
||||
|
||||
assert "continuation" in properties(interactive)
|
||||
assert properties(limited) == {name: field for name, field in properties(interactive).items() if name != "continuation"}
|
||||
assert "continuation" in properties(tools)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("thread_incarnation", "expected_present"),
|
||||
@ -87,8 +102,10 @@ async def test_batch_task_is_explicit_idempotent_submission(
|
||||
),
|
||||
)
|
||||
|
||||
runtime = _runtime(thread_incarnation)
|
||||
runtime.context["non_interactive"] = True
|
||||
command = await tool_module.batch_task.coroutine(
|
||||
runtime=_runtime(thread_incarnation),
|
||||
runtime=runtime,
|
||||
title="Process records",
|
||||
items=[
|
||||
BatchTaskItem(key="record-1", prompt="Process one"),
|
||||
@ -104,6 +121,7 @@ async def test_batch_task_is_explicit_idempotent_submission(
|
||||
request = submitter.submit.await_args.args[0]
|
||||
assert request.submission_key == "run-1:call-1"
|
||||
assert request.execution_spec["mcp_plugins"] == ["stable-plugin"]
|
||||
assert "ask_clarification" in request.execution_spec["subagent_config"]["disallowed_tools"]
|
||||
assert request.user_id == "user-1"
|
||||
assert [item["key"] for item in request.items] == ["record-1", "record-2"]
|
||||
assert request.max_live_items == 20
|
||||
|
||||
@ -4604,13 +4604,14 @@ async def test_start_run_peer_idempotent_reuse_does_not_reject_later_runs_after_
|
||||
assert follow_up.run_id != first.run_id
|
||||
|
||||
|
||||
def test_launch_scheduled_thread_run_marks_context_non_interactive(_stub_app_config):
|
||||
@pytest.mark.parametrize("options", [{}, {"subagent_enabled": False}, {"subagent_enabled": True}])
|
||||
def test_launch_scheduled_thread_run_marks_context_non_interactive(_stub_app_config, options):
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.gateway.routers.thread_runs import RunCreateRequest
|
||||
from app.gateway.services import launch_scheduled_thread_run
|
||||
from app.gateway.services import get_trusted_internal_owner_user_id, launch_scheduled_thread_run, merge_run_context_overrides
|
||||
|
||||
async def _scenario():
|
||||
captured: dict[str, object] = {}
|
||||
@ -4619,6 +4620,10 @@ def test_launch_scheduled_thread_run_marks_context_non_interactive(_stub_app_con
|
||||
captured["body"] = body
|
||||
captured["thread_id"] = thread_id
|
||||
captured["context"] = body.context
|
||||
captured["trusted_owner"] = get_trusted_internal_owner_user_id(request)
|
||||
config: dict = {}
|
||||
merge_run_context_overrides(config, body.context, internal=True)
|
||||
captured["runtime_config"] = config
|
||||
captured["scheduled_task_runtime"] = scheduled_task_runtime
|
||||
captured["metadata"] = body.metadata
|
||||
captured["idempotency_key"] = idempotency_key
|
||||
@ -4637,6 +4642,7 @@ def test_launch_scheduled_thread_run_marks_context_non_interactive(_stub_app_con
|
||||
"scheduled_task_id": "task-1",
|
||||
"scheduled_task_run_id": "task-run-1",
|
||||
},
|
||||
**options,
|
||||
)
|
||||
return captured, result
|
||||
|
||||
@ -4645,7 +4651,12 @@ def test_launch_scheduled_thread_run_marks_context_non_interactive(_stub_app_con
|
||||
assert captured["thread_id"] == "thread-scheduled"
|
||||
assert isinstance(captured["body"], RunCreateRequest)
|
||||
assert captured["body"].config == {"recursion_limit": 1000}
|
||||
assert captured["context"] == {"non_interactive": True, "user_id": "user-1"}
|
||||
expected_context = {"non_interactive": True, "user_id": "user-1"}
|
||||
if options.get("subagent_enabled"):
|
||||
expected_context["subagent_enabled"] = True
|
||||
assert captured["context"] == expected_context
|
||||
assert captured["trusted_owner"] == "user-1"
|
||||
assert captured["runtime_config"]["context"] == expected_context
|
||||
assert captured["scheduled_task_runtime"] == {"task_id": "task-1", "occurrence_id": "task-run-1", "user_id": "user-1"}
|
||||
assert captured["metadata"] == {
|
||||
"scheduled_task_id": "task-1",
|
||||
|
||||
@ -1607,10 +1607,11 @@ def test_request_thinking_overrides_agent_default(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mcp_plugins", [None, [], ["installed-plugin"]])
|
||||
def test_empty_allowed_subagents_disables_requested_delegation(monkeypatch, mcp_plugins):
|
||||
@pytest.mark.parametrize("allowed, enabled", [([], False), (["planner"], True)])
|
||||
def test_scheduled_delegation_respects_agent_allowlist(monkeypatch, mcp_plugins, allowed, enabled):
|
||||
"""A request switch cannot widen an explicit Custom Agent hard deny."""
|
||||
app_config = _make_app_config([_make_model("agent-model", supports_thinking=False)])
|
||||
agent_config = _make_agent_config(model="agent-model", allowed_subagents=[])
|
||||
agent_config = _make_agent_config(model="agent-model", allowed_subagents=allowed)
|
||||
agent_config.mcp_plugins = mcp_plugins
|
||||
|
||||
import deerflow.tools as tools_module
|
||||
@ -1626,6 +1627,8 @@ def test_empty_allowed_subagents_disables_requested_delegation(monkeypatch, mcp_
|
||||
"context": {
|
||||
"agent_name": "researcher",
|
||||
"subagent_enabled": True,
|
||||
"non_interactive": True,
|
||||
"user_id": "owner",
|
||||
}
|
||||
}
|
||||
lead_agent_module._make_lead_agent(config, app_config=app_config)
|
||||
@ -1634,14 +1637,14 @@ def test_empty_allowed_subagents_disables_requested_delegation(monkeypatch, mcp_
|
||||
model_name="agent-model",
|
||||
groups=None,
|
||||
mcp_plugins=mcp_plugins,
|
||||
subagent_enabled=False,
|
||||
subagent_enabled=enabled,
|
||||
include_conversation_reader=False,
|
||||
app_config=app_config,
|
||||
chat_model=ANY,
|
||||
)
|
||||
assert config["context"]["subagent_enabled"] is False
|
||||
assert config["configurable"]["subagent_enabled"] is False
|
||||
assert config["metadata"]["allowed_subagents"] == []
|
||||
assert config["context"]["subagent_enabled"] is enabled
|
||||
assert config["configurable"]["subagent_enabled"] is enabled
|
||||
assert config["metadata"]["allowed_subagents"] == allowed
|
||||
assert config["metadata"]["mcp_plugins"] == mcp_plugins
|
||||
|
||||
|
||||
|
||||
@ -21,7 +21,8 @@ from deerflow.persistence.mcp_oauth_tokens import McpOAuthTokenRow
|
||||
from deerflow.persistence.postgres_schema import build_asyncpg_connect_args
|
||||
|
||||
REVISION = "0047_mcp_oauth_tokens"
|
||||
HEAD = "0062_mcp_agent_grants"
|
||||
HEAD = "0063_scheduled_task_subagents"
|
||||
MCP_AGENT_GRANTS_REVISION = "0062_mcp_agent_grants"
|
||||
COORDINATOR_REVISION = "0061_coordination_coordinator"
|
||||
COORDINATION_RUN_SETTINGS_REVISION = "0060_coordination_run_settings"
|
||||
COORDINATION_GRANTS_REVISION = "0059_coordination_grants"
|
||||
@ -52,7 +53,8 @@ async def test_0047_remains_in_the_single_migration_chain():
|
||||
assert bootstrap._get_head_revision() == HEAD
|
||||
script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR))
|
||||
assert script.get_heads() == [HEAD]
|
||||
assert script.get_revision(HEAD).down_revision == COORDINATOR_REVISION
|
||||
assert script.get_revision(HEAD).down_revision == MCP_AGENT_GRANTS_REVISION
|
||||
assert script.get_revision(MCP_AGENT_GRANTS_REVISION).down_revision == COORDINATOR_REVISION
|
||||
assert script.get_revision(COORDINATOR_REVISION).down_revision == COORDINATION_RUN_SETTINGS_REVISION
|
||||
assert script.get_revision(COORDINATION_RUN_SETTINGS_REVISION).down_revision == COORDINATION_GRANTS_REVISION
|
||||
assert script.get_revision(COORDINATION_GRANTS_REVISION).down_revision == BROWSER_OAUTH_REVISION
|
||||
|
||||
@ -28,7 +28,8 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from alembic import command
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from support.postgres import asyncpg_test_url
|
||||
|
||||
# Pre-import models so Base.metadata is populated before bootstrap reads it.
|
||||
@ -46,6 +47,7 @@ from deerflow.persistence.bootstrap import (
|
||||
)
|
||||
from deerflow.persistence.migrations._helpers import _normalize_default
|
||||
from deerflow.persistence.postgres_schema import build_asyncpg_connect_args
|
||||
from deerflow.persistence.scheduled_tasks import ScheduledTaskRepository
|
||||
|
||||
# Mark only async tests via the decorator below; module-level pytestmark would
|
||||
# spuriously warn for the sync ``TestDecideState`` cases.
|
||||
@ -386,6 +388,56 @@ async def _drift_engine(tmp_path: Path, backend: str):
|
||||
return engine, schema
|
||||
|
||||
|
||||
@asyncio_test
|
||||
@pytest.mark.parametrize("backend", ["sqlite", "postgres"])
|
||||
async def test_scheduled_task_delegation_upgrade_retry_and_downgrade(tmp_path, backend):
|
||||
previous = "0062_mcp_agent_grants"
|
||||
revision = "0063_scheduled_task_subagents"
|
||||
engine, schema = await _drift_engine(tmp_path, backend)
|
||||
try:
|
||||
cfg = _get_alembic_config(engine, postgres_schema=schema or None)
|
||||
await asyncio.to_thread(command.upgrade, cfg, previous)
|
||||
insert = sa.text(
|
||||
"INSERT INTO scheduled_tasks "
|
||||
"(id, user_id, context_mode, title, prompt, schedule_type, schedule_spec, timezone, status, "
|
||||
"overlap_policy, run_count, last_occurrence_seq, created_at, updated_at) "
|
||||
"VALUES ('existing', 'owner', 'fresh_thread_per_run', 'Report', 'Write report', 'cron', "
|
||||
"'{}', 'UTC', 'paused', 'enqueue', 4, 4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
)
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(insert)
|
||||
|
||||
await asyncio.to_thread(command.upgrade, cfg, revision)
|
||||
repo = ScheduledTaskRepository(async_sessionmaker(engine, expire_on_commit=False))
|
||||
task = await repo.get("existing", user_id="owner")
|
||||
assert task["subagent_enabled"] is False
|
||||
assert task["run_count"] == 4
|
||||
|
||||
await repo.update("existing", user_id="owner", updates={"subagent_enabled": True})
|
||||
await asyncio.to_thread(command.stamp, cfg, previous)
|
||||
await asyncio.to_thread(command.upgrade, cfg, revision)
|
||||
assert (await repo.get("existing", user_id="owner"))["subagent_enabled"] is True
|
||||
|
||||
await asyncio.to_thread(command.downgrade, cfg, previous)
|
||||
async with engine.connect() as conn:
|
||||
columns = await conn.run_sync(lambda sync: sa.inspect(sync).get_columns("scheduled_tasks"))
|
||||
assert "subagent_enabled" not in {column["name"] for column in columns}
|
||||
row = (await conn.execute(sa.text("SELECT title, run_count FROM scheduled_tasks WHERE id = 'existing'"))).one()
|
||||
assert row == ("Report", 4)
|
||||
|
||||
await asyncio.to_thread(command.upgrade, cfg, revision)
|
||||
task = await repo.get("existing", user_id="owner")
|
||||
assert task["subagent_enabled"] is False
|
||||
assert task["run_count"] == 4
|
||||
finally:
|
||||
try:
|
||||
if schema:
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(sa.text(f'DROP SCHEMA "{schema}" CASCADE'))
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def _seed_at_revision(revision: str, *, drop_version_row: bool):
|
||||
async def seed(engine, schema: str) -> None:
|
||||
await asyncio.to_thread(_upgrade, _get_alembic_config(engine, postgres_schema=schema), revision)
|
||||
|
||||
@ -1093,6 +1093,40 @@ def _create_request(**overrides):
|
||||
return scheduled_tasks.ScheduledTaskCreateRequest(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("options", [{}, {"subagent_enabled": False}, {"subagent_enabled": True}])
|
||||
async def test_delegation_setting_create_patch_and_get(tmp_path, monkeypatch, options):
|
||||
config = DatabaseConfig(backend="sqlite", sqlite_dir=str(tmp_path))
|
||||
await init_engine_from_config(config)
|
||||
try:
|
||||
repo = ScheduledTaskRepository(get_session_factory())
|
||||
task = await _call_create(_create_request(**options), repo=repo)
|
||||
assert task["subagent_enabled"] is options.get("subagent_enabled", False)
|
||||
task_id = task["id"]
|
||||
|
||||
for enabled in (True, False):
|
||||
body = scheduled_tasks.ScheduledTaskUpdateRequest(subagent_enabled=enabled)
|
||||
assert (await _call_update(repo, task_id, body))["subagent_enabled"] is enabled
|
||||
for unchanged in (
|
||||
scheduled_tasks.ScheduledTaskUpdateRequest(title="Updated title"),
|
||||
scheduled_tasks.ScheduledTaskUpdateRequest(subagent_enabled=None),
|
||||
):
|
||||
assert (await _call_update(repo, task_id, unchanged))["subagent_enabled"] is enabled
|
||||
|
||||
await _call_update(repo, task_id, scheduled_tasks.ScheduledTaskUpdateRequest(subagent_enabled=True))
|
||||
finally:
|
||||
await close_engine()
|
||||
|
||||
await init_engine_from_config(config)
|
||||
try:
|
||||
monkeypatch.setattr(scheduled_tasks, "get_scheduled_task_repo", lambda _: ScheduledTaskRepository(get_session_factory()))
|
||||
monkeypatch.setattr(scheduled_tasks, "get_optional_user_from_request", AsyncMock(return_value=SimpleNamespace(id="user-1")))
|
||||
response = await call_unwrapped(scheduled_tasks.get_scheduled_task, task_id=task_id, request=SimpleNamespace())
|
||||
assert response["subagent_enabled"] is True
|
||||
finally:
|
||||
await close_engine()
|
||||
|
||||
|
||||
async def _seed_task(repo: _Repo | ScheduledTaskRepository, **overrides):
|
||||
kwargs = {
|
||||
"task_id": "task-1",
|
||||
@ -1905,12 +1939,14 @@ def test_is_scheduler_running_reads_the_service_of_this_process():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_reports_outcome_thread_and_an_already_waiting_run(http):
|
||||
await _seed(http.repo, next_run_at=datetime.now(UTC) + timedelta(hours=1))
|
||||
await _seed(http.repo, next_run_at=datetime.now(UTC) + timedelta(hours=1), subagent_enabled=True)
|
||||
launched = await http.client.post("/api/scheduled-tasks/task-l/trigger")
|
||||
assert launched.status_code == 200, launched.text
|
||||
body = launched.json()
|
||||
assert (body["id"], body["triggered"], body["outcome"], body["existing"]) == ("task-l", True, "launched", False)
|
||||
assert body["thread_id"] == http.launches[0]["thread_id"]
|
||||
assert http.launches[0]["subagent_enabled"] is True
|
||||
assert http.launches[0]["owner_user_id"] == OWNER
|
||||
await _seed(http.repo, "task-q", next_run_at=datetime.now(UTC) + timedelta(hours=1))
|
||||
async with http.sf() as session:
|
||||
session.add(occurrence("waiting", "task-q", seq=1, status="queued", accounted=False, thread_id="thread-waiting"))
|
||||
|
||||
@ -42,9 +42,9 @@ async def scheduler(tmp_path):
|
||||
await close_engine()
|
||||
|
||||
|
||||
async def create_task(tasks, **extra):
|
||||
async def create_task(tasks, *, task_id="task-a", **extra):
|
||||
return await tasks.create(
|
||||
task_id="task-a",
|
||||
task_id=task_id,
|
||||
user_id="owner",
|
||||
thread_id=None,
|
||||
context_mode="fresh_thread_per_run",
|
||||
@ -78,6 +78,42 @@ async def dispatch_scheduled(tasks, service):
|
||||
return await service.dispatch_task(claimed[0], now=now, trigger="scheduled")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("trigger", ["manual", "scheduled"])
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
async def test_dispatch_uses_stored_delegation_setting(scheduler, trigger, enabled):
|
||||
sf, tasks, _, service, launches, _ = scheduler
|
||||
await create_task(tasks, subagent_enabled=enabled)
|
||||
reopened = ScheduledTaskRepository(sf)
|
||||
task = await reopened.get("task-a", user_id="owner")
|
||||
assert task["subagent_enabled"] is enabled
|
||||
if trigger == "scheduled":
|
||||
await service.run_once(now=datetime.now(UTC))
|
||||
else:
|
||||
result = await service.dispatch_task(task, now=datetime.now(UTC), trigger="manual")
|
||||
assert result["outcome"] == "launched"
|
||||
|
||||
assert len(launches) == 1
|
||||
assert launches[0]["subagent_enabled"] is enabled
|
||||
assert launches[0]["owner_user_id"] == "owner"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_due_tasks_keep_independent_delegation_settings(scheduler):
|
||||
_, tasks, _, service, launches, _ = scheduler
|
||||
await create_task(tasks, subagent_enabled=True)
|
||||
await create_task(tasks, task_id="task-b")
|
||||
now = datetime.now(UTC)
|
||||
await service.run_once(now=now)
|
||||
await service.run_once(now=now)
|
||||
|
||||
assert len(launches) == 2
|
||||
assert {launch["metadata"]["scheduled_task_id"]: launch["subagent_enabled"] for launch in launches} == {
|
||||
"task-a": True,
|
||||
"task-b": False,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_launch_snapshots_goal_and_explicit_task_notes(scheduler):
|
||||
sf, tasks, _occurrences, service, launches, _deliveries = scheduler
|
||||
|
||||
@ -6,15 +6,21 @@ the original worker is then released and cleaned up normally.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from contextlib import ExitStack
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
||||
from langchain_core.messages import AIMessage, ToolMessage
|
||||
from langchain_core.utils.function_calling import convert_to_openai_tool
|
||||
from langgraph.graph import END, START, StateGraph
|
||||
from langgraph.prebuilt import ToolNode
|
||||
|
||||
@ -198,3 +204,236 @@ def test_fresh_gateway_boot_recovers_self_stop_once_after_running_snapshot(tmp_p
|
||||
print("Gateway stop recovery evidence: " + json.dumps(evidence, sort_keys=True))
|
||||
finally:
|
||||
reset_app_config()
|
||||
|
||||
|
||||
def _tool_call(name, **args):
|
||||
return AIMessage(content="", tool_calls=[{"name": name, "args": args, "id": name, "type": "tool_call"}])
|
||||
|
||||
|
||||
class _ScheduledReportModel(FakeMessagesListChatModel):
|
||||
schemas: dict = {}
|
||||
system_prompts: list[str] = []
|
||||
|
||||
def bind_tools(self, tools, **kwargs):
|
||||
self.schemas.update({tool.name: convert_to_openai_tool(tool)["function"]["parameters"] for tool in tools})
|
||||
return self
|
||||
|
||||
def _generate(self, messages, *args, **kwargs):
|
||||
self.system_prompts.extend(str(message.content) for message in messages if message.type == "system")
|
||||
if not self.responses:
|
||||
if any("There is no human available" in prompt and "smallest reasonable assumption" in prompt for prompt in self.system_prompts):
|
||||
self.responses = [
|
||||
_tool_call("write_file", path="/mnt/user-data/outputs/monthly.csv", content="month,total\n2026-11,42\n"),
|
||||
AIMessage(content="Report saved. Assumption: use the reporting month from the schedule."),
|
||||
]
|
||||
else:
|
||||
self.responses = [AIMessage(content="Which month should I use?")]
|
||||
return super()._generate(messages, *args, **kwargs)
|
||||
|
||||
|
||||
def _await_result(read, condition):
|
||||
for _ in range(300):
|
||||
result = read()
|
||||
if condition(result):
|
||||
return result
|
||||
time.sleep(0.1)
|
||||
pytest.fail(f"Run did not reach the expected state: {result!r}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def report_executor(monkeypatch):
|
||||
from deerflow import subagents
|
||||
from deerflow.subagents import batch_service
|
||||
|
||||
task_tool_module = importlib.import_module("deerflow.tools.builtins.task_tool")
|
||||
|
||||
# conftest loads a stub to break lightweight unit-test imports. Use the
|
||||
# production executor and reconnect its existing import sites here.
|
||||
name = "deerflow.subagents.executor"
|
||||
path = Path(__file__).parents[1] / "packages/harness/deerflow/subagents/executor.py"
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, name, module)
|
||||
spec.loader.exec_module(module)
|
||||
monkeypatch.setattr(subagents, "executor", module, raising=False)
|
||||
for target in (subagents, batch_service, task_tool_module):
|
||||
for attr in (
|
||||
"SubagentExecutor",
|
||||
"SubagentStatus",
|
||||
"cleanup_background_task",
|
||||
"force_cleanup_background_task",
|
||||
"get_background_task_result",
|
||||
"request_cancel_background_task",
|
||||
"run_on_isolated_subagent_loop",
|
||||
):
|
||||
if hasattr(target, attr):
|
||||
monkeypatch.setattr(target, attr, getattr(module, attr))
|
||||
try:
|
||||
yield module
|
||||
finally:
|
||||
module._shutdown_isolated_subagent_loop()
|
||||
|
||||
|
||||
@pytest.mark.no_auto_user
|
||||
@pytest.mark.parametrize(
|
||||
("trigger", "delegation", "arguments"),
|
||||
[
|
||||
("automatic", None, {}),
|
||||
("manual", None, {}),
|
||||
("automatic", "task", {}),
|
||||
("manual", "task", {}),
|
||||
("automatic", "batch_task", {}),
|
||||
("manual", "batch_task", {"continuation": None, "legacy_extra": True}),
|
||||
("manual", "batch_task", {"continuation": ""}),
|
||||
("manual", "batch_task", {"continuation": "Publish the report"}),
|
||||
("interactive", "batch_task", {"continuation": "Publish the report"}),
|
||||
("interactive", "ask_clarification", {}),
|
||||
],
|
||||
)
|
||||
def test_gateway_scheduled_subagent_contract(tmp_path, monkeypatch, trigger, delegation, arguments, report_executor):
|
||||
from app.gateway import deps
|
||||
from app.gateway.app import create_app
|
||||
from deerflow.agents.lead_agent import agent as lead_agent
|
||||
from deerflow.config import paths
|
||||
from deerflow.sandbox.local.local_sandbox import LocalSandbox
|
||||
|
||||
execute_command = LocalSandbox.execute_command
|
||||
|
||||
def execute_without_remote_probe(self, command, *args, **kwargs):
|
||||
# A local file check must work without GNU filesystem utilities.
|
||||
if (kwargs.get("env") or {}).get("_DEERFLOW_SIZE_PROBE"):
|
||||
raise OSError("Remote file probe is unavailable on this local host")
|
||||
return execute_command(self, command, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(LocalSandbox, "execute_command", execute_without_remote_probe)
|
||||
monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path / "home"))
|
||||
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "0")
|
||||
monkeypatch.setenv("AUTH_JWT_SECRET", "local-scheduled-report-test-secret")
|
||||
monkeypatch.setattr(ExtensionsConfig, "from_file", lambda *args, **kwargs: ExtensionsConfig())
|
||||
monkeypatch.setattr(paths, "_paths", None)
|
||||
monkeypatch.setattr(deps, "_cached_local_provider", None)
|
||||
monkeypatch.setattr(deps, "_cached_repo", None)
|
||||
config = AppConfig.model_validate(
|
||||
{
|
||||
"models": [{"name": "offline", "use": "langchain_openai:ChatOpenAI", "model": "offline", "api_key": "unused"}],
|
||||
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
|
||||
"tools": [{"name": "write_file", "group": "file:write", "use": "deerflow.sandbox.tools:write_file_tool"}],
|
||||
"database": {"backend": "sqlite", "sqlite_dir": str(tmp_path / "db")},
|
||||
"scheduler": {"enabled": True, "poll_interval_seconds": 300, "min_once_delay_seconds": 1},
|
||||
"subagent_batches": {"enabled": True, "poll_interval_seconds": 0.1},
|
||||
"memory": {"enabled": False},
|
||||
"title": {"enabled": False},
|
||||
"summarization": {"enabled": False},
|
||||
"skills": {"path": str(tmp_path / "skills")},
|
||||
"subagents": {"custom_agents": {"reporter": {"description": "Monthly reports", "system_prompt": "Generate the monthly report.", "disallowed_tools": [], "skills": []}}},
|
||||
}
|
||||
)
|
||||
criterion = "file:/mnt/user-data/outputs/monthly.csv non-empty"
|
||||
prompt = "Generate a CSV report. No month was supplied; the schedule normally reports November 2026."
|
||||
if delegation == "task":
|
||||
call = _tool_call("task", description="Monthly report", prompt=prompt, subagent_type="reporter", acceptance_criteria=[criterion])
|
||||
elif delegation == "batch_task":
|
||||
call = _tool_call("batch_task", title="Monthly report", items=[{"key": "report", "prompt": prompt, "acceptance_criteria": [criterion]}], subagent_type="reporter", **arguments)
|
||||
elif delegation == "ask_clarification":
|
||||
call = _tool_call("ask_clarification", question="Which month?", clarification_type="missing_info")
|
||||
else:
|
||||
call = AIMessage(content="Run completed without delegation.")
|
||||
lead = _ScheduledReportModel(responses=[call, AIMessage(content="Lead turn complete."), AIMessage(content="Follow-up published.")])
|
||||
child = _ScheduledReportModel(responses=[AIMessage(content="Finished interactive work.")] if trigger == "interactive" else [])
|
||||
child_builds = []
|
||||
|
||||
def child_model(**kwargs):
|
||||
child_builds.append(child)
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(lead_agent, "create_chat_model", lambda *args, **kwargs: lead)
|
||||
monkeypatch.setattr(report_executor, "create_chat_model", child_model)
|
||||
set_app_config(config)
|
||||
try:
|
||||
app = create_app()
|
||||
with ExitStack() as clients:
|
||||
client = clients.enter_context(TestClient(app))
|
||||
recover_batch = trigger == "automatic" and delegation == "batch_task"
|
||||
if recover_batch:
|
||||
client.portal.call(app.state.subagent_batch_service.stop)
|
||||
|
||||
def request(method, url, **kwargs):
|
||||
response = client.request(method, url, **kwargs)
|
||||
assert response.is_success, response.text
|
||||
return response.json()
|
||||
|
||||
request("POST", "/api/v1/auth/register", json={"email": "reporter@example.com", "password": "local-report-fixture-strong-372!"})
|
||||
client.headers["X-CSRF-Token"] = client.cookies["csrf_token"]
|
||||
if trigger == "interactive":
|
||||
thread_id = request("POST", "/api/threads", json={})["thread_id"]
|
||||
thread_url = f"/api/threads/{thread_id}"
|
||||
request("POST", f"{thread_url}/runs/wait", json={"assistant_id": "lead_agent", "input": {"messages": [{"role": "user", "content": prompt}]}, "context": {"subagent_enabled": True}})
|
||||
else:
|
||||
due = datetime.now(UTC) + timedelta(minutes=2)
|
||||
task_id = request(
|
||||
"POST", "/api/scheduled-tasks", json={"title": "Monthly report", "prompt": prompt, "schedule_type": "once", "schedule_spec": {"run_at": due.isoformat()}, "timezone": "UTC", "subagent_enabled": delegation is not None}
|
||||
)["id"]
|
||||
task_url = f"/api/scheduled-tasks/{task_id}"
|
||||
assert request("GET", task_url)["subagent_enabled"] is (delegation is not None)
|
||||
if trigger == "manual":
|
||||
request("POST", f"{task_url}/trigger")
|
||||
else:
|
||||
|
||||
async def tick():
|
||||
await app.state.scheduled_task_service.run_once(now=due + timedelta(seconds=1))
|
||||
|
||||
client.portal.call(tick)
|
||||
history = _await_result(lambda: request("GET", f"{task_url}/runs"), lambda rows: rows and rows[0]["status"] in TERMINAL_RUN_STATUSES)
|
||||
assert history[0]["status"] == "success", history
|
||||
thread_url = f"/api/threads/{history[0]['thread_id']}"
|
||||
if delegation is None:
|
||||
assert not {"task", "batch_task", "ask_clarification"} & lead.schemas.keys()
|
||||
assert not child_builds
|
||||
return
|
||||
assert delegation in lead.schemas
|
||||
messages = request("GET", f"{thread_url}/state")["values"]["messages"]
|
||||
receipt = next(message for message in messages if message.get("tool_call_id") == delegation)
|
||||
if delegation == "ask_clarification":
|
||||
assert receipt["artifact"]["human_input"]["question"] == "Which month?"
|
||||
return
|
||||
if delegation == "batch_task":
|
||||
assert ("continuation" in lead.schemas["batch_task"]["properties"]) is (trigger == "interactive")
|
||||
batch_url = f"{thread_url}/subagent-batches"
|
||||
batches = request("GET", batch_url)
|
||||
if trigger != "interactive" and arguments.get("continuation") is not None:
|
||||
expected = "must contain 1 to 4000 characters" if not arguments["continuation"] else "requires its originating Agent run authority"
|
||||
assert expected in receipt["content"]
|
||||
assert batches == []
|
||||
return
|
||||
assert len(batches) == 1, receipt
|
||||
batch_url = f"{batch_url}/{batches[0]['id']}"
|
||||
if recover_batch:
|
||||
assert request("GET", f"{batch_url}/items")[0]["status"] in {"queued", "pending"}
|
||||
assert not child_builds
|
||||
clients.close()
|
||||
monkeypatch.setattr(deps, "_cached_local_provider", None)
|
||||
monkeypatch.setattr(deps, "_cached_repo", None)
|
||||
client = clients.enter_context(TestClient(create_app()))
|
||||
request("POST", "/api/v1/auth/login/local", data={"username": "reporter@example.com", "password": "local-report-fixture-strong-372!"})
|
||||
client.headers["X-CSRF-Token"] = client.cookies["csrf_token"]
|
||||
items = _await_result(lambda: request("GET", f"{batch_url}/items"), lambda rows: rows and rows[0]["status"] in {"succeeded", "failed", "cancelled"})
|
||||
assert items[0]["status"] == "succeeded", items
|
||||
if trigger == "interactive":
|
||||
batch = _await_result(lambda: request("GET", batch_url), lambda row: row["continuation_status"] not in {"pending", "dispatching"})
|
||||
assert batch["continuation_status"] == "dispatched", batch
|
||||
follow_up_url = f"{thread_url}/runs/{batch['continuation_run_id']}"
|
||||
follow_up = _await_result(lambda: request("GET", follow_up_url), lambda run: run["status"] not in {"pending", "running"})
|
||||
assert follow_up["status"] == "success", follow_up
|
||||
assert len(request("GET", f"{thread_url}/subagent-batches")) == 1
|
||||
assert "ask_clarification" in child.schemas
|
||||
return
|
||||
verdict = items[0]["acceptance_verdict"]
|
||||
else:
|
||||
assert receipt["additional_kwargs"]["subagent_status"] == "completed", receipt
|
||||
verdict = receipt["additional_kwargs"]["subagent_acceptance_verdict"]
|
||||
assert "ask_clarification" not in child.schemas
|
||||
assert any("There is no human available" in message for message in child.system_prompts)
|
||||
assert verdict["all_hold"], verdict
|
||||
assert [path.read_text(encoding="utf-8") for path in (tmp_path / "home").rglob("monthly.csv")] == ["month,total\n2026-11,42\n"]
|
||||
finally:
|
||||
reset_app_config()
|
||||
|
||||
@ -675,13 +675,17 @@ def test_bound_task_tool_sync_path_uses_the_explicit_capacity(monkeypatch):
|
||||
assert captured["executor_kwargs"]["app_config"] is app_config
|
||||
|
||||
|
||||
def test_task_tool_forwards_channel_user_id_to_executor(monkeypatch):
|
||||
"""The IM-channel sender identity must survive delegation: in group chats
|
||||
one thread serves many senders, so a subagent's bash commands need the
|
||||
dispatching turn's channel_user_id (same propagation rule as user_role /
|
||||
oauth attribution)."""
|
||||
@pytest.mark.parametrize(
|
||||
"parent_context",
|
||||
[
|
||||
{"user_id": "channel-owner", "channel_user_id": "ou_group_sender_1"},
|
||||
{"user_id": "schedule-owner", "non_interactive": True},
|
||||
],
|
||||
ids=["channel", "scheduled"],
|
||||
)
|
||||
def test_task_tool_forwards_parent_identity_to_executor(monkeypatch, parent_context):
|
||||
runtime = _make_runtime()
|
||||
runtime.context["channel_user_id"] = "ou_group_sender_1"
|
||||
runtime.context.update(parent_context)
|
||||
captured = {}
|
||||
|
||||
class DummyExecutor:
|
||||
@ -713,7 +717,9 @@ def test_task_tool_forwards_channel_user_id_to_executor(monkeypatch):
|
||||
|
||||
message = _task_tool_message(output)
|
||||
assert message.content == "Task Succeeded. Result: done"
|
||||
assert captured["executor_kwargs"]["channel_user_id"] == "ou_group_sender_1"
|
||||
assert captured["executor_kwargs"]["user_id"] == parent_context["user_id"]
|
||||
assert captured["executor_kwargs"]["channel_user_id"] == parent_context.get("channel_user_id")
|
||||
assert ("ask_clarification" in captured["executor_kwargs"]["config"].disallowed_tools) is ("non_interactive" in parent_context)
|
||||
|
||||
|
||||
def test_task_tool_forwards_is_internal_true_to_executor(monkeypatch):
|
||||
|
||||
@ -630,6 +630,36 @@ async def test_child_in_an_isolated_loop_waits_for_parent_decision(cancel):
|
||||
await bridge.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unattended_child_cannot_open_an_approval_wait():
|
||||
import asyncio
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from deerflow.approvals.runtime import ApprovalRuntime
|
||||
from deerflow.approvals.store import ApprovalStore
|
||||
|
||||
store = ApprovalStore()
|
||||
scope = ("owner", "scheduled-thread", "incarnation")
|
||||
bridge = ApprovalRuntime(
|
||||
store,
|
||||
scope=scope,
|
||||
run_id="scheduled-run",
|
||||
mode="ask",
|
||||
timeout=5,
|
||||
record=SimpleNamespace(ownership_lost=False, abort_event=threading.Event()),
|
||||
interactive=False,
|
||||
)
|
||||
graph, config, calls = graph_fixture()
|
||||
context = {"is_subagent": True, "__tool_approval_runtime": bridge.child(), "user_id": "owner", "thread_id": "scheduled-thread"}
|
||||
try:
|
||||
result = await asyncio.wait_for(graph.ainvoke({"messages": [("user", "delegated work")]}, config, context=context), timeout=2)
|
||||
assert not calls and not result.get("__interrupt__")
|
||||
assert not await store.list(scope=scope, status="pending")
|
||||
finally:
|
||||
await bridge.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_exact_thread_grant_is_reused_then_revoked():
|
||||
import threading
|
||||
|
||||
@ -185,6 +185,8 @@ originating chat.
|
||||
|
||||
To start a trial, use the task card's **Run once now** button or the corresponding action on `/workspace/scheduled-tasks`. A request in chat can bring up the card, but its wording alone does not dispatch a run. The action uses the existing authenticated, owner-checked endpoint; an already waiting run is not duplicated. A trial does not count toward `max_runs`.
|
||||
|
||||
Automatic runs and manual trials both use the unattended tool policy. Native subagents inherit its clarification restriction and unattended guidance, including when a durable batch resumes after a restart. Set `subagent_enabled: true` through the [Scheduled Tasks API](../../backend/docs/API.md#scheduled-tasks) to allow delegation on a schedule. With durable batches also enabled, the run can submit batch work and inspect results. Automatic batch follow-ups require an originating interactive session with follow-up authority.
|
||||
|
||||
A goal occurrence can use up to nine agent turns, with an evaluator request after
|
||||
each. Evaluator requests and provider-reported tokens are included in run usage;
|
||||
missing usage makes the corresponding cost estimate unknown. `token_budget`
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user