sycommon-python-lib 0.2.10a27__py3-none-any.whl → 0.2.10a28__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sycommon/agent/agent_manager.py +110 -2
- {sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/METADATA +1 -1
- {sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/RECORD +6 -6
- {sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/WHEEL +0 -0
- {sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/entry_points.txt +0 -0
- {sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/top_level.txt +0 -0
sycommon/agent/agent_manager.py
CHANGED
|
@@ -42,6 +42,7 @@ Agent 管理器
|
|
|
42
42
|
|
|
43
43
|
import asyncio
|
|
44
44
|
import threading
|
|
45
|
+
import time
|
|
45
46
|
from typing import Any, Dict, List, Optional, Union
|
|
46
47
|
from pathlib import Path
|
|
47
48
|
|
|
@@ -83,6 +84,12 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
83
84
|
self._sandbox_backends: Dict[str, HTTPSandboxBackend] = {}
|
|
84
85
|
# 使用线程锁保护字典,避免在 loop 重启后 asyncio.Lock 失效的问题
|
|
85
86
|
self._lock = threading.Lock()
|
|
87
|
+
# 空闲淘汰:记录每个 agent 最近活跃时间(monotonic 秒)。
|
|
88
|
+
# get/get_or_create/create 命中即 touch;淘汰循环只清超过
|
|
89
|
+
# idle_ttl 的条目。0/None = 禁用(默认禁用,长跑服务按需开启)。
|
|
90
|
+
self._last_used: Dict[str, float] = {}
|
|
91
|
+
self._idle_ttl: Optional[float] = None
|
|
92
|
+
self._reaper_task: Optional[asyncio.Task] = None
|
|
86
93
|
|
|
87
94
|
def _get_async_lock(self) -> asyncio.Lock:
|
|
88
95
|
"""获取当前 event loop 的 asyncio.Lock,避免跨 loop 问题"""
|
|
@@ -133,6 +140,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
133
140
|
# 保存引用
|
|
134
141
|
with self._lock:
|
|
135
142
|
self._agents[user_id] = agent
|
|
143
|
+
self._last_used[user_id] = time.monotonic()
|
|
136
144
|
self._agent_configs[user_id] = AgentInfo(
|
|
137
145
|
user_id=user_id,
|
|
138
146
|
type="agent",
|
|
@@ -188,6 +196,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
188
196
|
# 保存引用
|
|
189
197
|
with self._lock:
|
|
190
198
|
self._agents[user_id] = team
|
|
199
|
+
self._last_used[user_id] = time.monotonic()
|
|
191
200
|
self._agent_configs[user_id] = AgentInfo(
|
|
192
201
|
user_id=user_id,
|
|
193
202
|
type="team",
|
|
@@ -200,6 +209,90 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
200
209
|
SYLogger.info(f"[AgentManager] 创建数字团队: {user_id}, 成员: {[m.name for m in members]}")
|
|
201
210
|
return team
|
|
202
211
|
|
|
212
|
+
def _touch(self, user_id: str) -> None:
|
|
213
|
+
"""记录/刷新 agent 的最近活跃时间(淘汰判据)。
|
|
214
|
+
|
|
215
|
+
Deprecated: 保留兼容旧调用方;新代码用 _touch_if_present
|
|
216
|
+
(语义相同,命名与 get_agent 内部路径统一)。
|
|
217
|
+
"""
|
|
218
|
+
self._touch_if_present(user_id)
|
|
219
|
+
|
|
220
|
+
def set_idle_ttl(self, ttl_seconds: Optional[float], reaper_interval: float = 300.0) -> None:
|
|
221
|
+
"""开启/关闭空闲淘汰。
|
|
222
|
+
|
|
223
|
+
ttl_seconds=None/0 关闭淘汰并停掉后台任务;>0 时启动(或重启)
|
|
224
|
+
后台淘汰循环,每 reaper_interval 秒清理一次空闲超 TTL 的 agent。
|
|
225
|
+
|
|
226
|
+
幂等:重复调用以最新参数为准;先停旧任务再起新任务。
|
|
227
|
+
必须在 event loop 内调用(asyncio.create_task 需要运行中的 loop);
|
|
228
|
+
无运行 loop 时仅记录 TTL、不起后台任务(下次调用再起),并告警。
|
|
229
|
+
"""
|
|
230
|
+
if ttl_seconds and ttl_seconds > 0:
|
|
231
|
+
self._idle_ttl = float(ttl_seconds)
|
|
232
|
+
else:
|
|
233
|
+
self._idle_ttl = None
|
|
234
|
+
|
|
235
|
+
old = self._reaper_task
|
|
236
|
+
self._reaper_task = None
|
|
237
|
+
if old is not None and not old.done():
|
|
238
|
+
old.cancel()
|
|
239
|
+
if self._idle_ttl is not None:
|
|
240
|
+
try:
|
|
241
|
+
self._reaper_task = asyncio.create_task(self._reap_idle_loop(reaper_interval))
|
|
242
|
+
except RuntimeError:
|
|
243
|
+
# 无运行 event loop(如同步启动路径):不起后台任务。
|
|
244
|
+
# reap_idle 仍可被外部周期性调用(判据已就绪)。
|
|
245
|
+
self._reaper_task = None
|
|
246
|
+
SYLogger.warning(
|
|
247
|
+
"[AgentManager] set_idle_ttl 无运行 event loop,未起淘汰循环"
|
|
248
|
+
"(TTL 已记录,可手动周期调 reap_idle)")
|
|
249
|
+
|
|
250
|
+
async def _reap_idle_loop(self, interval: float) -> None:
|
|
251
|
+
"""后台淘汰循环:周期性销毁空闲超 TTL 的 agent。
|
|
252
|
+
|
|
253
|
+
CancelledError 正常退出(set_idle_ttl 关闭/重启时 cancel);
|
|
254
|
+
其他异常记 warning 后继续(淘汰失败不应杀死循环)。
|
|
255
|
+
"""
|
|
256
|
+
while True:
|
|
257
|
+
try:
|
|
258
|
+
await asyncio.sleep(interval)
|
|
259
|
+
await self.reap_idle()
|
|
260
|
+
except asyncio.CancelledError:
|
|
261
|
+
return
|
|
262
|
+
except Exception as e: # noqa: BLE001 - 守护循环必须吞异常续跑
|
|
263
|
+
SYLogger.warning(f"[AgentManager] 空闲淘汰循环异常(继续运行): {e}")
|
|
264
|
+
|
|
265
|
+
async def reap_idle(self) -> List[str]:
|
|
266
|
+
"""销毁所有空闲超过 TTL 的 agent,返回被销毁的 user_id 列表。
|
|
267
|
+
|
|
268
|
+
判据快照在锁内取;cleanup()(含沙箱 HTTP 调用)在锁外逐个执行;
|
|
269
|
+
destroy 前用 _touch 时间复核,避免清理期间刚被复用的 agent 误杀。
|
|
270
|
+
TTL 未设置时为 no-op。
|
|
271
|
+
"""
|
|
272
|
+
if self._idle_ttl is None:
|
|
273
|
+
return []
|
|
274
|
+
now = time.monotonic()
|
|
275
|
+
with self._lock:
|
|
276
|
+
expired = [
|
|
277
|
+
uid for uid, ts in self._last_used.items()
|
|
278
|
+
if now - ts > self._idle_ttl and uid in self._agents
|
|
279
|
+
]
|
|
280
|
+
destroyed: List[str] = []
|
|
281
|
+
for uid in expired:
|
|
282
|
+
# 复核(取当下时间而非快照 now):cleanup 可能耗时(沙箱 HTTP),
|
|
283
|
+
# 期间该 agent 可能刚被 touch(活跃中)——last 被推到当下后
|
|
284
|
+
# now2-last<=ttl 自然跳过,不会误杀在用 agent。
|
|
285
|
+
now2 = time.monotonic()
|
|
286
|
+
with self._lock:
|
|
287
|
+
last = self._last_used.get(uid)
|
|
288
|
+
if last is None or now2 - last <= self._idle_ttl:
|
|
289
|
+
continue
|
|
290
|
+
if await self.destroy_agent(uid):
|
|
291
|
+
destroyed.append(uid)
|
|
292
|
+
if destroyed:
|
|
293
|
+
SYLogger.info(f"[AgentManager] 空闲淘汰: {len(destroyed)} 个 ({destroyed})")
|
|
294
|
+
return destroyed
|
|
295
|
+
|
|
203
296
|
async def get_agent(self, user_id: str) -> Optional[Union[DeepAgent, MultiAgentTeam]]:
|
|
204
297
|
"""
|
|
205
298
|
获取已存在的 Agent
|
|
@@ -211,7 +304,17 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
211
304
|
DeepAgent | MultiAgentTeam | None: Agent 实例或 None
|
|
212
305
|
"""
|
|
213
306
|
with self._lock:
|
|
214
|
-
|
|
307
|
+
agent = self._agents.get(user_id)
|
|
308
|
+
if agent is not None:
|
|
309
|
+
# 命中即视为活跃(消费方拿到后可能直接 chat,不走
|
|
310
|
+
# get_or_create)——刷新淘汰判据,避免在用中被 reap。
|
|
311
|
+
self._last_used[user_id] = time.monotonic()
|
|
312
|
+
return agent
|
|
313
|
+
|
|
314
|
+
def _touch_if_present(self, user_id: str) -> None:
|
|
315
|
+
with self._lock:
|
|
316
|
+
if user_id in self._agents:
|
|
317
|
+
self._last_used[user_id] = time.monotonic()
|
|
215
318
|
|
|
216
319
|
async def get_or_create_agent(
|
|
217
320
|
self,
|
|
@@ -232,6 +335,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
232
335
|
"""
|
|
233
336
|
agent = await self.get_agent(user_id)
|
|
234
337
|
if agent and isinstance(agent, DeepAgent):
|
|
338
|
+
self._touch_if_present(user_id)
|
|
235
339
|
return agent
|
|
236
340
|
return await self.create_agent(user_id, config, project_root)
|
|
237
341
|
|
|
@@ -256,6 +360,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
256
360
|
"""
|
|
257
361
|
agent = await self.get_agent(user_id)
|
|
258
362
|
if agent and isinstance(agent, MultiAgentTeam):
|
|
363
|
+
self._touch_if_present(user_id)
|
|
259
364
|
return agent
|
|
260
365
|
return await self.create_team(user_id, members, config, project_root)
|
|
261
366
|
|
|
@@ -282,10 +387,12 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
282
387
|
SYLogger.warning(f"[AgentManager] Agent 清理失败 (user={user_id}): {e}")
|
|
283
388
|
|
|
284
389
|
with self._lock:
|
|
285
|
-
# 重新检查,防止并发 destroy
|
|
390
|
+
# 重新检查,防止并发 destroy(cleanup 在锁外执行期间
|
|
391
|
+
# 另一路可能已删;同时 _last_used 一并清理,避免判据字典残留)
|
|
286
392
|
if user_id not in self._agents:
|
|
287
393
|
return False
|
|
288
394
|
del self._agents[user_id]
|
|
395
|
+
self._last_used.pop(user_id, None)
|
|
289
396
|
if user_id in self._agent_configs:
|
|
290
397
|
del self._agent_configs[user_id]
|
|
291
398
|
if user_id in self._sandbox_backends:
|
|
@@ -360,6 +467,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
360
467
|
self._agents.clear()
|
|
361
468
|
self._agent_configs.clear()
|
|
362
469
|
self._sandbox_backends.clear()
|
|
470
|
+
self._last_used.clear()
|
|
363
471
|
|
|
364
472
|
SYLogger.info(f"[AgentManager] 清理所有 Agent: {count} 个")
|
|
365
473
|
return count
|
|
@@ -135,7 +135,7 @@ sycli/skills/__init__.py,sha256=0o9HuaDSvN-z0JZwlDSwU7WxtchQn7f0OtluIMgtC0Q,212
|
|
|
135
135
|
sycommon/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
136
136
|
sycommon/services.py,sha256=bGwsfKnm2CYNquesAJUqVu31kn5JXZmHvfjGkP0tjvA,31090
|
|
137
137
|
sycommon/agent/__init__.py,sha256=mxceAeUifQ-DKvWp7ZEJIFlmOCb5wpYHPGQw3rwEN8I,4378
|
|
138
|
-
sycommon/agent/agent_manager.py,sha256=
|
|
138
|
+
sycommon/agent/agent_manager.py,sha256=6GpQHk2PBX4UvvyosGKXtGkuEc5Jh0gi1iZqbyXjg04,18833
|
|
139
139
|
sycommon/agent/chat_events.py,sha256=t7qWa6OrIWLfqtd1AnqaVP67QWkn1JxpCBTZYQpoLuM,14226
|
|
140
140
|
sycommon/agent/deep_agent.py,sha256=p9MXKFHZvLQyiKpRbJ8mHKtLdFjQTydbYY-pv4ZbE3s,92793
|
|
141
141
|
sycommon/agent/multi_agent_team.py,sha256=GRXjjrPblsMnLjY2aB5CeFJ6-F7wvPhUc_JxNjfBXes,34789
|
|
@@ -387,8 +387,8 @@ sycommon/tools/timing.py,sha256=OiiE7P07lRoMzX9kzb8sZU9cDb0zNnqIlY5pWqHcnkY,2064
|
|
|
387
387
|
sycommon/tools/user_id.py,sha256=o-zsubGSR5rSSZf8Pk8B7AhE21ahDTTIW5JZmJO6Flw,4761
|
|
388
388
|
sycommon/xxljob/__init__.py,sha256=7eoBlQxv-B39IfRSCY2bkqdGYs1QRe1umAWd88VMEEM,86
|
|
389
389
|
sycommon/xxljob/xxljob_service.py,sha256=1yifwIBNGsCIxLnQjHKiBlbsigc_zvPH-dMTZcNxe-Q,7649
|
|
390
|
-
sycommon_python_lib-0.2.
|
|
391
|
-
sycommon_python_lib-0.2.
|
|
392
|
-
sycommon_python_lib-0.2.
|
|
393
|
-
sycommon_python_lib-0.2.
|
|
394
|
-
sycommon_python_lib-0.2.
|
|
390
|
+
sycommon_python_lib-0.2.10a28.dist-info/METADATA,sha256=5fDg8SzTtYliIyKL6xelnbe7_6OcHn_w3r9KNVmy7H4,8029
|
|
391
|
+
sycommon_python_lib-0.2.10a28.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
392
|
+
sycommon_python_lib-0.2.10a28.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
|
|
393
|
+
sycommon_python_lib-0.2.10a28.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
|
|
394
|
+
sycommon_python_lib-0.2.10a28.dist-info/RECORD,,
|
|
File without changes
|
{sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{sycommon_python_lib-0.2.10a27.dist-info → sycommon_python_lib-0.2.10a28.dist-info}/top_level.txt
RENAMED
|
File without changes
|