feat(schedule): 优化排程任务配置与进度契约处理逻辑

This commit is contained in:
hugo committed 2026-07-08 16:09:28 +08:00
1 parent d54f51ddc3
commit 99453aa52a
65 files changed
+2837 -487

No files matched your search

@@ -20,6 +20,7 @@ from app.services.agent_registry.catalog_loader import (
)
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
default_capabilities_copy,
normalize_handler_config,
validate_required_fields,
@@ -176,6 +177,8 @@ def validate_agent_payload(
bound_schedule_task_id = data.get('bound_schedule_task_id', getattr(agent, 'bound_schedule_task_id', None) if agent else None)
bound_schedule_task_id = _parse_bound_schedule_task_id(bound_schedule_task_id)
if not catalog_progress_requires_schedule_task(agent_code):
bound_schedule_task_id = None
capabilities = _parse_capabilities(data.get('capabilities', getattr(agent, 'capabilities', None) if agent else None))
capabilities = apply_catalog_capabilities(agent_code, capabilities)
@@ -12,6 +12,7 @@ from typing import Any
from app.services.agent_registry.catalog_loader import (
build_agent_type_catalog,
get_agent_type_default_capabilities,
get_default_capabilities,
get_platform_config,
get_tool_run_progress_defaults,
@@ -41,7 +42,9 @@ def build_agent_registry_schema() -> dict[str, Any]:
agent_types.append({
**item,
'required_fields': list(entry.get('required_fields') or []),
'default_capabilities': get_agent_type_default_capabilities(str(code or '')),
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
})
@@ -20,6 +20,17 @@ from app.services.agent_registry.catalog_bindings import RUNTIME_HANDLER_BINDING
_MANIFEST_PATH = Path(__file__).resolve().parent / 'data' / 'catalog_manifest.yaml'
_PROGRESS_DATA_SOURCES = frozenset({
'schedule_run',
'domain_state',
'job_queue',
'external_callback',
})
_PROGRESS_TRANSPORTS = frozenset({'polling', 'sse', 'manual_refresh'})
_PROGRESS_BINDINGS = frozenset({'chat_log_run', 'conversation_context', 'domain_key'})
_PROGRESS_LAYOUTS = frozenset({'card', 'workspace', 'inline', 'drawer'})
_PROGRESS_VISUALIZATIONS = frozenset({'counter', 'stepper', 'timeline', 'percent', 'hybrid'})
def coerce_manifest_boolean(value: Any, *, context: str = 'manifest') -> bool:
"""
@@ -128,6 +139,24 @@ def get_default_capabilities() -> dict[str, bool]:
return result
def get_agent_type_default_capabilities(agent_code: str) -> dict[str, bool]:
"""
合并 platform 与 agent_types 段 default_capabilities。
核心逻辑:平台默认为基础,类型级 default_capabilities 覆盖同名字段。
"""
merged = dict(get_default_capabilities())
entry = get_catalog_entry(agent_code) or {}
type_defaults = entry.get('default_capabilities') or {}
if isinstance(type_defaults, dict):
for key, value in type_defaults.items():
merged[str(key)] = coerce_manifest_boolean(
value,
context=f'agent_types.{agent_code}.default_capabilities.{key}',
)
return merged
def get_tool_run_progress_defaults() -> dict[str, Any]:
"""task_progress 视图默认值(含 progress_type);布尔/整数字段经 coercion。"""
platform = get_platform_config()
@@ -151,6 +180,134 @@ def get_tool_run_progress_defaults() -> dict[str, Any]:
}
def _enum_value(
value: Any,
*,
allowed: frozenset[str],
context: str,
default: str | None = None,
) -> str | None:
text = str(value or '').strip()
if not text:
return default
if text not in allowed:
raise ValidationError(f'{context} 取值无效: {text}')
return text
def normalize_progress_contract(raw: Any, *, context: str = 'progress_contract') -> dict[str, Any] | None:
"""
归一化通用进度契约。
核心逻辑:catalog 只声明通用 source/update/binding/presentation 维度,
不以 agent_code 作为进度类型。
"""
if raw in (None, False):
return None
if not isinstance(raw, dict):
raise ValidationError(f'{context} 必须为 JSON 对象')
enabled = coerce_manifest_boolean(raw.get('enabled', True), context=f'{context}.enabled')
if not enabled:
return {'enabled': False}
data_source_raw = raw.get('data_source') if isinstance(raw.get('data_source'), dict) else {}
update_raw = raw.get('update') if isinstance(raw.get('update'), dict) else {}
binding_raw = raw.get('binding') if isinstance(raw.get('binding'), dict) else {}
presentation_raw = raw.get('presentation') if isinstance(raw.get('presentation'), dict) else {}
data_source_type = _enum_value(
data_source_raw.get('type'),
allowed=_PROGRESS_DATA_SOURCES,
context=f'{context}.data_source.type',
)
if not data_source_type:
raise ValidationError(f'{context}.data_source.type 必填')
transport = _enum_value(
update_raw.get('transport'),
allowed=_PROGRESS_TRANSPORTS,
context=f'{context}.update.transport',
default='polling',
)
binding_type = _enum_value(
binding_raw.get('type'),
allowed=_PROGRESS_BINDINGS,
context=f'{context}.binding.type',
default='chat_log_run',
)
layout = _enum_value(
presentation_raw.get('layout'),
allowed=_PROGRESS_LAYOUTS,
context=f'{context}.presentation.layout',
default='card',
)
visualization = _enum_value(
presentation_raw.get('visualization'),
allowed=_PROGRESS_VISUALIZATIONS,
context=f'{context}.presentation.visualization',
default='counter',
)
interval_raw = update_raw.get('interval_seconds')
interval_seconds = None
if interval_raw is not None:
try:
interval_seconds = max(1, min(int(interval_raw), 30))
except (TypeError, ValueError):
raise ValidationError(f'{context}.update.interval_seconds 必须为整数')
keys_raw = binding_raw.get('keys')
keys = [
str(item or '').strip()
for item in keys_raw
if str(item or '').strip()
] if isinstance(keys_raw, list) else []
contract: dict[str, Any] = {
'enabled': True,
'data_source': {
'type': data_source_type,
},
'update': {
'transport': transport,
},
'binding': {
'type': binding_type,
'requires_schedule_task': coerce_manifest_boolean(
binding_raw.get('requires_schedule_task', False),
context=f'{context}.binding.requires_schedule_task',
),
},
'presentation': {
'layout': layout,
'visualization': visualization,
},
}
domain = str(data_source_raw.get('domain') or '').strip()
if domain:
contract['data_source']['domain'] = domain
event = str(update_raw.get('event') or '').strip()
if event:
contract['update']['event'] = event
if interval_seconds is not None:
contract['update']['interval_seconds'] = interval_seconds
fallback = str(binding_raw.get('fallback') or '').strip()
if fallback:
contract['binding']['fallback'] = fallback
if keys:
contract['binding']['keys'] = keys
# [STEP 组合校验] manifest 配错时 fail-fast,避免运行时静默失效。
if transport == 'sse' and not event:
raise ValidationError(f'{context}.update.transport=sse 时 update.event 必填')
if data_source_type == 'schedule_run' and contract['binding']['requires_schedule_task'] is not True:
raise ValidationError(
f'{context}.data_source.type=schedule_run 时 binding.requires_schedule_task 必须为 true',
)
return contract
@lru_cache(maxsize=1)
def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
"""
@@ -169,6 +326,14 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
continue
merged = deepcopy(entry)
merged['runtime_handler'] = RUNTIME_HANDLER_BINDINGS.get(str(code)) or None
if isinstance(merged.get('default_capabilities'), dict):
merged['default_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
cap_value,
context=f'agent_types.{code}.default_capabilities.{cap_key}',
)
for cap_key, cap_value in merged['default_capabilities'].items()
}
if isinstance(merged.get('forced_capabilities'), dict):
merged['forced_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
@@ -177,6 +342,10 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
)
for cap_key, cap_value in merged['forced_capabilities'].items()
}
merged['progress_contract'] = normalize_progress_contract(
merged.get('progress_contract'),
context=f'agent_types.{code}.progress_contract',
)
catalog[str(code)] = merged
return catalog
@@ -42,22 +42,37 @@ def apply_catalog_capabilities(agent_code: str, capabilities: dict[str, bool]) -
return merged
def catalog_progress_requires_schedule_task(agent_code: str) -> bool:
"""
判断 Catalog progress_contract 是否要求绑定排程任务。
核心逻辑:优先读 progress_contract.binding.requires_schedule_task;
兼容 required_fields 中的 bound_schedule_task_id 声明。
"""
entry = get_catalog_entry(agent_code) or {}
progress = entry.get('progress_contract') if isinstance(entry.get('progress_contract'), dict) else {}
if progress.get('enabled') is True:
binding = progress.get('binding') if isinstance(progress.get('binding'), dict) else {}
if binding.get('requires_schedule_task') is True:
return True
required = entry.get('required_fields') or []
return isinstance(required, list) and 'bound_schedule_task_id' in required
def validate_required_fields(
agent_code: str,
*,
bound_schedule_task_id: int | None = None,
) -> None:
"""
校验 Catalog 声明的 required_fields。
校验 Catalog 声明的 required_fields 与 progress_contract.binding。
Raises:
ValidationError: 必填列缺失。
"""
entry = get_catalog_entry(agent_code) or {}
required = entry.get('required_fields') or []
if not isinstance(required, list):
if not catalog_progress_requires_schedule_task(agent_code):
return
if 'bound_schedule_task_id' in required and not bound_schedule_task_id:
if not bound_schedule_task_id:
raise ValidationError(f'agent_code={agent_code} 时 bound_schedule_task_id 必填')
@@ -58,7 +58,30 @@ agent_types:
- ShippingTask
- ShippingTaskEvent
required_fields: []
forced_capabilities: {}
default_capabilities:
file_upload: true
task_progress: true
forced_capabilities:
file_upload: true
task_progress: true
human_confirm: true
progress_contract:
enabled: true
data_source:
type: domain_state
domain: shipping_notice
update:
transport: sse
event: shipping_ui_state
binding:
type: conversation_context
keys:
- batch_no
- task_no
requires_schedule_task: false
presentation:
layout: workspace
visualization: stepper
handler_config_schema: {}
file_check:
label: 文件检核
@@ -70,6 +93,20 @@ agent_types:
- bound_schedule_task_id
forced_capabilities:
task_progress: true
progress_contract:
enabled: true
data_source:
type: schedule_run
update:
transport: polling
interval_seconds: 2
binding:
type: chat_log_run
fallback: chat_log_id
requires_schedule_task: true
presentation:
layout: card
visualization: counter
handler_config_schema:
poll_interval_seconds:
type: integer
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/file_check.py
用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry、resolver。
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。
"""
@@ -12,7 +12,16 @@ import uuid
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import agent_declares_task_progress
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_schedule_run_progress(agent) -> bool:
"""progress_contract 声明 schedule_run 数据源时才注册检核 turn。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
return data_source.get('type') == 'schedule_run'
@register_handler('file_check')
@@ -20,12 +29,12 @@ class FileCheckHandler(AgentHandler):
"""
文件检核业务 Handler。
核心逻辑:capabilities.task_progress === true 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities 本身仅控制前端是否展示进度 UI。
核心逻辑:progress_contract.data_source=schedule_run 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities.task_progress 仅作能力门禁。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
if not agent_declares_task_progress(ctx.agent):
if not _uses_schedule_run_progress(ctx.agent):
return ctx
turn_id = uuid.uuid4().hex
@@ -15,6 +15,22 @@ from flask import current_app
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_shipping_ui_state_progress(agent) -> bool:
"""progress_contract 声明 domain_state + shipping_ui_state SSE 时才下发 UI State。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
return (
data_source.get('type') == 'domain_state'
and data_source.get('domain') == 'shipping_notice'
and update.get('transport') == 'sse'
and update.get('event') == 'shipping_ui_state'
)
@register_handler('shipping_notice')
@@ -31,6 +47,9 @@ class ShippingNoticeHandler(AgentHandler):
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
if not task_id and not batch_no:
@@ -287,6 +287,40 @@ def agent_declares_task_progress(agent) -> bool:
return resolve_capabilities(agent).get('task_progress') is True
def resolve_progress_contract(agent) -> dict[str, Any] | None:
"""
解析 Agent 通用进度契约。
核心逻辑:读 catalog 中的 progress_contract;task_progress 门禁同时合并
Catalog forced_capabilities,避免存量行 capabilities 缺失导致进度 UI 消失。
"""
entry = get_catalog_entry(resolve_agent_code(agent)) or {}
forced = entry.get('forced_capabilities') if isinstance(entry.get('forced_capabilities'), dict) else {}
task_progress_enabled = (
agent_declares_task_progress(agent)
or forced.get('task_progress') is True
)
if not task_progress_enabled:
return None
contract = entry.get('progress_contract')
if not isinstance(contract, dict) or contract.get('enabled') is not True:
return None
import copy
return copy.deepcopy(contract)
def agent_has_progress(agent) -> bool:
"""判断 Agent 是否有可用通用进度契约。"""
return resolve_progress_contract(agent) is not None
def agent_progress_requires_schedule_task(agent) -> bool:
"""判断 Agent 进度契约是否需要绑定 ScheduleTask。"""
contract = resolve_progress_contract(agent)
binding = contract.get('binding') if isinstance(contract, dict) else None
return isinstance(binding, dict) and binding.get('requires_schedule_task') is True
def is_file_check_runtime_ready(agent) -> bool:
"""
判断 file_check 对话入口是否已完整配置(可注入 task_id、绑定 chat_log.run_id)。
@@ -299,7 +333,7 @@ def is_file_check_runtime_ready(agent) -> bool:
Returns:
能力声明且 task_id 列已配置时返回 True。
"""
if not agent_declares_task_progress(agent):
if not agent_progress_requires_schedule_task(agent):
return False
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -12,10 +12,10 @@ from typing import Any
from app.models import Agent
from app.services.agent_registry.resolver import (
normalize_capabilities,
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_progress_contract,
resolve_runtime_provider,
)
@@ -43,6 +43,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
handler_config = getattr(agent, 'handler_config', None)
intent_meta = resolve_agent_intent_metadata(agent)
tool_run_progress = build_tool_run_progress_view(agent)
progress_contract = resolve_progress_contract(agent)
return {
'agent_code': resolve_agent_code(agent),
'runtime_provider': resolve_runtime_provider(agent),
@@ -60,12 +61,13 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'bound_schedule_task_id': getattr(agent, 'bound_schedule_task_id', None),
'handler_config': handler_config if isinstance(handler_config, dict) else None,
'tool_run_progress': tool_run_progress,
'progress_contract': progress_contract,
**intent_meta,
}
def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
"""Agent ORM → 管理端列表/详情 JSON(API Key 仅返回脱敏值,明文不可读)。"""
"""Agent ORM → 管理端列表/详情 JSON(含 dify_api_key 供编辑表单密码框回填)。"""
registry = serialize_registry_fields(agent)
return {
'id': agent.id,
@@ -75,6 +77,7 @@ def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
'is_active': agent.is_active,
'type': agent.type,
'dify_app_id': agent.dify_app_id,
'dify_api_key': agent.dify_api_key,
'dify_api_key_masked': mask_dify_api_key(agent.dify_api_key),
'api_base_url': agent.api_base_url,
'extra_config': agent.extra_config if isinstance(agent.extra_config, dict) else {},
@@ -123,13 +126,18 @@ def serialize_agent_for_user_detail(
def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
"""
从 Registry 列构建前端 tool_run_progress 视图(迁移期兼容 extra 读者)。
从 Registry 列构建前端 tool_run_progress 视图(schedule_run 进度兼容层)。
核心逻辑:capabilities.task_progress 为 true 且 bound_schedule_task_id 已注册时返回配置 dict。
核心逻辑:progress_contract.data_source.type=schedule_run 且 bound_schedule_task_id
已注册时返回配置 dict;domain_state 等其它进度类型不走本视图。
"""
caps = resolve_capabilities(agent)
if not caps.get('task_progress'):
contract = resolve_progress_contract(agent)
if not contract:
return None
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
if data_source.get('type') != 'schedule_run':
return None
task_id = getattr(agent, 'bound_schedule_task_id', None)
try:
schedule_task_id = int(task_id)
@@ -143,11 +151,12 @@ def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
from app.services.agent_registry.resolver import resolve_agent_code
defaults = get_tool_run_progress_defaults()
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
cfg: dict[str, Any] = {
'type': str(defaults.get('progress_type') or resolve_agent_code(agent) or 'file_check'),
'schedule_task_id': schedule_task_id,
}
cfg['poll_interval_seconds'] = defaults.get('poll_interval_seconds', 2)
cfg['poll_interval_seconds'] = update.get('interval_seconds') or defaults.get('poll_interval_seconds', 2)
cfg['lock_input_when_running'] = defaults.get('lock_input_when_running', True)
if isinstance(handler_config, dict):
if handler_config.get('poll_interval_seconds') is not None: