refactor(agent-runtime, shipping-notice, frontend): 重构上下文体系,修复重试RPA无响应问题
- 替换原有的hxops_context模块为全新的代理运行时上下文平台协议,统一跨业务上下文注入逻辑 - 新增多语言操作繁忙提示文案(覆盖中、繁、英、泰四语),前端绑定页面繁忙状态实现操作阻断 - 调整RPA库存导出重试策略:移除可配置的最大自动重试次数,改为固定单次自动重试,手动重试需用户显式触发 - 优化任务用户态状态展示逻辑,优先展示具体的pending原因而非通用状态文案 - 重构任务焦点切换逻辑,统一事件日志与处理流程,复用switch_batch_focus工具函数 - 修复clearAllHistory函数残留UI问题,确保清空会话后完全复位发货通知相关视图 - 更新OpenAPI文档与静态快照,补充工具使用约束说明 - 新增调试打点日志与问题排查文档,完善全套单元测试与快照校验用例 - 更新RPA脚本的README文档,调整登录方式说明与浏览器 profile 路径配置 - 删除废弃的hxops_context模块,迁移所有相关调用到新的上下文体系
This commit is contained in:
1 parent
60dd0c0f58
commit
8846ce159f
102 files changed
+18289
-9072
No files matched your search
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/__init__.py
|
||||
|
||||
用途:聚合导出 HXOPS Agent Runtime Context 平台协议能力与通用构建器。
|
||||
依赖:builder、schema、generic adapter、reference。
|
||||
逻辑:业务 adapter 从本包导入平台协议与构建器;聊天分发入口单独从 `dify_inputs.py` 直接导入,避免包初始化时反向拉起业务 adapter 形成循环依赖。
|
||||
"""
|
||||
|
||||
from app.services.agent_runtime_context.adapters.generic import (
|
||||
build_generic_runtime_context,
|
||||
resolve_agent_code,
|
||||
)
|
||||
from app.services.agent_runtime_context.builder import (
|
||||
build_agent_runtime_context,
|
||||
build_dify_inputs,
|
||||
serialize_for_dify,
|
||||
)
|
||||
from app.services.agent_runtime_context.reference import (
|
||||
build_object_ref,
|
||||
build_reference_context,
|
||||
)
|
||||
from app.services.agent_runtime_context.schema import (
|
||||
AGENT_RUNTIME_CONTEXT_INPUT,
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AGENT_RUNTIME_CONTEXT_INPUT",
|
||||
"AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION",
|
||||
"build_agent_runtime_context",
|
||||
"build_dify_inputs",
|
||||
"build_generic_runtime_context",
|
||||
"build_object_ref",
|
||||
"build_reference_context",
|
||||
"resolve_agent_code",
|
||||
"serialize_for_dify",
|
||||
]
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/adapters/generic.py
|
||||
|
||||
用途:为未接入专用业务 adapter 的 Dify Agent 构建最小可用的 agent_runtime_context。
|
||||
依赖:agent_runtime_context.builder、标准库 typing。
|
||||
逻辑:由平台级 dify_inputs 分发入口调用;当 Agent 既不是 shipping_notice 也不是 file_check 时,
|
||||
使用本模块生成通用会话快照,让 Dify Start 节点也能稳定拿到 platform/session 上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.builder import (
|
||||
build_agent_runtime_context,
|
||||
build_dify_inputs,
|
||||
)
|
||||
|
||||
|
||||
def _agent_extra_config(agent) -> dict[str, Any]:
|
||||
"""读取 Agent.extra_config;非字典时回退为空,避免通用适配器因脏配置报错。"""
|
||||
extra_config = getattr(agent, "extra_config", None)
|
||||
return extra_config if isinstance(extra_config, dict) else {}
|
||||
|
||||
|
||||
def resolve_agent_code(agent) -> str:
|
||||
"""
|
||||
解析通用 Agent 的稳定 code。
|
||||
|
||||
核心逻辑:优先读取 extra_config.agent_code;未配置或为空时回退为 generic,
|
||||
让知识库/普通问答类 Agent 也能在 Runtime 中暴露稳定标识。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent 记录或代理对象。
|
||||
|
||||
Returns:
|
||||
Agent code 字符串;缺省为 generic。
|
||||
"""
|
||||
agent_code = str(_agent_extra_config(agent).get("agent_code") or "").strip()
|
||||
return agent_code or "generic"
|
||||
|
||||
|
||||
def _resolve_domain_summary(agent) -> str:
|
||||
"""按优先级提取通用摘要,避免无业务状态 Agent 的 domain.summary 为空。"""
|
||||
extra_config = _agent_extra_config(agent)
|
||||
runtime_context_summary = str(extra_config.get("runtime_context_summary") or "").strip()
|
||||
if runtime_context_summary:
|
||||
return runtime_context_summary
|
||||
|
||||
agent_description = str(getattr(agent, "description", None) or "").strip()
|
||||
if agent_description:
|
||||
return agent_description
|
||||
return "通用对话"
|
||||
|
||||
|
||||
def build_generic_runtime_context(
|
||||
*,
|
||||
session_id: str,
|
||||
agent,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
scope: str = "chat_turn",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为通用 Dify Agent 构建最小 Runtime Context。
|
||||
|
||||
核心逻辑:仅注入 platform/session 锚点与 generic domain 摘要,
|
||||
不附带 refs/reference_context,适用于纯 Q&A 或知识库类 Agent。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS 会话 ID;为空时返回空 dict。
|
||||
agent: 当前对话 Agent,读取 extra_config.agent_code/runtime_context_summary。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,默认 frontend_chat。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域,默认 chat_turn。
|
||||
|
||||
Returns:
|
||||
通用 agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
return build_agent_runtime_context(
|
||||
agent_code=resolve_agent_code(agent),
|
||||
scope=scope,
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
domain={
|
||||
"type": "generic",
|
||||
"summary": _resolve_domain_summary(agent),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def build_generic_dify_inputs(
|
||||
*,
|
||||
session_id: str,
|
||||
agent,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
scope: str = "chat_turn",
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建通用 Agent 的 Dify Start inputs。
|
||||
|
||||
核心逻辑:统一把最小 Runtime Context 序列化到 agent_runtime_context,
|
||||
让未接入专用 adapter 的 Agent 也能消费平台会话快照。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS 会话 ID。
|
||||
agent: 当前对话 Agent。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域。
|
||||
|
||||
Returns:
|
||||
仅含 agent_runtime_context 的 inputs;session_id 为空时返回空 dict。
|
||||
"""
|
||||
runtime_context = build_generic_runtime_context(
|
||||
session_id=session_id,
|
||||
agent=agent,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
scope=scope,
|
||||
)
|
||||
return build_dify_inputs(runtime_context)
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/builder.py
|
||||
|
||||
用途:构建并序列化 HXOPS 平台统一的 agent_runtime_context。
|
||||
依赖:schema 协议常量、policy 裁剪策略、json/uuid/time 标准库。
|
||||
逻辑:聊天入口或业务 adapter 调用本模块生成每次 Runtime 调用前的现场 snapshot,再作为 Dify Start 变量注入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from app.services.agent_runtime_context.policy import (
|
||||
MAX_CONTEXT_JSON_CHARS,
|
||||
normalize_domain,
|
||||
normalize_reference_context,
|
||||
normalize_refs,
|
||||
)
|
||||
from app.services.agent_runtime_context.schema import (
|
||||
AGENT_RUNTIME_CONTEXT_INPUT,
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
AgentRuntimeContext,
|
||||
)
|
||||
|
||||
|
||||
def generate_context_id() -> str:
|
||||
"""
|
||||
生成单次 Runtime 上下文编号。
|
||||
|
||||
核心逻辑:使用毫秒时间戳与短 UUID,便于日志检索且不暴露业务编号。
|
||||
|
||||
Returns:
|
||||
形如 ctx_20260702094300000_ab12cd34 的上下文编号。
|
||||
"""
|
||||
timestamp_ms = int(time.time() * 1000)
|
||||
return f"ctx_{timestamp_ms}_{uuid4().hex[:8]}"
|
||||
|
||||
|
||||
def _normalize_platform(
|
||||
*,
|
||||
session_id: str,
|
||||
parent_session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建平台侧上下文片段。
|
||||
|
||||
核心逻辑:session_id 为必填锚点,其余字段有值才输出,避免空字段误导 Runtime。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS ChatSession.session_id。
|
||||
parent_session_id: 后台 run 所属的用户主会话;缺省时等于 session_id。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
|
||||
locale: 用户语言。
|
||||
|
||||
Returns:
|
||||
平台上下文字典。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
platform = {"session_id": normalized_session_id}
|
||||
|
||||
normalized_parent = str(parent_session_id or "").strip()
|
||||
if normalized_parent:
|
||||
platform["parent_session_id"] = normalized_parent
|
||||
elif normalized_session_id:
|
||||
platform["parent_session_id"] = normalized_session_id
|
||||
|
||||
normalized_request_id = str(request_id or "").strip()
|
||||
normalized_trigger_source = str(trigger_source or "").strip()
|
||||
normalized_locale = str(locale or "").strip()
|
||||
if normalized_request_id:
|
||||
platform["request_id"] = normalized_request_id
|
||||
if normalized_trigger_source:
|
||||
platform["trigger_source"] = normalized_trigger_source
|
||||
if normalized_locale:
|
||||
platform["locale"] = normalized_locale
|
||||
return platform
|
||||
|
||||
|
||||
def build_agent_runtime_context(
|
||||
*,
|
||||
agent_code: str = "generic",
|
||||
scope: str = "chat_turn",
|
||||
session_id: str,
|
||||
parent_session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
refs: dict[str, Any] | None = None,
|
||||
domain: dict[str, Any] | None = None,
|
||||
reference_context: dict[str, Any] | None = None,
|
||||
context_id: str | None = None,
|
||||
) -> AgentRuntimeContext:
|
||||
"""
|
||||
构建单次 Runtime 调用的上下文 snapshot。
|
||||
|
||||
核心逻辑:校验 session 锚点,填充平台字段,裁剪 refs/domain/reference_context,并生成 context_id 供审计追踪。
|
||||
|
||||
Args:
|
||||
agent_code: 稳定 Agent 标识,禁止使用展示名称。
|
||||
scope: 上下文作用域,如 chat_turn/task_run。
|
||||
session_id: HXOPS 本地会话 ID。
|
||||
parent_session_id: 后台任务所属主会话 ID。
|
||||
request_id: 本次请求 ID。
|
||||
trigger_source: 触发来源。
|
||||
locale: 用户语言。
|
||||
refs: 业务对象锚点字典。
|
||||
domain: 业务域摘要与状态提示。
|
||||
reference_context: 短期指代治理上下文。
|
||||
context_id: 外部指定的上下文编号;通常留空自动生成。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
context: AgentRuntimeContext = {
|
||||
"schema_version": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
"context_id": str(context_id or "").strip() or generate_context_id(),
|
||||
"agent_code": str(agent_code or "generic").strip() or "generic",
|
||||
"scope": str(scope or "chat_turn").strip() or "chat_turn",
|
||||
"platform": _normalize_platform(
|
||||
session_id=normalized_session_id,
|
||||
parent_session_id=parent_session_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
),
|
||||
"refs": normalize_refs(refs),
|
||||
}
|
||||
|
||||
normalized_domain = normalize_domain(domain)
|
||||
if normalized_domain:
|
||||
context["domain"] = normalized_domain
|
||||
normalized_reference_context = normalize_reference_context(reference_context)
|
||||
if normalized_reference_context:
|
||||
context["reference_context"] = normalized_reference_context
|
||||
return context
|
||||
|
||||
|
||||
def serialize_for_dify(context: dict[str, Any]) -> str:
|
||||
"""
|
||||
将上下文序列化为 Dify Start 节点可稳定接收的 JSON 字符串。
|
||||
|
||||
核心逻辑:使用紧凑 JSON,超过平台限制时抛 ValueError,避免悄悄截断成非法 JSON。
|
||||
|
||||
Args:
|
||||
context: agent_runtime_context 字典。
|
||||
|
||||
Returns:
|
||||
UTF-8 JSON 字符串。
|
||||
|
||||
Raises:
|
||||
ValueError: 上下文序列化后超过长度上限。
|
||||
"""
|
||||
payload = json.dumps(context or {}, ensure_ascii=False, separators=(",", ":"))
|
||||
if len(payload) > MAX_CONTEXT_JSON_CHARS:
|
||||
raise ValueError("agent_runtime_context exceeds max serialized length")
|
||||
return payload
|
||||
|
||||
|
||||
def build_dify_inputs(
|
||||
context: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建传给 Dify 的 inputs。
|
||||
|
||||
核心逻辑:统一只输出 agent_runtime_context JSON 字符串,避免 Start 协议出现多套上下文字段。
|
||||
|
||||
Args:
|
||||
context: agent_runtime_context 字典。
|
||||
|
||||
Returns:
|
||||
Dify inputs 字典。
|
||||
"""
|
||||
if not context:
|
||||
return {}
|
||||
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(context)}
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/dify_inputs.py
|
||||
|
||||
用途:提供聊天入口构建 Dify inputs 的统一分发入口。
|
||||
依赖:generic adapter、file_check_tools.dify_inputs、shipping_notice.dify_inputs。
|
||||
逻辑:chat.py 在调用 DifyService.stream_chat 前只调用本模块;本模块按 Agent 类型分发到
|
||||
shipping_notice / file_check / generic adapter,平台层只暴露会话级公共参数,领域提示由 adapter_hints 透传。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.adapters.generic import build_generic_dify_inputs
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
|
||||
|
||||
def build_chat_dify_inputs(
|
||||
agent,
|
||||
*,
|
||||
session_id: str,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
adapter_hints: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
统一构建聊天 Dify inputs。
|
||||
|
||||
核心逻辑:优先命中 shipping_notice 专用 adapter;其次复用 file_check 既有 task_id 注入;
|
||||
其余 Agent 一律走 generic adapter,让所有 Dify Chatflow 至少拿到 platform/session 快照。
|
||||
业务域专用提示不出现在平台签名中,而是由 adapter_hints 交给对应 adapter 自行消费。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent。
|
||||
session_id: HXOPS 会话 ID;为空时直接返回空 dict。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,默认 frontend_chat。
|
||||
locale: 用户语言。
|
||||
adapter_hints: 领域 adapter 可选读取的提示字典;平台层不感知其内部业务字段。
|
||||
|
||||
Returns:
|
||||
Dify inputs 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
normalized_adapter_hints = adapter_hints if isinstance(adapter_hints, dict) else {}
|
||||
|
||||
if is_shipping_notice_chat_agent(agent):
|
||||
shipping_hints = normalized_adapter_hints.get("shipping_notice")
|
||||
shipping_hints = shipping_hints if isinstance(shipping_hints, dict) else {}
|
||||
return build_shipping_notice_dify_inputs(
|
||||
normalized_session_id,
|
||||
task_id=shipping_hints.get("task_id"),
|
||||
batch_no=shipping_hints.get("batch_no"),
|
||||
trigger_source=trigger_source,
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
)
|
||||
|
||||
if agent_declares_file_check_progress(agent) or is_file_check_chat_agent(agent):
|
||||
return build_file_check_dify_inputs(agent, required=True)
|
||||
|
||||
return build_generic_dify_inputs(
|
||||
session_id=normalized_session_id,
|
||||
agent=agent,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/openapi_spec.py
|
||||
|
||||
用途:构建 agent_runtime_context Tool API 的 OpenAPI 3.0 文档,供 Dify 导入。
|
||||
依赖:parser.ALLOWED_PARSE_PATHS。
|
||||
逻辑:api/agent_runtime_context_tools.py 调用本模块生成 JSON 文档,Dify 通过 parse 工具安全读取上下文字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.parser import ALLOWED_PARSE_PATHS, MAX_PARSE_PATHS
|
||||
|
||||
|
||||
def build_agent_runtime_context_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
构建 Dify 导入用 OpenAPI 文档。
|
||||
|
||||
核心逻辑:仅暴露 parse_agent_runtime_context 一个只读工具,不包含任何业务推进接口。
|
||||
|
||||
Args:
|
||||
base_url: HXOPS 后端公开 Base URL。
|
||||
|
||||
Returns:
|
||||
OpenAPI 3.0 字典。
|
||||
"""
|
||||
server = str(base_url or "").strip().rstrip("/")
|
||||
if not server.endswith("/api/agent-runtime-context"):
|
||||
server = f"{server}/api/agent-runtime-context" if server else "/api/agent-runtime-context"
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "HXOPS Agent Runtime Context Tools",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"HXOPS 平台运行态上下文只读解析工具。"
|
||||
"Dify 应在需要读取 session、task、batch、run purpose、state_hint 或模糊指代线索时调用本工具;"
|
||||
"遇到“继续”“刚才那个”“上一个失败的”等表达时,应优先读取 reference_context。"
|
||||
"若只需要 focus id、last action 或 failure reason,可优先读取 reference_context 的细粒度字段,减少上下文判断分支。"
|
||||
"若 reference_context 返回多个 candidates(多候选),不要猜测,应追问用户或调用业务 Tool 再确认。"
|
||||
"reference_context 与 state_hint 都只是提示,不是业务事实源,也不能替代 HXOPS 状态机。"
|
||||
"推进业务状态必须调用对应业务 Tool,不能依据上下文直接宣布完成、上传成功或任务关闭。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/parse": {
|
||||
"post": {
|
||||
"operationId": "parse_agent_runtime_context",
|
||||
"summary": "解析 HXOPS agent_runtime_context 中的白名单字段",
|
||||
"description": (
|
||||
"只读解析工具;agent_runtime_context 应为 Dify Start 节点中的 JSON 字符串。"
|
||||
f"paths 最多 {MAX_PARSE_PATHS} 个,且必须属于 allowed_paths。"
|
||||
"推荐优先读取 reference_context.focus_object.id、reference_context.last_action_target.action、"
|
||||
"reference_context.last_failed_target.reason 等细粒度字段,降低提示词中的对象拆解成本。"
|
||||
"模糊指代建议优先读取 reference_context;若拿到多个 candidates(多候选),必须追问或回到业务 Tool 校验,禁止自行猜测推进。"
|
||||
"reference_context/state_hint 仅用于理解当前现场,不能替代状态机事实,更不能据此直接推进业务或宣布完成。"
|
||||
),
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["agent_runtime_context", "paths"],
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Dify Start 变量 agent_runtime_context 的 JSON 字符串。"
|
||||
"其中 reference_context 仅用于辅助理解当前现场,不可替代 HXOPS 业务事实源。"
|
||||
),
|
||||
},
|
||||
"paths": {
|
||||
"type": "array",
|
||||
"description": "需要读取的字段路径。",
|
||||
"maxItems": MAX_PARSE_PATHS,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": sorted(ALLOWED_PARSE_PATHS),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Parse response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {"type": "string", "enum": ["ok"]},
|
||||
"data": {"type": "object", "additionalProperties": True},
|
||||
"missing": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
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.file_name",
|
||||
"refs.schedule_task_id",
|
||||
"domain.type",
|
||||
"domain.summary",
|
||||
"domain.state_hint.batch_no",
|
||||
"domain.state_hint.focus_task_no",
|
||||
"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",
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/policy.py
|
||||
|
||||
用途:集中管理 agent_runtime_context 的长度、字段与安全裁剪策略。
|
||||
依赖:schema 中的平台协议常量;不访问数据库或业务服务。
|
||||
逻辑:builder 在输出给 Dify 前调用本模块,确保上下文短小、稳定且不会把大段历史塞进 Runtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MAX_CONTEXT_JSON_CHARS = 8192
|
||||
MAX_DOMAIN_SUMMARY_CHARS = 500
|
||||
MAX_RECENT_ACTIVITY_SUMMARY_CHARS = 500
|
||||
MAX_REF_VALUE_CHARS = 200
|
||||
MAX_REFS = 30
|
||||
|
||||
|
||||
def truncate_text(value: Any, max_chars: int) -> str:
|
||||
"""
|
||||
将任意输入规范化为短文本。
|
||||
|
||||
核心逻辑:strip 后按字符数截断,避免上下文摘要或 ref 值撑爆 Dify Start 变量。
|
||||
|
||||
Args:
|
||||
value: 待规范化的文本或可转字符串对象。
|
||||
max_chars: 最大保留字符数。
|
||||
|
||||
Returns:
|
||||
规范化后的字符串;空值返回空字符串。
|
||||
"""
|
||||
normalized = str(value or "").strip()
|
||||
if max_chars <= 0 or len(normalized) <= max_chars:
|
||||
return normalized
|
||||
return normalized[:max_chars]
|
||||
|
||||
|
||||
def normalize_refs(refs: dict[str, Any] | None) -> dict[str, str]:
|
||||
"""
|
||||
规范化业务对象锚点。
|
||||
|
||||
核心逻辑:保留首个有效 key/value,裁剪 value 长度,并限制总数量,防止业务 adapter 注入过长对象。
|
||||
|
||||
Args:
|
||||
refs: 业务 adapter 传入的 refs 字典。
|
||||
|
||||
Returns:
|
||||
字段名和值均为非空字符串的 refs 字典。
|
||||
"""
|
||||
normalized: dict[str, str] = {}
|
||||
for raw_key, raw_value in (refs or {}).items():
|
||||
key = str(raw_key or "").strip()
|
||||
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
|
||||
if not key or not value or key in normalized:
|
||||
continue
|
||||
normalized[key] = value
|
||||
if len(normalized) >= MAX_REFS:
|
||||
break
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_domain(domain: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
规范化领域上下文。
|
||||
|
||||
核心逻辑:只裁剪已知长文本字段,其余结构保持给业务 adapter 自主表达。
|
||||
|
||||
Args:
|
||||
domain: 业务域上下文片段。
|
||||
|
||||
Returns:
|
||||
裁剪后的领域上下文字典。
|
||||
"""
|
||||
if not domain:
|
||||
return {}
|
||||
normalized = dict(domain)
|
||||
if "summary" in normalized:
|
||||
normalized["summary"] = truncate_text(normalized.get("summary"), MAX_DOMAIN_SUMMARY_CHARS)
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_reference_context(reference_context: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
规范化短期指代上下文。
|
||||
|
||||
核心逻辑:限制 recent_activity_summary 长度,保留 focus/candidates 等结构化候选。
|
||||
|
||||
Args:
|
||||
reference_context: 指代治理上下文。
|
||||
|
||||
Returns:
|
||||
裁剪后的 reference_context 字典。
|
||||
"""
|
||||
if not reference_context:
|
||||
return {}
|
||||
normalized = dict(reference_context)
|
||||
if "recent_activity_summary" in normalized:
|
||||
normalized["recent_activity_summary"] = truncate_text(
|
||||
normalized.get("recent_activity_summary"),
|
||||
MAX_RECENT_ACTIVITY_SUMMARY_CHARS,
|
||||
)
|
||||
return normalized
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/reference.py
|
||||
|
||||
用途:构建平台级 reference_context,给外部 Runtime 提供短期指代解析线索。
|
||||
依赖:agent_runtime_context.policy、schema;不依赖具体业务模型。
|
||||
逻辑:业务 adapter 先把 focus/last_action/candidates 等抽象成对象引用,再由本模块统一裁剪、去重和限流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.policy import MAX_REF_VALUE_CHARS, normalize_reference_context, truncate_text
|
||||
from app.services.agent_runtime_context.schema import ReferenceContext
|
||||
|
||||
MAX_REFERENCE_OBJECT_TYPE_CHARS = 64
|
||||
MAX_REFERENCE_KEY_CHARS = 64
|
||||
MAX_REFERENCE_CANDIDATES = 5
|
||||
|
||||
|
||||
def build_object_ref(type_: str, id_: str, **extra: Any) -> dict[str, str]:
|
||||
"""
|
||||
构建 reference_context 中的对象引用。
|
||||
|
||||
核心逻辑:统一输出 type/id,并裁剪 action/reason/label 等扩展字段,避免业务 adapter 各自拼装不同口径。
|
||||
|
||||
Args:
|
||||
type_: 对象类型,如 task/batch。
|
||||
id_: 对象稳定标识,如 SN-001。
|
||||
**extra: 可选扩展字段,例如 action/reason/label。
|
||||
|
||||
Returns:
|
||||
规范化后的对象引用;type 或 id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_type = truncate_text(type_, MAX_REFERENCE_OBJECT_TYPE_CHARS)
|
||||
normalized_id = truncate_text(id_, MAX_REF_VALUE_CHARS)
|
||||
if not normalized_type or not normalized_id:
|
||||
return {}
|
||||
|
||||
object_ref: dict[str, str] = {
|
||||
"type": normalized_type,
|
||||
"id": normalized_id,
|
||||
}
|
||||
for raw_key, raw_value in extra.items():
|
||||
key = truncate_text(raw_key, MAX_REFERENCE_KEY_CHARS)
|
||||
if not key or key in object_ref or raw_value is None:
|
||||
continue
|
||||
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
|
||||
if not value:
|
||||
continue
|
||||
object_ref[key] = value
|
||||
return object_ref
|
||||
|
||||
|
||||
def _normalize_object_ref(value: dict[str, Any] | None) -> dict[str, str]:
|
||||
"""
|
||||
规范化单个对象引用。
|
||||
|
||||
核心逻辑:兼容业务 adapter 传入的普通 dict,统一转成 build_object_ref 输出结构。
|
||||
|
||||
Args:
|
||||
value: 原始对象引用。
|
||||
|
||||
Returns:
|
||||
规范化后的对象引用;非法输入返回空 dict。
|
||||
"""
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
extra = {key: item for key, item in value.items() if key not in {"type", "type_", "id"}}
|
||||
return build_object_ref(
|
||||
str(value.get("type") or value.get("type_") or ""),
|
||||
str(value.get("id") or ""),
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_candidates(candidates: list[dict[str, Any]] | None) -> list[dict[str, str]]:
|
||||
"""
|
||||
规范化候选对象列表。
|
||||
|
||||
核心逻辑:只保留前几个有效候选,按 type/id 去重,避免把整批对象全塞给 Dify。
|
||||
|
||||
Args:
|
||||
candidates: 候选对象引用列表。
|
||||
|
||||
Returns:
|
||||
去重并限量后的候选列表。
|
||||
"""
|
||||
normalized: list[dict[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for item in candidates or []:
|
||||
candidate = _normalize_object_ref(item)
|
||||
if not candidate:
|
||||
continue
|
||||
dedupe_key = (candidate["type"], candidate["id"])
|
||||
if dedupe_key in seen:
|
||||
continue
|
||||
normalized.append(candidate)
|
||||
seen.add(dedupe_key)
|
||||
if len(normalized) >= MAX_REFERENCE_CANDIDATES:
|
||||
break
|
||||
return normalized
|
||||
|
||||
|
||||
def build_reference_context(
|
||||
*,
|
||||
recent_activity_summary: str | None = None,
|
||||
focus_object: dict[str, Any] | None = None,
|
||||
last_action_target: dict[str, Any] | None = None,
|
||||
last_failed_target: dict[str, Any] | None = None,
|
||||
candidates: list[dict[str, Any]] | None = None,
|
||||
) -> ReferenceContext:
|
||||
"""
|
||||
构建平台统一的 reference_context。
|
||||
|
||||
核心逻辑:收敛业务 adapter 提供的短期指代线索,限制候选数量并裁剪摘要长度,保证输出小而稳定。
|
||||
|
||||
Args:
|
||||
recent_activity_summary: 最近活动摘要。
|
||||
focus_object: 当前焦点对象。
|
||||
last_action_target: 最近一次动作作用对象。
|
||||
last_failed_target: 最近一次失败/异常对象。
|
||||
candidates: 模糊指代候选对象列表。
|
||||
|
||||
Returns:
|
||||
规范化后的 reference_context;所有字段都为空时返回空 dict。
|
||||
"""
|
||||
reference_context: ReferenceContext = {}
|
||||
|
||||
summary = str(recent_activity_summary or "").strip()
|
||||
if summary:
|
||||
reference_context["recent_activity_summary"] = summary
|
||||
|
||||
normalized_focus = _normalize_object_ref(focus_object)
|
||||
if normalized_focus:
|
||||
reference_context["focus_object"] = normalized_focus
|
||||
|
||||
normalized_last_action = _normalize_object_ref(last_action_target)
|
||||
if normalized_last_action:
|
||||
reference_context["last_action_target"] = normalized_last_action
|
||||
|
||||
normalized_last_failed = _normalize_object_ref(last_failed_target)
|
||||
if normalized_last_failed:
|
||||
reference_context["last_failed_target"] = normalized_last_failed
|
||||
|
||||
normalized_candidates = _normalize_candidates(candidates)
|
||||
if normalized_candidates:
|
||||
reference_context["candidates"] = normalized_candidates
|
||||
|
||||
return normalize_reference_context(reference_context)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MAX_REFERENCE_CANDIDATES",
|
||||
"build_object_ref",
|
||||
"build_reference_context",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/schema.py
|
||||
|
||||
用途:定义 HXOPS 传递给外部 Agent Runtime 的统一上下文协议常量与类型。
|
||||
依赖:typing 标准库;不依赖具体业务域,避免平台协议与 shipping/file-check 强耦合。
|
||||
逻辑:builder/policy/parser 等模块引用本文件的字段名和类型,业务 adapter 只填充 refs/domain 差异。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, TypedDict
|
||||
|
||||
AGENT_RUNTIME_CONTEXT_INPUT = "agent_runtime_context"
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION = "1"
|
||||
|
||||
AgentCode = Literal["generic", "shipping_notice", "file_check"]
|
||||
ContextScope = Literal["chat_turn", "task_run", "batch_summary"]
|
||||
|
||||
|
||||
class PlatformContext(TypedDict, total=False):
|
||||
"""
|
||||
描述 HXOPS 平台侧会话与请求锚点。
|
||||
|
||||
核心逻辑:只放平台身份与请求追踪字段,业务状态放入 refs/domain。
|
||||
"""
|
||||
|
||||
session_id: str
|
||||
parent_session_id: str
|
||||
request_id: str
|
||||
locale: str
|
||||
trigger_source: str
|
||||
|
||||
|
||||
class DomainContext(TypedDict, total=False):
|
||||
"""
|
||||
描述业务域运行态摘要。
|
||||
|
||||
核心逻辑:由各业务 adapter 填充 summary/state_hint,供 Dify 理解现场但不替代 HXOPS 状态机。
|
||||
"""
|
||||
|
||||
type: str
|
||||
summary: str
|
||||
state_hint: dict[str, Any]
|
||||
available_actions_hint: list[dict[str, Any]]
|
||||
|
||||
|
||||
class ReferenceContext(TypedDict, total=False):
|
||||
"""
|
||||
描述模糊指代解析所需的短期上下文。
|
||||
|
||||
核心逻辑:承载 recent_activity_summary/focus_object 等摘要,不传全量 ChatLog。
|
||||
"""
|
||||
|
||||
recent_activity_summary: str
|
||||
focus_object: dict[str, Any]
|
||||
last_action_target: dict[str, Any]
|
||||
last_failed_target: dict[str, Any]
|
||||
candidates: list[dict[str, Any]]
|
||||
|
||||
|
||||
class AgentRuntimeContext(TypedDict, total=False):
|
||||
"""
|
||||
HXOPS Agent Runtime Context 协议对象。
|
||||
|
||||
核心逻辑:每次调用外部 Runtime 前重新生成 snapshot,Dify/其他 Runtime 只读取,不作为业务事实源。
|
||||
"""
|
||||
|
||||
schema_version: str
|
||||
context_id: str
|
||||
agent_code: str
|
||||
scope: str
|
||||
platform: PlatformContext
|
||||
refs: dict[str, str]
|
||||
domain: DomainContext
|
||||
reference_context: ReferenceContext
|
||||
Reference in new issue
Block a user