fix: isolate agent sessions and retain runtime resource ownership (#7149)

* fix: arbitrate subscription identity and restore workflow state

* fix: isolate agent sessions and retain runtime resource ownership

* test: preserve legacy empty-owner subscription transactions

* test: handle reaped terminal descendants during shutdown polling

* fix: align shared atomic configuration method with lifecycle prerequisite

* test: cover subagent cancellation and completion lifecycle boundaries

---------

Co-authored-by: jxxghp <jxxghp@gmail.com>
This commit is contained in:
Aqr-K
2026-10-23 08:20:59 +08:00
committed by GitHub
parent 951cdc5b27
commit 7584d4b9fc
33 changed files with 1345 additions and 88 deletions

View File

@@ -249,11 +249,18 @@ class SqliteRecallRepository:
"""
最近会话先走活动时间索引限量取候选,不扫描全库会话链。
"""
rows = connection.execute("SELECT * FROM sessions WHERE source NOT IN ('kanban','subagent','tool') ORDER BY last_active DESC LIMIT ?",
(query.limit + 15,))
where = ["source NOT IN ('kanban','subagent','tool')", "id<>?"]
parameters: list[Any] = [query.current_session_id]
for operator, bound in ((">=", query.after), ("<", query.before)):
if bound is not None:
where.append(f"started_at {operator} ?")
parameters.append(bound)
excluded = {lineage(connection, identity) for identity in query.exclude_session_ids}
order = "started_at ASC,id ASC" if query.sort == "oldest" else "last_active DESC,id DESC"
rows = connection.execute(f"SELECT * FROM sessions WHERE {' AND '.join(where)} ORDER BY {order}", parameters)
results: list[dict[str, Any]] = []
for row in rows:
if row['id'] == query.current_session_id:
if row['id'] == query.current_session_id or lineage(connection, row['id']) in excluded:
continue
first, _ = bookends(connection, row['id'], 1, 0)
results.append(dict(session_id=row['id'], title=row['title'], source=row['source'],

View File

@@ -436,27 +436,38 @@ class _ProviderDiscovery:
try:
response = await client.aio.models.list()
results = []
for model in response.page:
supported = set(model.supported_actions or [])
if "generateContent" not in supported:
continue
model_id = model.name
metadata = (
await self._models_dev_model(
"google",
model_id,
use_proxy=use_proxy,
tokens: set[str] = set()
for _page in range(100):
for model in response.page:
supported = set(model.supported_actions or [])
if "generateContent" not in supported:
continue
model_id = model.name
metadata = (
await self._models_dev_model(
"google",
model_id,
use_proxy=use_proxy,
)
or {}
)
or {}
)
results.append(
self._normalize_model_record(
model_id=model_id,
display_name=model.display_name or metadata.get("name") or model_id,
metadata=metadata,
source="provider",
results.append(
self._normalize_model_record(
model_id=model_id,
display_name=model.display_name or metadata.get("name") or model_id,
metadata=metadata,
source="provider",
)
)
)
token = response.config.get("page_token")
if not token:
break
if token in tokens:
raise LLMProviderError("Google 模型列表分页游标重复")
tokens.add(token)
await response.next_page()
else:
raise LLMProviderError("Google 模型列表分页超过上限")
return sorted(results, key=lambda item: item["name"].lower())
finally:
try:

View File

@@ -669,8 +669,23 @@ class AgentMcpManager:
session_manager = await _open_mcp_session(normalized_server)
async with session_manager as session:
await self.initialize_session(session)
result = await session.request("tools/list")
tools_payload = result.get("tools", []) if isinstance(result, dict) else []
tools_payload = []
cursors: set[str] = set()
params = None
for _page in range(100):
result = await session.request("tools/list", params) if params else await session.request("tools/list")
if not isinstance(result, dict) or not isinstance(result.get("tools", []), list):
raise ValueError("MCP 工具列表响应格式无效")
tools_payload.extend(result.get("tools", []))
cursor = result.get("nextCursor")
if cursor is None or cursor == "":
break
if not isinstance(cursor, str) or cursor in cursors:
raise ValueError("MCP 工具列表分页游标无效或重复")
cursors.add(cursor)
params = {"cursor": cursor}
else:
raise ValueError("MCP 工具列表分页超过上限")
tool_specs: list[AgentMcpToolSpec] = []
for item in tools_payload:
if not isinstance(item, dict) or not item.get("name"):

View File

@@ -976,7 +976,7 @@ class SubAgentTaskControlMiddleware(AgentMiddleware):
if cancel_requested is not None:
cancel_requested.discard(task)
record = self._tasks.get(task_id)
if record:
if record and record.task is task:
record.finished_at = datetime.now()
if task.cancelled():
return
@@ -1005,12 +1005,7 @@ class SubAgentTaskControlMiddleware(AgentMiddleware):
name=task_id,
)
record.task = task
task.add_done_callback(
lambda finished_task: self._mark_task_finished(
task_id,
finished_task,
)
)
task.add_done_callback(self._task_finished_callback(task_id))
self._tasks[task_id] = record
records.append(record)
logger.info(
@@ -1109,10 +1104,14 @@ class SubAgentTaskControlMiddleware(AgentMiddleware):
"""
有界取消旧任务后复用 task_id 启动更新后的子代理任务。
"""
if not self._accepting_tasks or self._tasks.get(record.task_id) is not record:
return False, "子代理任务控制器正在关闭或任务已被回收,更新被拒绝。"
if not record.task.done():
pending = await self._cancel_records([record])
if pending:
return False, "旧子代理任务未能在取消窗口内收敛,更新被拒绝。"
if not self._accepting_tasks or self._tasks.get(record.task_id) is not record:
return False, "子代理任务控制器正在关闭或任务已被回收,更新被拒绝。"
record.description = description.strip()
record.terminal_sessions = terminal_sessions or []
record.started_at = None

View File

@@ -334,6 +334,8 @@ class AgentRuntimeManager:
self.bundled_defaults_dir = bundled_defaults_dir or (Path(__file__).parent / "defaults")
self._cache_lock = threading.Lock()
self._cached_signature: Optional[tuple[tuple[str, int, int], ...]] = None
# 磁盘观测签名与已加载配置版本分开,检查新文件不能提前使旧配置命中。
self._observed_signature: Optional[tuple[tuple[str, int, int], ...]] = None
self._cached_config: Optional[AgentRuntimeConfig] = None
self._cached_signature_checked_at = 0.0
self._signature_check_interval = 1.0
@@ -388,6 +390,7 @@ class AgentRuntimeManager:
"""
with self._cache_lock:
self._cached_signature = None
self._observed_signature = None
self._cached_config = None
self._cached_signature_checked_at = 0.0
self._layout_ready = False
@@ -418,14 +421,14 @@ class AgentRuntimeManager:
now = time.monotonic()
with self._cache_lock:
if (
self._cached_signature is not None
self._observed_signature is not None
and now - self._cached_signature_checked_at < self._signature_check_interval
):
return self._cached_signature
return self._observed_signature
signature = self._build_signature()
with self._cache_lock:
self._cached_signature = signature
self._observed_signature = signature
self._cached_signature_checked_at = now
return signature

View File

@@ -669,7 +669,7 @@ class SkillHelper(metaclass=WeakSingleton):
if not skill.repo_url or not skill.skill_path:
return False, "技能来源信息不完整,无法安装"
repo = self._parse_market_repo(skill.repo_url)
repo = self._parse_market_repo(skill.path) if "/tree/" in skill.path else self._parse_market_repo(skill.repo_url)
if not repo:
return False, "技能市场地址无效"
@@ -1094,8 +1094,7 @@ class SkillHelper(metaclass=WeakSingleton):
"""
下载市场仓库压缩包,并在缺省分支之间做回退尝试。
"""
branches = [repo.get("branch")] if repo.get("branch") else []
branches.extend([branch for branch in _DEFAULT_BRANCHES if branch not in branches])
branches = [repo["branch"]] if repo.get("branch") else list(_DEFAULT_BRANCHES)
for branch in branches:
archive_url = (
f"https://codeload.github.com/{repo['owner']}/{repo['repo']}/zip/refs/heads/{branch}"

View File

@@ -707,21 +707,39 @@ class _TerminalSessionManager:
同一终端的关闭串行执行,真实收尾前不丢弃进程或输出读取器。
"""
async with session.termination_lock:
if session.status == "running":
if session.status == "running" or os.name == "posix":
session.kill_requested = True
self._send_signal(session, signal.SIGTERM)
if not await self._wait_for_exit(session):
if session.status == "running":
if session.status == "running" or os.name == "posix":
self._send_signal(session, _KILL_SIGNAL)
if not await self._wait_for_exit(session):
logger.error(f"终端会话关闭超时: session_id={session.session_id}, pid={session.pid}")
return False
# 组长先结束也不代表组内后代已退出;关闭该owner时完成整组最终收口。
if os.name == "posix" and not await self._kill_remaining_process_group(session):
return False
if any(not task.done() for task in session.reader_tasks):
return False
session.finish_output()
session.close_pty()
return True
async def _kill_remaining_process_group(self, session: _TerminalSession) -> bool:
"""
有界重试组长退出后的进程组收口,兼容 macOS 后代退出期间的临时权限错误。
"""
deadline = asyncio.get_running_loop().time() + TERMINAL_KILL_GRACE_SECONDS
while True:
try:
self._send_signal(session, _KILL_SIGNAL)
return True
except PermissionError:
if asyncio.get_running_loop().time() >= deadline:
logger.error(f"终端进程组关闭被拒绝: session_id={session.session_id}, pid={session.pid}")
return False
await asyncio.sleep(TERMINAL_PTY_POLL_INTERVAL)
@staticmethod
async def _wait_for_exit(session: _TerminalSession) -> bool:
"""
@@ -830,7 +848,7 @@ class _TerminalSessionManager:
@staticmethod
def _send_signal(session: _TerminalSession, sig: int) -> None:
"""
优先向进程组发信号,失败时回退到单进程。
按平台向所属进程组或进程发信号,已消失的目标视为收尾完成。
"""
try:
if os.name == "posix":
@@ -851,6 +869,21 @@ class _TerminalSessionManager:
"""
return sum(1 for session in self._sessions.values() if session.status == "running")
@staticmethod
def _process_group_exists(session: _TerminalSession) -> bool:
"""
保留组长退出但仍有后代的终端归属,避免过期清理先丢弃唯一收口句柄。
"""
if os.name != "posix":
return session.status == "running"
try:
os.killpg(session.pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
def _cleanup_finished_sessions_locked(self) -> None:
"""
清理已经结束且超过保留时间的会话。
@@ -861,6 +894,7 @@ class _TerminalSessionManager:
for session_id, session in self._sessions.items()
if session.status != "running"
and now - session.updated_at > TERMINAL_RETENTION_SECONDS
and not self._process_group_exists(session)
]
for session_id in expired_ids:
session = self._sessions.pop(session_id)

View File

@@ -5,7 +5,25 @@ Agent 文件写入工具的共享辅助函数。
import hashlib
import os
import tempfile
import threading
from pathlib import Path
from weakref import WeakValueDictionary
_write_locks: WeakValueDictionary[str, threading.Lock] = WeakValueDictionary()
_write_locks_guard = threading.Lock()
def _write_lock(path: Path) -> threading.Lock:
"""
为同一规范目标保留进程内互斥,闲置后自动回收路径锁。
"""
key = os.path.normcase(str(path.resolve()))
with _write_locks_guard:
lock = _write_locks.get(key)
if lock is None:
lock = threading.Lock()
_write_locks[key] = lock
return lock
class FileVersionConflictError(RuntimeError):
@@ -29,9 +47,26 @@ def atomic_write_text(
path: Path,
content: str,
expected_sha256: str | None = None,
) -> None:
*,
overwrite: bool = True,
) -> str:
"""
校验目标版本后,在同目录写入临时文件并原子替换文本。
在同目标写锁内校验版本并原子替换,返回本次提交内容的SHA256。
:param path: 已通过权限检查的目标路径
:param content: 本次完整文本内容
:param expected_sha256: 当前版本摘要;None表示未提供版本前提
:param overwrite: False使用原子排他创建,已有目标不得替换
:return: 本次实际提交文本的SHA256,不重新读取可能被后续调用修改的文件
:raises FileVersionConflictError: 版本变化或排他创建时目标已存在
"""
with _write_lock(path):
return _write_text_locked(path, content, expected_sha256, overwrite=overwrite)
def _write_text_locked(path: Path, content: str, expected_sha256: str | None, *, overwrite: bool) -> str:
"""
在已持有目标锁时写入临时文件,禁止覆盖使用原子link拒绝已存在目标。
"""
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temp_name = tempfile.mkstemp(
@@ -55,7 +90,14 @@ def atomic_write_text(
raise FileVersionConflictError(str(path))
if path.exists():
os.chmod(temp_path, path.stat().st_mode)
os.replace(temp_path, path)
if overwrite:
os.replace(temp_path, path)
else:
try:
os.link(temp_path, path)
except FileExistsError as error:
raise FileVersionConflictError(str(path)) from error
return hashlib.sha256(content.encode("utf-8")).hexdigest()
finally:
if temp_path.exists():
temp_path.unlink()

View File

@@ -348,11 +348,9 @@ class ApplyPatchTool(MoviePilotTool):
f"错误:文件 {resolved_path} 在应用补丁期间被创建,拒绝覆盖。"
"请确认文件状态后重新应用补丁。"
)
await self.run_blocking(
"default", atomic_write_text, local_path, new_content, sha256
)
new_sha256 = await self.run_blocking(
"default", calculate_file_sha256, local_path
"default", atomic_write_text, local_path, new_content, sha256,
overwrite=file_patch.operation != "add",
)
verb = "新增" if file_patch.operation == "add" else "更新"
results.append(f"{verb} {resolved_path}(sha256={new_sha256})")

View File

@@ -151,16 +151,13 @@ class EditFileTool(MoviePilotTool):
new_text,
-1 if replace_all else 1,
)
await self.run_blocking(
new_sha256 = await self.run_blocking(
"default",
atomic_write_text,
local_path,
new_content,
current_sha256,
)
new_sha256 = await self.run_blocking(
"default", calculate_file_sha256, local_path
)
logger.info(
f"成功编辑文件 {resolved_path},替换了 {replacement_count} 处内容"

View File

@@ -224,7 +224,7 @@ class ViewImageTool(MoviePilotTool):
if has_file_path:
resolved_path, access_error = await self._check_local_file_access(
clean_file_path,
operation="读取图片",
operation="读取",
)
if access_error:
return self._failure("local_path_access_denied", access_error, source_type)

View File

@@ -129,15 +129,13 @@ class WriteFileTool(MoviePilotTool):
"请重新读取文件并基于最新内容写入。"
)
await self.run_blocking(
new_sha256 = await self.run_blocking(
"default",
atomic_write_text,
local_path,
content,
current_sha256,
)
new_sha256 = await self.run_blocking(
"default", calculate_file_sha256, local_path
overwrite=overwrite,
)
logger.info(f"成功写入文件 {resolved_path}")

View File

@@ -322,6 +322,8 @@ class MoviePilotToolsManager:
"""
根据字段类型规范化单个值
"""
if value is None:
return None
if field_type == "integer" and isinstance(value, str):
try:
return int(value)

View File

@@ -583,9 +583,12 @@ async def save_web_agent_display_snapshot(
client_session_id: Optional[str] = None,
service: Optional[AgentChatService] = None,
persistence: Optional[AgentChatPersistenceService] = None,
append: bool = False,
) -> None:
"""
保存 WebAgent 展示快照前重新检查归属,避免入口之后的会话变更造成越权覆盖。
:param append: 后台单轮结果为True,按消息ID追加合并;前端完整快照保留替换合同
"""
if service is None:
# 直接调用该内部 helper 时没有 FastAPI 依赖注入上下文。
@@ -596,7 +599,8 @@ async def save_web_agent_display_snapshot(
if persistence is None:
# 直接调用该内部 helper 时没有 FastAPI 依赖注入上下文。
persistence = get_configured_agent_chat_persistence()
await persistence.async_save_display_messages(
save_messages = persistence.async_append_display_messages if append else persistence.async_save_display_messages
await save_messages(
session_id=session_id,
user_id=(existing_chat.user_id if existing_chat else str(current_user.id)),
username=(existing_chat.username if existing_chat else current_user.name),
@@ -1569,6 +1573,7 @@ def _build_traditional_web_agent_stream(
client_session_id=command.session_id or session_id,
service=service,
persistence=persistence,
append=True,
)
except Exception as err:
logger.error(f"保存WebAgent传统消息快照失败: {str(err)}")

View File

@@ -346,6 +346,7 @@ def _build_web_agent_event_generator(
client_session_id=command.session_id or session_id,
service=service,
persistence=persistence,
append=True,
)
except Exception as err:
logger.error(f"保存WebAgent展示历史失败:{err}")

View File

@@ -4,6 +4,7 @@
import asyncio
import base64
import json
import mimetypes
import re
import threading
@@ -146,7 +147,7 @@ class MessageChain(ChainBase):
_ai_prefix = "/ai"
_no_ai_prefix = "/noai"
# 用户会话信息 {userid: (session_id, last_time)}
# 用户会话信息按渠道、接入源与用户组合键隔离,旧直接调用保留原始键。
_user_sessions: Dict[Union[str, int], tuple[str, datetime]] = {}
# 会话超时时间(分钟)
_session_timeout_minutes: int = 24 * 60
@@ -186,10 +187,24 @@ class MessageChain(ChainBase):
"""
用类级兼容映射构建可测试的用户会话服务。
"""
def expired(session_id: str, user_key: Union[str, int]) -> None:
"""
映射键只隔离入口,会话回收仍使用真正的渠道用户身份。
"""
user_id = user_key
if isinstance(user_key, str) and user_key.startswith("message:"):
try:
identity = json.loads(user_key.removeprefix("message:"))
if isinstance(identity, list) and len(identity) == 3 and isinstance(identity[2], str):
user_id = identity[2]
except ValueError:
pass
self._schedule_agent_session_clear(session_id, user_id)
return MessageSessionService(
sessions=self._user_sessions,
timeout_minutes=self._session_timeout_minutes,
expired_handler=self._schedule_agent_session_clear,
expired_handler=expired,
)
def _plugin_input_interaction_handler(self) -> PluginInputInteractionHandler:
@@ -466,7 +481,7 @@ class MessageChain(ChainBase):
if images or audio_refs or files or has_audio_input:
return False
session_info = self._user_sessions.get(userid)
session_info = self._user_sessions.get(self._session_user_key(userid, channel, source))
if not session_info:
return False
session_id, _ = session_info
@@ -965,7 +980,7 @@ class MessageChain(ChainBase):
prompt=request.prompt,
selected_label=option.label,
)
self._bind_session_id(context.user_id, request.session_id)
self._bind_session_id(self._session_user_key(context.user_id, context.channel, context.source), request.session_id)
return self._handle_ai_message(
text=selected_text,
channel=context.channel,
@@ -1005,6 +1020,18 @@ class MessageChain(ChainBase):
text=feedback_text,
)
@staticmethod
def _session_user_key(userid: Union[str, int], channel: NotificationChannel, source: Optional[str]) -> str:
"""
以无歧义序列化生成渠道和接入源隔离的会话键,不回退读取旧裸用户绑定。
:param userid: 渠道内原始用户标识
:param channel: 接收消息的渠道
:param source: 该渠道的配置实例,未提供时使用空标识
:return: 内部会话映射键,不作为发送消息的用户ID
"""
return "message:" + json.dumps([channel.value, source or "", str(userid)], ensure_ascii=False, separators=(",", ":"))
def _get_or_create_session_id(self, userid: Union[str, int]) -> str:
"""
获取或创建会话ID
@@ -1033,7 +1060,7 @@ class MessageChain(ChainBase):
:param userid: 用户 ID
:param session_id: 智能体会话 ID
"""
self._bind_session_id(userid, session_id)
self._bind_session_id(self._session_user_key(userid, NotificationChannel.WebAgent, "web-agent"), session_id)
def _record_user_message(
self,
@@ -1084,7 +1111,7 @@ class MessageChain(ChainBase):
"""
清除用户会话(远程命令接口)
"""
session_id = self._message_session_service().clear(userid)
session_id = self._message_session_service().clear(self._session_user_key(userid, channel, source))
if session_id:
logger.info(f"已清除用户 {userid} 的会话: {session_id}")
@@ -1124,7 +1151,7 @@ class MessageChain(ChainBase):
停止后用户仍可继续对话。
"""
# 查找用户的会话ID(不弹出,保留会话)
session_info = self._message_session_service().get(userid)
session_info = self._message_session_service().get(self._session_user_key(userid, channel, source))
if session_info:
session_id, _ = session_info
manager = get_running_agent_manager()
@@ -1303,7 +1330,7 @@ class MessageChain(ChainBase):
"""
查询当前用户的智能体会话状态。
"""
session_info = self._message_session_service().get(userid)
session_info = self._message_session_service().get(self._session_user_key(userid, channel, source))
if not session_info:
self.post_message(
Message(
@@ -1408,8 +1435,9 @@ class MessageChain(ChainBase):
)
return False
session_id = session_id or self._get_or_create_session_id(userid)
self._bind_session_id(userid, session_id)
session_key = self._session_user_key(userid, channel, source)
session_id = session_id or self._get_or_create_session_id(session_key)
self._bind_session_id(session_key, session_id)
# 将可直接输入给 LLM 的附件统一转换为 data URL
original_images = images

View File

@@ -32,6 +32,7 @@ from app.application.messaging.skill import (
reset_skill_catalog_provider,
)
from app.runtime.events import Event, eventmanager
from app.runtime.execution import run_in_threadpool_to_completion
from app.runtime.log import logger
from app.runtime.settings import get_runtime_setting
from app.schemas.types import EventType
@@ -124,9 +125,10 @@ def _get_agent_manager() -> Any:
"""
if agent_manager is not None:
return agent_manager
manager = get_runtime_agent_manager()
if _agent_data_context is not None:
return _get_injected_agent_manager()
return get_runtime_agent_manager()
manager.configure_data_context(_agent_data_context)
return manager
def _get_running_agent_manager() -> Any | None:
@@ -236,14 +238,15 @@ class AgentInitializer:
try:
self._shutdown_started = False
self._shutdown_complete = False
if agent_manager is not None or _agent_data_context is not None:
if agent_manager is not None:
if not get_runtime_setting("AI_AGENT_ENABLE"):
logger.info("AI智能体功能未启用")
return True
self._manager = agent_manager if agent_manager is not None else _get_injected_agent_manager()
self._manager = agent_manager
self._compat_injected = True
await self._manager.initialize()
else:
await self._bind_runtime_data()
self._manager = await activate_agent_service()
self._compat_injected = False
if self._manager is None:
@@ -257,6 +260,14 @@ class AgentInitializer:
logger.error(f"AI智能体管理器初始化失败: {e}")
return False
@staticmethod
async def _bind_runtime_data() -> None:
"""
首启及关闭后重新启用前,在受控线程给canonical实例绑定同一批数据端口。
"""
if _agent_data_context is not None and get_runtime_setting("AI_AGENT_ENABLE"):
await run_in_threadpool_to_completion(_get_agent_manager)
async def handle_config_changed(self, event: Event) -> None:
"""
仅在 manifest watch 命中时协调 service,关闭态保持 fail closed。
@@ -265,6 +276,8 @@ class AgentInitializer:
if not changed_keys or self._compat_injected or self._shutdown_started or self._shutdown_complete:
return
try:
if "AI_AGENT_ENABLE" in changed_keys:
await self._bind_runtime_data()
self._manager = await reconcile_agent_service(
reason="agent_service_config_changed",
changed_keys=changed_keys,