forked from Project-N-E-K-O/N.E.K.O
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_server.py
More file actions
2510 lines (2274 loc) · 115 KB
/
agent_server.py
File metadata and controls
2510 lines (2274 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mimetypes
import json
mimetypes.add_type("application/javascript", ".js")
import asyncio
import uuid
import logging
import time
import hashlib
from typing import Dict, Any, Optional, ClassVar, List
from datetime import datetime, timezone
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from utils.logger_config import setup_logging, ThrottledLogger
# Configure logging as early as possible so import-time failures are persisted.
logger, log_config = setup_logging(service_name="Agent", log_level=logging.INFO)
from config import TOOL_SERVER_PORT, USER_PLUGIN_SERVER_PORT
from utils.config_manager import get_config_manager
from main_logic.agent_event_bus import AgentServerEventBridge
try:
from brain.computer_use import ComputerUseAdapter
from brain.browser_use_adapter import BrowserUseAdapter
from brain.deduper import TaskDeduper
from brain.task_executor import DirectTaskExecutor
from brain.agent_session import get_session_manager
from brain.result_parser import (
parse_computer_use_result,
parse_browser_use_result,
parse_plugin_result,
_phrase as _rp_phrase,
_get_lang as _rp_lang,
)
except Exception as e:
logger.exception(f"[Agent] Module import failed during startup: {e}")
raise
app = FastAPI(title="N.E.K.O Tool Server")
class Modules:
computer_use: ComputerUseAdapter | None = None
browser_use: BrowserUseAdapter | None = None
deduper: TaskDeduper | None = None
task_executor: DirectTaskExecutor | None = None
user_plugin_app: FastAPI | None = None
user_plugin_http_server: Any = None
user_plugin_http_task: Any = None # threading.Thread (imported after class def)
_plugin_server_loop: Any = None
plugin_lifecycle_started: bool = False
_plugin_lifecycle_lock: Optional[asyncio.Lock] = None
# Task tracking
task_registry: Dict[str, Dict[str, Any]] = {}
executor_reset_needed: bool = False
analyzer_enabled: bool = False
analyzer_profile: Dict[str, Any] = {}
# Computer-use exclusivity and scheduling
computer_use_queue: Optional[asyncio.Queue] = None
computer_use_running: bool = False
active_computer_use_task_id: Optional[str] = None
active_computer_use_async_task: Optional[asyncio.Task] = None
# Browser-use task tracking
active_browser_use_task_id: Optional[str] = None
active_browser_use_bg_task: Optional[asyncio.Task] = None
# Agent feature flags (controlled by UI)
agent_flags: Dict[str, Any] = {"computer_use_enabled": False, "browser_use_enabled": False, "user_plugin_enabled": False}
# Notification queue for frontend (one-time messages)
notification: Optional[str] = None
# 使用统一的速率限制日志记录器(业务逻辑层面)
throttled_logger: "ThrottledLogger" = None # 延迟初始化
agent_bridge: AgentServerEventBridge | None = None
state_revision: int = 0
# Serialize analysis+dispatch to prevent duplicate tasks from concurrent analyze_request events
analyze_lock: Optional[asyncio.Lock] = None
# Per-lanlan fingerprint of latest user-turn payload already consumed by analyzer
last_user_turn_fingerprint: ClassVar[Dict[str, str]] = {}
capability_cache: Dict[str, Dict[str, Any]] = {
"computer_use": {"ready": False, "reason": "AGENT_PRECHECK_PENDING"},
"browser_use": {"ready": False, "reason": "AGENT_PRECHECK_PENDING"},
"user_plugin": {"ready": False, "reason": "AGENT_PRECHECK_PENDING"},
}
_background_tasks: ClassVar[set] = set()
_persistent_tasks: ClassVar[set] = set()
# Cancellable background task handles by logical task_id
task_async_handles: ClassVar[Dict[str, asyncio.Task]] = {}
# 插件名称缓存(避免频繁 HTTP 调用)
import threading
_plugin_name_cache: Dict[str, str] = {}
_plugin_name_cache_time: float = 0.0
_plugin_name_cache_lock = threading.Lock()
PLUGIN_NAME_CACHE_TTL: float = 30.0 # 缓存 30 秒
TASK_REGISTRY_CLEANUP_TTL: float = 300.0 # 已完成任务保留 5 分钟
DEFERRED_TASK_TIMEOUT: float = 3600.0 # deferred 任务超时 1 小时
_task_registry_last_cleanup: float = 0.0
def _cleanup_task_registry() -> List[Dict[str, Any]]:
"""清理 task_registry 中超过 5 分钟的已完成/失败/取消任务,防止内存泄漏;同时检查 deferred 任务超时
返回超时的 deferred 任务列表(需要发送 task_update 通知前端)
"""
global _task_registry_last_cleanup
now = time.time()
timed_out: List[Dict[str, Any]] = []
if now - _task_registry_last_cleanup < 60: # 最多每 60 秒清理一次
return timed_out
_task_registry_last_cleanup = now
to_remove = []
for tid, info in Modules.task_registry.items():
st = info.get("status")
# 检查 deferred 任务是否超时(防止绑定失败导致任务永远卡在 running)
if st == "running" and info.get("deferred_timeout"):
if now > info.get("deferred_timeout", float('inf')):
logger.warning("[TaskRegistry] Deferred task %s timed out, marking as failed", tid)
info["status"] = "failed"
info["end_time"] = _now_iso()
info["error"] = "Deferred task timeout (callback not received)"
# 收集超时任务,需要通知前端
timed_out.append({
"id": tid,
"status": "failed",
"type": info.get("type"),
"start_time": info.get("start_time"),
"end_time": info.get("end_time"),
"error": info.get("error"),
"params": info.get("params", {}),
"lanlan_name": info.get("lanlan_name"),
})
continue
if st not in ("completed", "failed", "cancelled"):
continue
end_time_str = info.get("end_time")
if end_time_str:
try:
end_dt = datetime.fromisoformat(end_time_str.replace("Z", "+00:00"))
age = (datetime.now(timezone.utc) - end_dt).total_seconds()
if age > TASK_REGISTRY_CLEANUP_TTL:
to_remove.append(tid)
except Exception:
to_remove.append(tid) # 解析失败的旧条目直接清理
else:
# 没有 end_time 的终态任务,用 start_time 估算
start_str = info.get("start_time", "")
try:
start_dt = datetime.fromisoformat(start_str.replace("Z", "+00:00"))
age = (datetime.now(timezone.utc) - start_dt).total_seconds()
if age > TASK_REGISTRY_CLEANUP_TTL * 2: # 宽松一点
to_remove.append(tid)
except Exception:
pass
for tid in to_remove:
del Modules.task_registry[tid]
if to_remove:
logger.debug("[TaskRegistry] Cleaned up %d completed tasks", len(to_remove))
return timed_out
def _bind_deferred_task(plugin_id: str, reminder_id: str, agent_task_id: str) -> None:
"""通过插件服务将 agent_task_id 关联到提醒记录,供 daemon 触发时回调使用。
bind_task 是快速操作(只写文件),触发 run 后短暂轮询等待完成。"""
try:
import time as _time
with httpx.Client(timeout=5.0, proxy=None, trust_env=False) as client:
# 1. 触发 bind_task entry
resp = client.post(
f"http://127.0.0.1:{USER_PLUGIN_SERVER_PORT}/runs",
json={
"plugin_id": plugin_id,
"entry_id": "bind_task",
"args": {"reminder_id": reminder_id, "agent_task_id": agent_task_id},
},
)
if resp.status_code != 200:
logger.warning("[Deferred] bind_task start HTTP %s", resp.status_code)
return
run_id = resp.json().get("run_id")
if not run_id:
return
# 2. 短暂轮询等待完成(bind_task 应在 <1s 内完成)
for _ in range(20):
_time.sleep(0.1)
r = client.get(f"http://127.0.0.1:{USER_PLUGIN_SERVER_PORT}/runs/{run_id}")
if r.status_code == 200:
if r.json().get("status", "") in ("succeeded", "failed", "canceled", "timeout"):
break
logger.info("[Deferred] bind_task done: plugin=%s reminder=%s agent_task=%s", plugin_id, reminder_id, agent_task_id)
except Exception as e:
logger.warning("[Deferred] bind failed: plugin=%s reminder=%s error=%s", plugin_id, reminder_id, e)
def _get_plugin_friendly_name(plugin_id: str) -> str | None:
"""获取插件的友好名称(用于 HUD 显示)
通过 HTTP 调用嵌入式插件服务的 /plugins 端点获取插件列表,
并使用缓存减少请求次数。使用线程锁保证多线程安全。
"""
global _plugin_name_cache, _plugin_name_cache_time
# 检查缓存(加锁读取)
now = time.time()
with _plugin_name_cache_lock:
if _plugin_name_cache and (now - _plugin_name_cache_time) < PLUGIN_NAME_CACHE_TTL:
return _plugin_name_cache.get(plugin_id)
# 缓存过期或为空,从嵌入式插件服务获取
new_cache = {}
cache_time = now
try:
with httpx.Client(timeout=1.0, proxy=None, trust_env=False) as client:
resp = client.get(f"http://127.0.0.1:{USER_PLUGIN_SERVER_PORT}/plugins")
if resp.status_code == 200:
data = resp.json()
plugins = data.get("plugins", [])
# 构建新缓存
for p in plugins:
if isinstance(p, dict):
pid = p.get("id")
pname = p.get("name")
if pid and pname:
new_cache[pid] = pname
elif pid:
new_cache[pid] = pid
# 更新全局缓存(加锁写入)
with _plugin_name_cache_lock:
_plugin_name_cache = new_cache
_plugin_name_cache_time = cache_time
return new_cache.get(plugin_id)
except Exception as e:
logger.warning("[AgentServer] Failed to fetch plugin names from port %s: %s", USER_PLUGIN_SERVER_PORT, e)
# HTTP 调用失败,尝试本地 state(兼容某些部署场景)
try:
from plugin.core.state import state
with state.acquire_plugins_read_lock():
meta = state.plugins.get(plugin_id)
if isinstance(meta, dict):
return meta.get("name") or meta.get("id")
except Exception:
pass
return None
def _rewire_computer_use_dependents() -> None:
"""Keep task_executor in sync after computer_use adapter refresh."""
try:
if Modules.task_executor is not None and hasattr(Modules.task_executor, "computer_use"):
Modules.task_executor.computer_use = Modules.computer_use
except Exception:
pass
def _try_refresh_computer_use_adapter(force: bool = False) -> bool:
"""
Best-effort refresh for computer-use adapter.
Useful when API key/model settings were fixed after agent_server startup.
Does NOT block on LLM connectivity — call ``_fire_agent_llm_connectivity_check``
afterwards to probe the endpoint asynchronously.
"""
current = Modules.computer_use
if not force and current is not None and getattr(current, "init_ok", False):
return True
try:
refreshed = ComputerUseAdapter()
Modules.computer_use = refreshed
_rewire_computer_use_dependents()
logger.info("[Agent] ComputerUse adapter rebuilt (connectivity pending)")
return True
except Exception as e:
logger.warning(f"[Agent] ComputerUse adapter refresh failed: {e}")
return False
def _get_throttled_logger() -> ThrottledLogger:
throttled = Modules.throttled_logger
if throttled is None:
throttled = ThrottledLogger(logger, interval=30.0)
Modules.throttled_logger = throttled
return throttled
async def _start_embedded_user_plugin_server() -> None:
"""Start the plugin HTTP server in a dedicated thread with its own event loop.
This isolates plugin HTTP handling from the agent's main event loop so that
heavy agent work (LLM calls, task execution, ZMQ) cannot starve plugin
requests and vice-versa.
"""
if Modules.user_plugin_http_server is not None:
return
_plugin_package_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugin")
if _plugin_package_root not in sys.path:
sys.path.insert(1, _plugin_package_root)
try:
from plugin.server.http_app import build_plugin_server_app
import uvicorn
except Exception as exc:
raise RuntimeError(f"failed to import embedded user plugin server: {exc}") from exc
if Modules.user_plugin_app is None:
Modules.user_plugin_app = build_plugin_server_app()
config = uvicorn.Config(
Modules.user_plugin_app,
host="127.0.0.1",
port=USER_PLUGIN_SERVER_PORT,
log_config=None,
backlog=4096,
timeout_keep_alive=30,
)
server = uvicorn.Server(config)
server.install_signal_handlers = lambda: None
Modules.user_plugin_http_server = server
ready = threading.Event()
startup_error: list[BaseException] = []
def _run_in_thread() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
Modules._plugin_server_loop = loop
async def _serve_and_signal():
task = asyncio.ensure_future(server.serve())
while not getattr(server, "started", False) and not task.done():
await asyncio.sleep(0.05)
if getattr(server, "started", False):
ready.set()
await task
try:
loop.run_until_complete(_serve_and_signal())
except Exception as exc:
startup_error.append(exc)
logger.warning("[Agent] Embedded plugin server thread exited: %s", exc)
finally:
ready.set() # unblock waiter even on failure
loop.close()
t = threading.Thread(target=_run_in_thread, name="plugin-server", daemon=True)
t.start()
Modules.user_plugin_http_task = t
started = await asyncio.to_thread(ready.wait, 10.0)
if not started or startup_error or not getattr(server, "started", False):
server.should_exit = True
detail = str(startup_error[0]) if startup_error else "timeout or server not started"
raise RuntimeError(f"embedded user plugin server failed: {detail}")
logger.info("[Agent] Embedded user plugin server started on 127.0.0.1:%s (isolated thread)", USER_PLUGIN_SERVER_PORT)
async def _stop_embedded_user_plugin_server() -> None:
"""Stop the plugin HTTP server running in its dedicated thread."""
server = Modules.user_plugin_http_server
thread = Modules.user_plugin_http_task
Modules.user_plugin_http_server = None
Modules.user_plugin_http_task = None
if server is not None:
server.should_exit = True
if thread is None:
return
await asyncio.to_thread(thread.join, 10.0)
if thread.is_alive():
logger.warning("[Agent] Embedded user plugin server thread did not exit in time")
if server is not None:
server.force_exit = True
async def _ensure_plugin_lifecycle_started() -> bool:
"""Start the plugin lifecycle (load & run plugins). Returns True on success."""
if Modules.plugin_lifecycle_started:
return True
if Modules._plugin_lifecycle_lock is None:
Modules._plugin_lifecycle_lock = asyncio.Lock()
async with Modules._plugin_lifecycle_lock:
if Modules.plugin_lifecycle_started:
return True
try:
from plugin.server.lifecycle import startup as plugin_lifecycle_startup
await plugin_lifecycle_startup()
Modules.plugin_lifecycle_started = True
logger.info("[Agent] Plugin lifecycle started")
return True
except Exception as exc:
logger.error("[Agent] Plugin lifecycle startup failed: %s", exc)
return False
async def _ensure_plugin_lifecycle_stopped() -> None:
"""Stop the plugin lifecycle (stop plugin processes, cleanup)."""
if not Modules.plugin_lifecycle_started:
return
if Modules._plugin_lifecycle_lock is None:
Modules._plugin_lifecycle_lock = asyncio.Lock()
async with Modules._plugin_lifecycle_lock:
if not Modules.plugin_lifecycle_started:
return
try:
from plugin.server.lifecycle import shutdown as plugin_lifecycle_shutdown
await plugin_lifecycle_shutdown()
logger.info("[Agent] Plugin lifecycle stopped")
except Exception as exc:
logger.warning("[Agent] Plugin lifecycle shutdown error: %s", exc)
finally:
Modules.plugin_lifecycle_started = False
async def _fire_user_plugin_capability_check() -> None:
"""Probe the user plugin server to determine if user_plugin capability is ready."""
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(3.0, connect=1.0), proxy=None, trust_env=False) as client:
r = await client.get(f"http://127.0.0.1:{USER_PLUGIN_SERVER_PORT}/plugins")
if r.status_code == 200:
data = r.json()
plugins = data.get("plugins", []) if isinstance(data, dict) else []
if plugins:
_set_capability("user_plugin", True, "")
logger.debug("[Agent] UserPlugin capability check passed (%d plugins)", len(plugins))
else:
_set_capability("user_plugin", False, "AGENT_NO_PLUGINS_FOUND")
logger.debug("[Agent] UserPlugin capability check: no plugins found")
else:
_set_capability("user_plugin", False, "AGENT_PLUGIN_SERVER_ERROR")
_get_throttled_logger().warning(
"user_plugin_capability_check_failed",
"[Agent] UserPlugin capability check failed: status %s",
r.status_code,
)
except Exception as e:
_set_capability("user_plugin", False, "AGENT_PLUGIN_SERVER_ERROR")
logger.debug("[Agent] UserPlugin capability check error: %s", e)
_llm_check_lock = asyncio.Lock()
async def _fire_agent_llm_connectivity_check() -> None:
"""Probe the shared Agent-LLM endpoint in a background thread.
Both ComputerUse and BrowserUse rely on the same ``agent`` model config,
so a single connectivity check covers both capabilities. Updates
``init_ok`` on the CUA adapter and refreshes the capability cache for
*both* computer_use and browser_use.
Uses a lock to prevent concurrent probes from racing.
"""
if _llm_check_lock.locked():
return
async with _llm_check_lock:
adapter = Modules.computer_use
if adapter is None:
return
def _probe():
return adapter.check_connectivity()
try:
ok = await asyncio.get_event_loop().run_in_executor(None, _probe)
reason = "" if ok else "AGENT_LLM_UNREACHABLE"
_set_capability("computer_use", ok, reason)
bu = Modules.browser_use
if bu is not None:
if not ok:
_set_capability("browser_use", False, reason)
elif not getattr(bu, "_ready_import", False):
_set_capability("browser_use", False, "AGENT_BROWSER_USE_NOT_INSTALLED")
else:
_set_capability("browser_use", True, "")
if ok:
logger.info("[Agent] Agent-LLM connectivity check passed")
else:
logger.warning("[Agent] Agent-LLM connectivity check failed: %s", reason)
if Modules.agent_flags.get("computer_use_enabled"):
Modules.agent_flags["computer_use_enabled"] = False
Modules.notification = json.dumps({"code": "AGENT_AUTO_DISABLED_COMPUTER", "details": {"reason_code": reason}})
if Modules.agent_flags.get("browser_use_enabled"):
Modules.agent_flags["browser_use_enabled"] = False
Modules.notification = json.dumps({"code": "AGENT_AUTO_DISABLED_BROWSER", "details": {"reason_code": reason}})
_bump_state_revision()
await _emit_agent_status_update()
except Exception as e:
logger.warning("[Agent] Agent-LLM connectivity check error: %s", e)
_set_capability("computer_use", False, "AGENT_LLM_UNREACHABLE")
_set_capability("browser_use", False, "AGENT_LLM_UNREACHABLE")
if Modules.agent_flags.get("computer_use_enabled"):
Modules.agent_flags["computer_use_enabled"] = False
if Modules.agent_flags.get("browser_use_enabled"):
Modules.agent_flags["browser_use_enabled"] = False
Modules.notification = json.dumps({"code": "AGENT_LLM_CHECK_ERROR"})
_bump_state_revision()
await _emit_agent_status_update()
def _bump_state_revision() -> int:
Modules.state_revision += 1
return Modules.state_revision
def _set_capability(name: str, ready: bool, reason: str = "") -> None:
def _normalize_precheck_reason(raw_reason: str) -> str:
text = str(raw_reason or "").strip()
if not text:
return ""
if text.startswith("AGENT_"):
return text
lower = text.lower()
# Normalize legacy Chinese/English free-text reasons into stable i18n codes.
if "未检查" in text or "not checked" in lower or "pending" in lower:
return "AGENT_PRECHECK_PENDING"
if "模型未配置" in text or "model not configured" in lower:
return "AGENT_MODEL_NOT_CONFIGURED"
if "api url 未配置" in lower or "url not configured" in lower:
return "AGENT_URL_NOT_CONFIGURED"
if "api key 未配置" in lower or "key not configured" in lower:
return "AGENT_KEY_NOT_CONFIGURED"
if "endpoint not configured" in lower or "api 未配置" in lower:
return "AGENT_ENDPOINT_NOT_CONFIGURED"
if "pyautogui" in lower and ("not installed" in lower or "未安装" in text):
return "AGENT_PYAUTOGUI_NOT_INSTALLED"
if "browser-use" in lower and ("not installed" in lower or "未安装" in text):
return "AGENT_BROWSER_USE_NOT_INSTALLED"
if "not initialized" in lower or "初始化失败" in text:
return "AGENT_NOT_INITIALIZED"
if "未发现可用插件" in text or "no plugins" in lower:
return "AGENT_NO_PLUGINS_FOUND"
if "plugin server" in lower or "插件服务" in text or "user_plugin server responded" in lower:
return "AGENT_PLUGIN_SERVER_ERROR"
if "unreachable" in lower or "连接失败" in text or "connectivity" in lower:
return "AGENT_LLM_UNREACHABLE"
return "AGENT_LLM_UNREACHABLE"
prev = Modules.capability_cache.get(name, {})
normalized_reason = _normalize_precheck_reason(reason)
Modules.capability_cache[name] = {"ready": bool(ready), "reason": normalized_reason}
if prev.get("ready") != bool(ready) or prev.get("reason", "") != normalized_reason:
_bump_state_revision()
def _collect_existing_task_descriptions(lanlan_name: Optional[str] = None) -> list[tuple[str, str]]:
"""Return list of (task_id, description) for queued/running tasks, optionally filtered by lanlan_name."""
items: list[tuple[str, str]] = []
for tid, info in Modules.task_registry.items():
try:
if info.get("status") in ("queued", "running"):
if lanlan_name and info.get("lanlan_name") not in (None, lanlan_name):
continue
params = info.get("params") or {}
desc = params.get("query") or params.get("instruction") or ""
if desc:
items.append((tid, desc))
except Exception:
continue
return items
async def _is_duplicate_task(query: str, lanlan_name: Optional[str] = None) -> tuple[bool, Optional[str]]:
"""Use LLM to judge if query duplicates any existing queued/running task."""
try:
if not Modules.deduper:
return False, None
candidates = _collect_existing_task_descriptions(lanlan_name)
res = await Modules.deduper.judge(query, candidates)
return bool(res.get("duplicate")), res.get("matched_id")
except Exception as e:
logger.warning(f"[Agent] Deduper judge failed: {e}")
return False, None
def _now_iso() -> str:
return datetime.utcnow().isoformat() + "Z"
async def _emit_task_result(
lanlan_name: Optional[str],
*,
channel: str,
task_id: str,
success: bool,
summary: str,
detail: str = "",
error_message: str = "",
) -> None:
"""Emit a structured task_result event to main_server."""
if success:
status = "completed"
elif detail:
status = "partial"
else:
status = "failed"
_SUMMARY_LIMIT = 500
_DETAIL_LIMIT = 1500
_ERROR_LIMIT = 500
await _emit_main_event(
"task_result",
lanlan_name,
text=summary[:_SUMMARY_LIMIT],
task_id=task_id,
channel=channel,
status=status,
success=success,
summary=summary[:_SUMMARY_LIMIT],
detail=detail[:_DETAIL_LIMIT] if detail else "",
error_message=error_message[:_ERROR_LIMIT] if error_message else "",
timestamp=_now_iso(),
)
def _lookup_llm_result_fields(plugin_id: str, entry_id: Optional[str]) -> Optional[list]:
"""从 plugin_list 中查找指定 entry 的 llm_result_fields 声明。"""
try:
plugins = getattr(Modules.task_executor, "plugin_list", None) or []
for p in plugins:
if not isinstance(p, dict) or p.get("id") != plugin_id:
continue
for e in p.get("entries") or []:
if not isinstance(e, dict):
continue
if e.get("id") == entry_id:
fields = e.get("llm_result_fields")
return list(fields) if isinstance(fields, list) else None
break
except Exception as e:
logger.debug("_lookup_llm_result_fields failed: plugin_id=%s entry_id=%s error=%s", plugin_id, entry_id, e)
return None
def _is_reply_suppressed(result: Optional[Dict]) -> bool:
"""检查插件是否通过 meta.agent.reply=False 显式抑制回复。"""
if not isinstance(result, dict):
return False
meta = result.get("meta")
if not isinstance(meta, dict):
return False
agent = meta.get("agent")
if not isinstance(agent, dict):
return False
return agent.get("reply") is False
def _check_agent_api_gate() -> Dict[str, Any]:
"""统一 Agent API 门槛检查。"""
try:
cm = get_config_manager()
ok, reasons = cm.is_agent_api_ready()
return {"ready": ok, "reasons": reasons, "is_free_version": cm.is_free_version()}
except Exception as e:
return {"ready": False, "reasons": [f"Agent API check failed: {e}"], "is_free_version": False}
async def _emit_main_event(event_type: str, lanlan_name: Optional[str], **payload) -> None:
event = {"event_type": event_type, "lanlan_name": lanlan_name, **payload}
if Modules.agent_bridge:
try:
sent = await Modules.agent_bridge.emit_to_main(event)
if sent:
return
logger.debug("[Agent] _emit_main_event not sent: type=%s lanlan=%s (bridge returned False)", event_type, lanlan_name)
except Exception as e:
logger.warning("[Agent] _emit_main_event failed: type=%s lanlan=%s error=%s", event_type, lanlan_name, e)
else:
logger.debug("[Agent] _emit_main_event skipped: no agent_bridge, type=%s", event_type)
def _collect_agent_status_snapshot() -> Dict[str, Any]:
gate = _check_agent_api_gate()
flags = dict(Modules.agent_flags or {})
capabilities = dict(Modules.capability_cache or {})
# Periodic cleanup of completed tasks to prevent memory leak
# Note: _emit_agent_status_update also calls this and handles timed_out tasks
_cleanup_task_registry()
# Include active (queued/running) tasks so frontend can restore after page refresh
active_tasks = []
for tid, info in Modules.task_registry.items():
try:
st = info.get("status")
if st in ("queued", "running"):
active_tasks.append({
"id": tid,
"status": st,
"type": info.get("type"),
"start_time": info.get("start_time"),
"params": info.get("params", {}),
"session_id": info.get("session_id"),
"lanlan_name": info.get("lanlan_name"),
})
except Exception:
continue
note = Modules.notification
if Modules.notification:
Modules.notification = None
return {
"revision": Modules.state_revision,
"server_online": True,
"analyzer_enabled": bool(Modules.analyzer_enabled),
"flags": flags,
"gate": gate,
"capabilities": capabilities,
"active_tasks": active_tasks,
"notification": note,
"updated_at": _now_iso(),
}
def _normalize_lanlan_key(lanlan_name: Optional[str]) -> str:
name = (lanlan_name or "").strip()
return name or "__default__"
def _build_user_turn_fingerprint(messages: Any) -> Optional[str]:
"""
Build a stable fingerprint from user-role messages only.
Used to ensure analyzer consumes each user turn once.
Only the message *text* is hashed. Timestamps and message IDs are
intentionally excluded because frontends may update these metadata
fields on re-render, which would produce a different fingerprint for
the same logical user turn and cause duplicate analysis.
"""
if not isinstance(messages, list):
return None
user_parts: list[str] = []
for m in messages:
if not isinstance(m, dict):
continue
if m.get("role") != "user":
continue
text = str(m.get("text") or m.get("content") or "").strip()
if text:
user_parts.append(text)
if not user_parts:
return None
payload = "\n".join(user_parts).encode("utf-8", errors="ignore")
return hashlib.sha256(payload).hexdigest()
async def _emit_agent_status_update(lanlan_name: Optional[str] = None) -> None:
try:
# 先检查超时的 deferred 任务并发送 task_update 通知
timed_out = _cleanup_task_registry()
for task_info in timed_out:
try:
await _emit_main_event(
"task_update",
task_info.get("lanlan_name"),
task={
"id": task_info.get("id"),
"status": "failed",
"type": task_info.get("type"),
"start_time": task_info.get("start_time"),
"end_time": task_info.get("end_time"),
"error": task_info.get("error"),
"params": task_info.get("params", {}),
},
)
except Exception as e:
logger.warning("[Agent] Failed to emit task_update for timed-out task %s: %s", task_info.get("id"), e)
snapshot = _collect_agent_status_snapshot()
await _emit_main_event(
"agent_status_update",
lanlan_name,
snapshot=snapshot,
)
except Exception:
pass
async def _on_session_event(event: Dict[str, Any]) -> None:
if (event or {}).get("event_type") == "analyze_request":
messages = event.get("messages", [])
lanlan_name = event.get("lanlan_name")
event_id = event.get("event_id")
logger.info("[AgentAnalyze] analyze_request received: trigger=%s lanlan=%s messages=%d", event.get("trigger"), lanlan_name, len(messages) if isinstance(messages, list) else 0)
if event_id:
ack_task = asyncio.create_task(_emit_main_event("analyze_ack", lanlan_name, event_id=event_id))
Modules._background_tasks.add(ack_task)
ack_task.add_done_callback(Modules._background_tasks.discard)
if not Modules.analyzer_enabled:
logger.info("[AgentAnalyze] skip: analyzer disabled (master switch off)")
return
if isinstance(messages, list) and messages:
# Consume only new user turn. Assistant turn_end without new user input should be ignored.
lanlan_key = _normalize_lanlan_key(lanlan_name)
fp = _build_user_turn_fingerprint(messages)
if fp is None:
logger.info("[AgentAnalyze] skip analyze: no user message found (trigger=%s lanlan=%s)", event.get("trigger"), lanlan_name)
return
if Modules.last_user_turn_fingerprint.get(lanlan_key) == fp:
logger.info("[AgentAnalyze] skip analyze: no new user turn (trigger=%s lanlan=%s)", event.get("trigger"), lanlan_name)
return
Modules.last_user_turn_fingerprint[lanlan_key] = fp
conversation_id = event.get("conversation_id")
task = asyncio.create_task(_background_analyze_and_plan(messages, lanlan_name, conversation_id=conversation_id))
Modules._background_tasks.add(task)
task.add_done_callback(Modules._background_tasks.discard)
def _spawn_task(kind: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""生成 computer_use 任务条目并入队等待独占执行。"""
task_id = str(uuid.uuid4())
info = {
"id": task_id,
"type": kind,
"status": "queued",
"start_time": _now_iso(),
"params": args,
"result": None,
"error": None,
}
if kind == "computer_use":
Modules.task_registry[task_id] = info
if Modules.computer_use_queue is None:
Modules.computer_use_queue = asyncio.Queue()
Modules.computer_use_queue.put_nowait({
"task_id": task_id,
"instruction": args.get("instruction", ""),
})
return info
else:
raise ValueError(f"Unknown task kind: {kind}")
async def _run_computer_use_task(
task_id: str,
instruction: str,
) -> None:
"""Run a computer-use task in a thread pool; emit results directly via ZeroMQ."""
info = Modules.task_registry.get(task_id, {})
lanlan_name = info.get("lanlan_name")
# Mark running
info["status"] = "running"
info["start_time"] = _now_iso()
Modules.computer_use_running = True
Modules.active_computer_use_task_id = task_id
try:
await _emit_main_event(
"task_update", lanlan_name,
task={
"id": task_id, "status": "running", "type": "computer_use",
"start_time": info["start_time"], "params": info.get("params", {}),
},
)
except Exception as e:
logger.debug("[ComputerUse] emit task_update(running) failed: task_id=%s error=%s", task_id, e)
# Execute in thread pool (run_instruction is synchronous/blocking)
success = False
cu_detail = ""
loop = asyncio.get_running_loop()
try:
if Modules.computer_use is None or not hasattr(Modules.computer_use, "run_instruction"):
success = False
cu_detail = "ComputerUse adapter is inactive or invalid (e.g., reset)"
info["error"] = cu_detail
logger.error("[ComputerUse] Task %s aborted: %s", task_id, cu_detail)
else:
session_id = info.get("session_id")
future = loop.run_in_executor(None, Modules.computer_use.run_instruction, instruction, session_id)
res = await future
if res is None:
logger.debug("[ComputerUse] run_instruction returned None, treating as success")
res = {"success": True}
elif isinstance(res, dict) and "success" not in res:
res["success"] = True
success = bool(res.get("success", False))
info["result"] = res
_cu_ok, cu_detail = parse_computer_use_result(res)
except asyncio.CancelledError:
info["error"] = "Task was cancelled"
logger.info("[ComputerUse] Task %s was cancelled", task_id)
# The underlying thread may still be running — wait for it to finish
# so we don't start a new task while pyautogui is still active.
cu = Modules.computer_use
if cu is not None and hasattr(cu, "wait_for_completion"):
finished = await loop.run_in_executor(None, cu.wait_for_completion, 15.0)
if not finished:
logger.warning("[ComputerUse] Thread did not stop within 15s after cancel")
except Exception as e:
info["error"] = str(e)
logger.error("[ComputerUse] Task %s failed: %s", task_id, e)
finally:
info["status"] = "cancelled" if info.get("error") == "Task was cancelled" else ("completed" if success else "failed")
info["end_time"] = _now_iso()
# 失败时将解析后的 cu_detail 写入 info["error"](仅在非异常路径下补全)
if not success and not info.get("error") and cu_detail:
info["error"] = cu_detail[:500]
Modules.computer_use_running = False
Modules.active_computer_use_task_id = None
Modules.active_computer_use_async_task = None
# Emit task_update (terminal state)
try:
task_obj = asyncio.create_task(_emit_main_event(
"task_update", lanlan_name,
task={
"id": task_id, "status": info["status"], "type": "computer_use",
"start_time": info.get("start_time"), "end_time": _now_iso(),
"error": info.get("error") if not success else None,
},
))
Modules._background_tasks.add(task_obj)
task_obj.add_done_callback(Modules._background_tasks.discard)
except Exception as e:
logger.debug("[ComputerUse] emit task_update(terminal) failed: task_id=%s error=%s", task_id, e)
# Emit structured task_result
try:
_lang = _rp_lang(None)
_done = _rp_phrase('cu_status_done', _lang) if success else _rp_phrase('cu_status_ended', _lang)
params = info.get("params") or {}
desc = params.get("query") or params.get("instruction") or ""
if cu_detail and desc:
summary = _rp_phrase('cu_task_done', _lang, desc=desc, status=_done, detail=cu_detail)
elif cu_detail:
summary = _rp_phrase('cu_task_done_no_desc', _lang, status=_done, detail=cu_detail)
elif desc:
summary = _rp_phrase('cu_task_desc_only', _lang, desc=desc, status=_done)
else:
summary = _rp_phrase('cu_done', _lang) if success else _rp_phrase('cu_fail', _lang)
task_obj = asyncio.create_task(_emit_task_result(
lanlan_name,
channel="computer_use",
task_id=task_id,
success=success,
summary=summary,
detail=cu_detail if success else "",
error_message=cu_detail if not success else "",
))
Modules._background_tasks.add(task_obj)
task_obj.add_done_callback(Modules._background_tasks.discard)
except Exception as e:
logger.debug("[ComputerUse] emit task_result failed: task_id=%s error=%s", task_id, e)
async def _computer_use_scheduler_loop():
"""Ensure only one computer-use task runs at a time by scheduling queued tasks."""
if Modules.computer_use_queue is None:
Modules.computer_use_queue = asyncio.Queue()
while True:
try:
await asyncio.sleep(0.05)
if Modules.computer_use_running:
continue
if Modules.computer_use_queue.empty():
continue
if not Modules.analyzer_enabled or not Modules.agent_flags.get("computer_use_enabled", False):
while not Modules.computer_use_queue.empty():
try:
Modules.computer_use_queue.get_nowait()
except asyncio.QueueEmpty:
break
continue
next_task = await Modules.computer_use_queue.get()
tid = next_task.get("task_id")
if not tid or tid not in Modules.task_registry:
continue
Modules.active_computer_use_async_task = asyncio.create_task(_run_computer_use_task(
tid, next_task.get("instruction", ""),
))
except Exception:
# Never crash the scheduler
await asyncio.sleep(0.1)
async def _background_analyze_and_plan(messages: list[dict[str, Any]], lanlan_name: Optional[str], conversation_id: Optional[str] = None):
"""
[简化版] 使用 DirectTaskExecutor 一步完成:分析对话 + 判断执行方式 + 执行任务
简化链条:
- 旧: Analyzer(LLM#1) → Planner(LLM#2) → 子进程Processor(LLM#3) → MCP调用
- 新: DirectTaskExecutor(LLM#1) → MCP调用
Args:
messages: 对话消息列表
lanlan_name: 角色名
conversation_id: 对话ID,用于关联触发事件和对话上下文