问答模式智能路由智能体初始版

This commit is contained in:
许海洋 committed 2026-05-21 13:50:15 +08:00
1 parent 1b0060ded7
commit 7ee89405f5
11 files changed
+263 -46

No files matched your search

@@ -37,6 +37,14 @@ def _get_runtime_app_config(runtime: Any) -> "AppConfig | None":
return None
def _get_runtime_stream_bridge(runtime: Any) -> Any:
"""Get StreamBridge from runtime context for publishing events to SSE."""
context = getattr(runtime, "context", None)
if isinstance(context, dict):
return context.get("stream_bridge")
return None
def _merge_skill_allowlists(parent: list[str] | None, child: list[str] | None) -> list[str] | None:
"""Return the effective subagent skill allowlist under the parent policy."""
if parent is None:
@@ -123,6 +131,8 @@ async def task_tool(
parent_model = None
trace_id = None
metadata: dict = {}
stream_bridge = None
run_id = None
if runtime is not None:
sandbox_state = runtime.state.get("sandbox")
@@ -138,6 +148,10 @@ async def task_tool(
# Get or generate trace_id for distributed tracing
trace_id = metadata.get("trace_id") or str(uuid.uuid4())[:8]
# Get StreamBridge from runtime context for SSE event publishing
stream_bridge = _get_runtime_stream_bridge(runtime)
run_id = runtime.context.get("run_id") if runtime.context else None
parent_available_skills = metadata.get("available_skills")
if parent_available_skills is not None:
overrides["skills"] = _merge_skill_allowlists(list(parent_available_skills), config.skills)
@@ -188,14 +202,22 @@ async def task_tool(
poll_count = 0
last_status = None
last_message_count = 0 # Track how many AI messages we've already sent
# Polling timeout: execution timeout + 60s buffer, checked every 5s
max_poll_count = (config.timeout_seconds + 60) // 5
# Polling timeout: execution timeout + 60s buffer, checked every 0.5s for near real-time streaming
max_poll_count = (config.timeout_seconds + 60) // 0.5
logger.info(f"[trace={trace_id}] Started background task {task_id} (subagent={subagent_type}, timeout={config.timeout_seconds}s, polling_limit={max_poll_count} polls)")
writer = get_stream_writer()
# Send Task Started message'
writer({"type": "task_started", "task_id": task_id, "description": description})
# Use StreamBridge for SSE events if available, otherwise fall back to StreamWriter
async def publish_event(event_type: str, data: Any) -> None:
"""Publish event to SSE stream via bridge or writer."""
if stream_bridge is not None and run_id is not None:
await stream_bridge.publish(run_id, event_type, data)
else:
writer = get_stream_writer()
writer({"type": event_type, **data})
# Send Task Started message
await publish_event("task_started", {"task_id": task_id, "description": description})
try:
while True:
@@ -203,7 +225,7 @@ async def task_tool(
if result is None:
logger.error(f"[trace={trace_id}] Task {task_id} not found in background tasks")
writer({"type": "task_failed", "task_id": task_id, "error": "Task disappeared from background tasks"})
await publish_event("task_failed", {"task_id": task_id, "error": "Task disappeared from background tasks"})
cleanup_background_task(task_id)
return f"Error: Task {task_id} disappeared from background tasks"
@@ -219,46 +241,43 @@ async def task_tool(
# Send task_running event for each new message
for i in range(last_message_count, current_message_count):
message = ai_messages[i]
writer(
{
"type": "task_running",
"task_id": task_id,
"message": message,
"message_index": i + 1, # 1-based index for display
"total_messages": current_message_count,
}
)
await publish_event("task_running", {
"task_id": task_id,
"message": message,
"message_index": i + 1, # 1-based index for display
"total_messages": current_message_count,
})
logger.info(f"[trace={trace_id}] Task {task_id} sent message #{i + 1}/{current_message_count}")
last_message_count = current_message_count
# Check if task completed, failed, or timed out
if result.status == SubagentStatus.COMPLETED:
writer({"type": "task_completed", "task_id": task_id, "result": result.result})
await publish_event("task_completed", {"task_id": task_id, "result": result.result})
logger.info(f"[trace={trace_id}] Task {task_id} completed after {poll_count} polls")
cleanup_background_task(task_id)
return f"Task Succeeded. Result: {result.result}"
elif result.status == SubagentStatus.FAILED:
writer({"type": "task_failed", "task_id": task_id, "error": result.error})
await publish_event("task_failed", {"task_id": task_id, "error": result.error})
logger.error(f"[trace={trace_id}] Task {task_id} failed: {result.error}")
cleanup_background_task(task_id)
return f"Task failed. Error: {result.error}"
elif result.status == SubagentStatus.CANCELLED:
writer({"type": "task_cancelled", "task_id": task_id, "error": result.error})
await publish_event("task_cancelled", {"task_id": task_id, "error": result.error})
logger.info(f"[trace={trace_id}] Task {task_id} cancelled: {result.error}")
cleanup_background_task(task_id)
return "Task cancelled by user."
elif result.status == SubagentStatus.TIMED_OUT:
writer({"type": "task_timed_out", "task_id": task_id, "error": result.error})
await publish_event("task_timed_out", {"task_id": task_id, "error": result.error})
logger.warning(f"[trace={trace_id}] Task {task_id} timed out: {result.error}")
cleanup_background_task(task_id)
return f"Task timed out. Error: {result.error}"
# Still running, wait before next poll
await asyncio.sleep(5)
# Still running, wait before next poll (reduced from 5s to 0.5s for near real-time streaming)
await asyncio.sleep(0.5)
poll_count += 1
# Polling timeout as a safety net (in case thread pool timeout doesn't work)
# Set to execution timeout + 60s buffer, in 5s poll intervals
# Set to execution timeout + 60s buffer, in 0.5s poll intervals for near real-time streaming
# This catches edge cases where the background task gets stuck
# Note: We don't call cleanup_background_task here because the task may
# still be running in the background. The cleanup will happen when the
@@ -292,7 +311,7 @@ async def task_tool(
logger.warning(f"[trace={trace_id}] Deferred cleanup for task {task_id} timed out after {cleanup_poll_count} polls")
return
await asyncio.sleep(5)
await asyncio.sleep(0.5)
cleanup_poll_count += 1
def log_cleanup_failure(cleanup_task: asyncio.Task[None]) -> None: