Files
syops/backend/app/services/agent_runtime_context/parser.py
T

210 lines
6.8 KiB
Python

"""
backend/app/services/agent_runtime_context/parser.py
用途:解析 Dify 传回的 agent_runtime_context JSON 字符串,并按白名单路径取值。
依赖:json 标准库、agent_runtime_context.schema/policy、AppError 体系。
逻辑:Tool API 调用本模块只读解析上下文;不执行表达式、不访问数据库、不推进任何业务状态。
"""
from __future__ import annotations
import json
from typing import Any
from app.core.errors import ValidationError
from app.services.agent_runtime_context.policy import MAX_CONTEXT_JSON_CHARS
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION
MAX_PARSE_PATHS = 20
ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
{
"schema_version",
"context_id",
"agent_code",
"scope",
"platform.session_id",
"platform.parent_session_id",
"platform.request_id",
"platform.locale",
"platform.trigger_source",
"refs.batch_no",
"refs.task_no",
"refs.run_purpose",
"refs.capability",
"refs.intake_nos",
"refs.file_name",
"refs.schedule_task_id",
"refs.hxops_turn_id",
"domain.type",
"domain.summary",
"domain.state_hint.batch_no",
"domain.state_hint.focus_task_no",
"domain.state_hint.schedule_task_id",
"domain.state_hint.hxops_turn_id",
"domain.state_hint.current_step",
"domain.state_hint.status",
"domain.state_hint.review_status",
"domain.state_hint.match_status",
"domain.state_hint.pending_human_reason",
"domain.state_hint.upload_status",
"reference_context.recent_activity_summary",
"reference_context.focus_object",
"reference_context.focus_object.type",
"reference_context.focus_object.id",
"reference_context.last_action_target",
"reference_context.last_action_target.action",
"reference_context.last_action_target.id",
"reference_context.last_failed_target",
"reference_context.last_failed_target.reason",
"reference_context.last_failed_target.id",
"reference_context.candidates",
}
)
def _normalize_context(raw_context: str | dict[str, Any]) -> dict[str, Any]:
"""
解析并校验 agent_runtime_context。
核心逻辑:优先支持 Dify Paragraph 传入的 JSON 字符串,也兼容测试/内部调用传 object。
Args:
raw_context: JSON 字符串或上下文字典。
Returns:
agent_runtime_context 字典。
Raises:
ValidationError: 空上下文、超长、JSON 非法或协议版本不匹配。
"""
if isinstance(raw_context, dict):
context = raw_context
else:
serialized = str(raw_context or "").strip()
if not serialized:
raise ValidationError("agent_runtime_context_required")
if len(serialized) > MAX_CONTEXT_JSON_CHARS:
raise ValidationError(
"agent_runtime_context_too_large",
details={"max_chars": MAX_CONTEXT_JSON_CHARS},
)
try:
context = json.loads(serialized)
except json.JSONDecodeError as exc:
raise ValidationError("agent_runtime_context_invalid_json", details={"error": str(exc)}) from exc
if not isinstance(context, dict):
raise ValidationError("agent_runtime_context_must_be_object")
schema_version = str(context.get("schema_version") or "").strip()
if schema_version != AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION:
raise ValidationError(
"agent_runtime_context_schema_version_unsupported",
details={
"expected": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
"actual": schema_version,
},
)
return context
def _normalize_paths(paths: Any) -> list[str]:
"""
校验并规范化字段路径列表。
核心逻辑:限制路径数量且只允许白名单字段,避免 Dify 读取未授权内部上下文片段。
Args:
paths: 请求中的 paths 字段。
Returns:
去重后的路径列表。
Raises:
ValidationError: paths 非列表、为空、超限或包含非白名单路径。
"""
if not isinstance(paths, list) or not paths:
raise ValidationError("paths_required")
if len(paths) > MAX_PARSE_PATHS:
raise ValidationError("paths_too_many", details={"max_paths": MAX_PARSE_PATHS})
normalized: list[str] = []
seen: set[str] = set()
rejected: list[str] = []
for item in paths:
path = str(item or "").strip()
if not path:
continue
if path not in ALLOWED_PARSE_PATHS:
rejected.append(path)
continue
if path not in seen:
normalized.append(path)
seen.add(path)
if rejected:
raise ValidationError("paths_not_allowed", details={"paths": rejected})
if not normalized:
raise ValidationError("paths_required")
return normalized
def _get_path_value(context: dict[str, Any], path: str) -> tuple[bool, Any]:
"""
按点路径从上下文读取值。
核心逻辑:只做 dict key 逐层访问,不支持数组下标、通配符或表达式。
Args:
context: agent_runtime_context 字典。
path: 白名单字段路径。
Returns:
(是否存在, 值)。
"""
cursor: Any = context
for part in path.split("."):
if not isinstance(cursor, dict) or part not in cursor:
return False, None
cursor = cursor[part]
return True, cursor
def parse_agent_runtime_context(raw_context: str | dict[str, Any], paths: Any) -> dict[str, Any]:
"""
解析 agent_runtime_context 并返回指定字段。
【AI 触发时机】:Dify 画布需要读取当前 HXOPS 会话、任务、批次、执行目的或状态提示时调用;
不用于推进任务状态,推进必须调用对应业务 Tool。
核心逻辑:校验协议版本与路径白名单,逐路径读取字段,缺失字段放入 missing。
Args:
raw_context: Dify Start 变量中的 agent_runtime_context JSON 字符串。
paths: 需要读取的白名单路径列表。
Returns:
{"status": "ok", "data": {...}, "missing": [...]}。
Raises:
ValidationError: 请求体、上下文或路径非法。
"""
context = _normalize_context(raw_context)
normalized_paths = _normalize_paths(paths)
data: dict[str, Any] = {}
missing: list[str] = []
for path in normalized_paths:
exists, value = _get_path_value(context, path)
if exists:
data[path] = value
else:
missing.append(path)
return {"status": "ok", "data": data, "missing": missing}
__all__ = [
"ALLOWED_PARSE_PATHS",
"MAX_PARSE_PATHS",
"parse_agent_runtime_context",
]