-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathagentic_tool_loop.py
More file actions
1627 lines (1414 loc) · 65.4 KB
/
agentic_tool_loop.py
File metadata and controls
1627 lines (1414 loc) · 65.4 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
#!/usr/bin/env python3
"""
Agentic Tool Loop 核心引擎
实现单LLM agentic loop:模型在对话中发起工具调用,接收结果,再继续推理,直到不再需要工具。
"""
import asyncio
import json
import logging
import re
import time as _time
from json import JSONDecodeError
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
import httpx
from system.config import get_config, get_server_port
from apiserver.agent_directory import format_agent_directory_text, resolve_agent_descriptor
from apiserver import naga_auth
logger = logging.getLogger(__name__)
_TOOL_SECTION_BEGIN = "<|tool_calls_section_begin|>"
_TOOL_SECTION_END = "<|tool_calls_section_end|>"
_TOOL_CALL_BEGIN = "<|tool_call_begin|>functions."
_TOOL_CALL_ARG_BEGIN = "<|tool_call_argument_begin|>"
_TOOL_CALL_END = "<|tool_call_end|>"
# ---------------------------------------------------------------------------
# 解析工具
# ---------------------------------------------------------------------------
def _normalize_fullwidth_json_chars(text: str) -> str:
"""将常见全角JSON相关字符归一化为ASCII"""
if not text:
return text
translation_table = str.maketrans(
{
"{": "{",
"}": "}",
":": ":",
",": ",",
"\u201c": '"',
"\u201d": '"',
"\u2018": "'",
"\u2019": "'",
}
)
return text.translate(translation_table)
def _extract_json_objects(text: str) -> List[Dict[str, Any]]:
"""从文本中提取所有顶层JSON对象(花括号深度匹配 + json5/json 解析 + agentType过滤)"""
def _loads(s: str) -> Any:
try:
import json5 as _json5
return _json5.loads(s)
except Exception:
return json.loads(s)
objects: List[Dict[str, Any]] = []
start: Optional[int] = None
depth = 0
for i, ch in enumerate(text):
if ch == "{":
if depth == 0:
start = i
depth += 1
elif ch == "}":
if depth > 0:
depth -= 1
if depth == 0 and start is not None:
candidate = text[start : i + 1].strip()
start = None
if candidate in ("{}", "{ }"):
continue
try:
parsed = _loads(candidate)
except Exception:
continue
if isinstance(parsed, dict):
objects.append(parsed)
elif isinstance(parsed, list):
for item in parsed:
if isinstance(item, dict):
objects.append(item)
# 只保留含 agentType 字段的对象
return [obj for obj in objects if isinstance(obj.get("agentType"), str) and obj["agentType"]]
def _extract_tool_blocks(text: str) -> Tuple[str, List[Dict[str, Any]]]:
"""从 ```tool``` 代码块中提取工具调用JSON。
Returns:
(clean_text, tool_calls) — clean_text 是移除代码块后的纯文本
"""
tool_calls: List[Dict[str, Any]] = []
# 匹配 ```tool ... ``` 代码块(允许未闭合的尾部块用 \Z 兜底)
# 注意: 用 [ \t]* 而非 \s* 避免吃掉换行符; 用 \Z 而非 $ 避免 MULTILINE 下提前匹配行尾
pattern = re.compile(r"```tool[ \t]*\n([\s\S]*?)(?:```|\Z)")
for match in pattern.finditer(text):
block_content = match.group(1).strip()
if not block_content:
continue
normalized = _normalize_fullwidth_json_chars(block_content)
extracted = _extract_json_objects(normalized)
tool_calls.extend(extracted)
# 从文本中移除 ```tool...``` 代码块
clean_text = pattern.sub("", text).strip()
# 清理多余空行
clean_text = re.sub(r"\n{3,}", "\n\n", clean_text)
return clean_text, tool_calls
def _convert_special_tool_call_to_dispatch(tool_name: str, arguments: Any) -> List[Dict[str, Any]]:
args = arguments if isinstance(arguments, dict) else {"value": arguments}
if tool_name == "web_search":
queries = args.get("queries")
if isinstance(queries, list):
shared_args = {k: v for k, v in args.items() if k != "queries"}
dispatches: List[Dict[str, Any]] = []
for query in queries:
if not isinstance(query, str) or not query.strip():
continue
dispatch_args = dict(shared_args)
dispatch_args["query"] = query.strip()
dispatches.append({
"agentType": "tool",
"tool_name": "web_search",
"args": dispatch_args,
})
if dispatches:
return dispatches
return [{
"agentType": "tool",
"tool_name": tool_name,
"args": args,
}]
def _extract_special_tool_calls(text: str) -> Tuple[str, List[Dict[str, Any]]]:
"""提取 Kimi/OpenAI 兼容层泄露出的特殊工具调用语法。"""
if _TOOL_CALL_BEGIN not in text:
return text, []
decoder = json.JSONDecoder()
tool_calls: List[Dict[str, Any]] = []
clean_parts: List[str] = []
cursor = 0
while True:
start = text.find(_TOOL_CALL_BEGIN, cursor)
if start < 0:
clean_parts.append(text[cursor:])
break
section_start = text.rfind(_TOOL_SECTION_BEGIN, cursor, start)
clean_parts.append(text[cursor:section_start if section_start >= 0 else start])
name_start = start + len(_TOOL_CALL_BEGIN)
colon = text.find(":", name_start)
arg_start = text.find(_TOOL_CALL_ARG_BEGIN, colon if colon >= 0 else name_start)
if colon < 0 or arg_start < 0:
clean_parts.append(text[start:])
break
tool_name = text[name_start:colon].strip()
json_start = arg_start + len(_TOOL_CALL_ARG_BEGIN)
try:
arguments, consumed = decoder.raw_decode(text[json_start:])
except JSONDecodeError:
logger.warning("[AgenticLoop] 无法解析特殊工具调用 JSON,保留原始文本")
clean_parts.append(text[start:])
break
tool_calls.extend(_convert_special_tool_call_to_dispatch(tool_name, arguments))
end = text.find(_TOOL_CALL_END, json_start + consumed)
if end < 0:
cursor = json_start + consumed
else:
cursor = end + len(_TOOL_CALL_END)
if text.startswith(_TOOL_SECTION_END, cursor):
cursor += len(_TOOL_SECTION_END)
clean_text = "".join(clean_parts).strip()
clean_text = re.sub(r"\n{3,}", "\n\n", clean_text)
return clean_text, tool_calls
def parse_tool_calls_from_text(text: str) -> Tuple[str, List[Dict[str, Any]]]:
"""从LLM完整输出中提取所有工具调用JSON。
优先从 ```tool``` 代码块提取,回退到裸JSON行提取(向后兼容)。
Returns:
(clean_text, tool_calls) — clean_text 是去掉工具调用后的纯文本
"""
# 优先使用 ```tool``` 代码块
clean_text, tool_calls = _extract_tool_blocks(text)
if tool_calls:
return clean_text, tool_calls
clean_text, tool_calls = _extract_special_tool_calls(text)
if tool_calls:
return clean_text, tool_calls
# 回退:从裸文本中提取含 agentType 的JSON对象(向后兼容)
normalized = _normalize_fullwidth_json_chars(text)
tool_calls = _extract_json_objects(normalized)
if not tool_calls:
return text, []
# 从原始文本中移除工具调用JSON所在的行
clean_lines = []
for line in text.split("\n"):
norm_line = _normalize_fullwidth_json_chars(line.strip())
if norm_line:
extracted = _extract_json_objects(norm_line)
if extracted:
continue # 跳过包含工具调用的行
clean_lines.append(line)
clean_text = "\n".join(clean_lines).strip()
return clean_text, tool_calls
# ---------------------------------------------------------------------------
# OpenClaw 共享客户端与可用性预检
# ---------------------------------------------------------------------------
_shared_openclaw_client: Optional[httpx.AsyncClient] = None
def _get_openclaw_client() -> httpx.AsyncClient:
"""获取或创建共享的 httpx 客户端(避免每次调用都新建连接)"""
global _shared_openclaw_client
if _shared_openclaw_client is None or _shared_openclaw_client.is_closed:
_shared_openclaw_client = httpx.AsyncClient(
timeout=httpx.Timeout(timeout=150.0, connect=10.0),
proxy=None, # localhost 请求不走系统代理
)
return _shared_openclaw_client
_openclaw_available: Optional[bool] = None
_openclaw_check_time: float = 0.0
_OPENCLAW_CHECK_TTL = 30.0
_openclaw_start_attempted: bool = False # 每次进程生命周期内只自动启动一次
async def _check_openclaw_available() -> bool:
"""检查 OpenClaw 服务是否可用,不可用时尝试自动启动"""
global _openclaw_available, _openclaw_check_time, _openclaw_start_attempted
now = _time.monotonic()
if _openclaw_available is not None and (now - _openclaw_check_time) < _OPENCLAW_CHECK_TTL:
return _openclaw_available
agent_base = f"http://localhost:{get_server_port('agent_server')}"
client = _get_openclaw_client()
_openclaw_available = await _probe_openclaw_health(client, agent_base)
# 不可用且还没尝试过自动启动 → 启动一次
if not _openclaw_available and not _openclaw_start_attempted:
_openclaw_start_attempted = True
logger.info("[AgenticLoop] OpenClaw gateway 不可用,尝试自动启动...")
try:
resp = await client.post(f"{agent_base}/openclaw/gateway/start", timeout=45.0)
if resp.status_code == 200:
start_result = resp.json()
# start_gateway 内部已经等待并检查了连通性
if start_result.get("success"):
logger.info("[AgenticLoop] OpenClaw gateway 启动成功")
# 再确认一次 health
_openclaw_available = await _probe_openclaw_health(client, agent_base)
if not _openclaw_available:
# start 说成功但 health 还没好,短暂等待
await asyncio.sleep(2)
_openclaw_available = await _probe_openclaw_health(client, agent_base)
else:
msg = start_result.get("message", "未知原因")
logger.warning(f"[AgenticLoop] OpenClaw gateway 启动失败: {msg}")
else:
logger.warning(f"[AgenticLoop] OpenClaw gateway 启动请求失败: HTTP {resp.status_code}")
except Exception as e:
logger.warning(f"[AgenticLoop] OpenClaw gateway 自动启动异常: {e}")
_openclaw_check_time = _time.monotonic()
return _openclaw_available
async def _probe_openclaw_health(client: httpx.AsyncClient, agent_base: str) -> bool:
"""探测 OpenClaw gateway 是否健康"""
try:
resp = await client.get(f"{agent_base}/openclaw/health", timeout=3.0)
data = resp.json()
return (
resp.status_code == 200
and data.get("success", False)
and data.get("health", {}).get("status") == "healthy"
)
except Exception:
return False
# ---------------------------------------------------------------------------
# 工具执行
# ---------------------------------------------------------------------------
async def _execute_mcp_call(call: Dict[str, Any], source_agent_id: Optional[str] = None) -> Dict[str, Any]:
"""执行单个MCP调用"""
service_name = call.get("service_name", "")
tool_name = call.get("tool_name", "")
if not service_name and tool_name in {
"ask_guide",
"ask_guide_with_screenshot",
"calculate_damage",
"get_team_recommendation",
}:
service_name = "game_guide"
call["service_name"] = service_name
# 游戏攻略功能仅登录用户可用
if service_name == "game_guide":
if not naga_auth.is_authenticated():
return {
"tool_call": call,
"result": "游戏攻略功能需要登录 Naga 账号后才能使用,请先登录。",
"status": "error",
"service_name": service_name,
"tool_name": tool_name,
}
try:
from mcpserver.mcp_registry import is_service_visible_to_agent
from mcpserver.mcp_manager import get_mcp_manager
if not is_service_visible_to_agent(service_name, agent_id=source_agent_id):
return {
"tool_call": call,
"result": f"当前干员无权访问 MCP 服务: {service_name}",
"status": "error",
"service_name": service_name,
"tool_name": tool_name,
}
manager = get_mcp_manager()
t0 = _time.monotonic()
result = await manager.unified_call(service_name, call)
elapsed = _time.monotonic() - t0
logger.info(f"[AgenticLoop] MCP调用完成: {service_name}/{tool_name} 耗时 {elapsed:.2f}s")
return {
"tool_call": call,
"result": result,
"status": "success",
"service_name": service_name,
"tool_name": tool_name,
}
except Exception as e:
logger.error(f"[AgenticLoop] MCP调用失败: service={service_name}, error={e}")
return {
"tool_call": call,
"result": f"调用失败: {e}",
"status": "error",
"service_name": service_name,
"tool_name": tool_name,
}
async def _execute_openclaw_call(call: Dict[str, Any], session_id: str) -> Dict[str, Any]:
"""执行单个OpenClaw调用(Agent 模式,通过 /hooks/agent 走二次 LLM)"""
message = call.get("message", "")
task_type = call.get("task_type", "message")
if not message:
return {
"tool_call": call,
"result": "缺少message字段",
"status": "error",
"service_name": "openclaw",
"tool_name": task_type,
}
if not await _check_openclaw_available():
return {
"tool_call": call,
"result": "OpenClaw 服务当前不可用,请稍后重试",
"status": "error",
"service_name": "openclaw",
"tool_name": task_type,
}
payload = {
"message": message,
"session_key": call.get("session_key", f"naga_{session_id}"),
"name": "Naga",
"wake_mode": "now",
"timeout_seconds": 120,
}
if task_type == "cron" and call.get("schedule"):
payload["message"] = f"[定时任务 cron: {call.get('schedule')}] {message}"
elif task_type == "reminder" and call.get("at"):
payload["message"] = f"[提醒 在 {call.get('at')} 后] {message}"
try:
client = _get_openclaw_client()
response = await client.post(
f"http://localhost:{get_server_port('agent_server')}/openclaw/send",
json=payload,
)
if response.status_code == 200:
result_data = response.json()
# 先检查 agent_server 返回的 success 标记
if not result_data.get("success", True):
error_msg = result_data.get("error") or "OpenClaw任务执行失败"
return {
"tool_call": call,
"result": f"联网搜索失败: {error_msg}",
"status": "error",
"service_name": "openclaw",
"tool_name": task_type,
}
# agent_server 返回两个字段:replies(列表,异步轮询时填充) 和 reply(字符串,同步完成时填充)
replies = result_data.get("replies") or []
if replies:
combined = "\n".join(replies)
elif result_data.get("reply"):
combined = result_data["reply"]
else:
combined = "任务已提交,暂无返回结果"
return {
"tool_call": call,
"result": combined,
"status": "success",
"service_name": "openclaw",
"tool_name": task_type,
}
else:
return {
"tool_call": call,
"result": f"HTTP {response.status_code}: {response.text[:200]}",
"status": "error",
"service_name": "openclaw",
"tool_name": task_type,
}
except Exception as e:
logger.error(f"[AgenticLoop] OpenClaw调用失败: {e}")
return {
"tool_call": call,
"result": f"调用失败: {e}",
"status": "error",
"service_name": "openclaw",
"tool_name": task_type,
}
async def _execute_naga_search(call: Dict[str, Any]) -> Dict[str, Any]:
"""通过 NagaBusiness 搜索代理执行 web_search(已登录时优先使用)"""
tool_args = call.get("args", {})
query = tool_args.get("query", "") or tool_args.get("q", "")
count = tool_args.get("count", 10)
freshness = tool_args.get("freshness")
if not query:
return {
"tool_call": call, "result": "缺少搜索关键词",
"status": "error", "service_name": "naga_search", "tool_name": "web_search",
}
try:
token = naga_auth.get_access_token()
params: Dict[str, Any] = {"q": query, "count": count}
if freshness:
params["freshness"] = freshness
client = _get_openclaw_client()
t0 = _time.monotonic()
resp = await client.post(
naga_auth.NAGA_MODEL_URL + "/tools/search",
json=params,
headers={"Authorization": f"Bearer {token}"},
timeout=30.0,
)
elapsed = _time.monotonic() - t0
if resp.status_code != 200:
try:
error_data = resp.json()
error_msg = error_data.get("error", {}).get("message", f"HTTP {resp.status_code}")
except Exception:
error_msg = f"HTTP {resp.status_code}"
logger.error(f"[AgenticLoop] Naga搜索代理错误: {error_msg}")
return {
"tool_call": call, "result": f"搜索失败: {error_msg}",
"status": "error", "service_name": "naga_search", "tool_name": "web_search",
}
data = resp.json()
results = data.get("web", {}).get("results", [])
# 格式化搜索结果为可读文本
if not results:
readable = "未找到相关搜索结果。"
else:
lines = []
for i, r in enumerate(results, 1):
title = r.get("title", "")
url = r.get("url", "")
desc = r.get("description", "")
age = r.get("age", "")
lines.append(f"{i}. {title}")
lines.append(f" URL: {url}")
if desc:
lines.append(f" 摘要: {desc}")
if age:
lines.append(f" 时间: {age}")
lines.append("")
readable = "\n".join(lines)
logger.info(f"[AgenticLoop] Naga搜索完成: query=\"{query}\" 耗时 {elapsed:.2f}s, 结果数={len(results)}")
return {
"tool_call": call, "result": readable,
"status": "success", "service_name": "naga_search", "tool_name": "web_search",
}
except Exception as e:
logger.error(f"[AgenticLoop] Naga搜索代理异常: {e}")
return {
"tool_call": call, "result": f"搜索异常: {e}",
"status": "error", "service_name": "naga_search", "tool_name": "web_search",
}
async def _execute_brave_search(call: Dict[str, Any]) -> Dict[str, Any]:
"""通过配置的 Brave Search API Key 直接搜索(未登录 Naga 时使用)"""
tool_args = call.get("args", {})
query = tool_args.get("query", "") or tool_args.get("q", "")
count = tool_args.get("count", 10)
freshness = tool_args.get("freshness")
if not query:
return {
"tool_call": call, "result": "缺少搜索关键词",
"status": "error", "service_name": "brave_search", "tool_name": "web_search",
}
try:
cfg = get_config()
api_key = cfg.online_search.search_api_key
api_base = cfg.online_search.search_api_base
params: Dict[str, Any] = {"q": query, "count": count}
if freshness:
params["freshness"] = freshness
client = _get_openclaw_client()
t0 = _time.monotonic()
resp = await client.get(
api_base,
params=params,
headers={
"Accept": "application/json",
"X-Subscription-Token": api_key,
},
timeout=30.0,
)
elapsed = _time.monotonic() - t0
if resp.status_code != 200:
try:
error_data = resp.json()
error_msg = str(error_data)[:200]
except Exception:
error_msg = f"HTTP {resp.status_code}"
logger.error(f"[AgenticLoop] Brave搜索错误: {error_msg}")
return {
"tool_call": call, "result": f"搜索失败: {error_msg}",
"status": "error", "service_name": "brave_search", "tool_name": "web_search",
}
data = resp.json()
results = data.get("web", {}).get("results", [])
if not results:
readable = "未找到相关搜索结果。"
else:
lines = []
for i, r in enumerate(results, 1):
title = r.get("title", "")
url = r.get("url", "")
desc = r.get("description", "")
age = r.get("age", "")
lines.append(f"{i}. {title}")
lines.append(f" URL: {url}")
if desc:
lines.append(f" 摘要: {desc}")
if age:
lines.append(f" 时间: {age}")
lines.append("")
readable = "\n".join(lines)
logger.info(f"[AgenticLoop] Brave搜索完成: query=\"{query}\" 耗时 {elapsed:.2f}s, 结果数={len(results)}")
return {
"tool_call": call, "result": readable,
"status": "success", "service_name": "brave_search", "tool_name": "web_search",
}
except Exception as e:
logger.error(f"[AgenticLoop] Brave搜索异常: {e}")
return {
"tool_call": call, "result": f"搜索异常: {e}",
"status": "error", "service_name": "brave_search", "tool_name": "web_search",
}
async def execute_pre_search(query: str, count: int = 8) -> Optional[str]:
"""
前置搜索:在主 LLM 调用前执行搜索,返回格式化的搜索结果文本。
复用 3-tier 搜索回退链:NagaBusiness → Brave → None
"""
# 构造虚拟 call dict 供搜索函数使用
call = {"args": {"query": query, "count": count}}
if naga_auth.is_authenticated():
result = await _execute_naga_search(call)
if result.get("status") == "success" and result.get("result"):
return result["result"]
cfg = get_config()
if cfg.online_search.search_api_key:
result = await _execute_brave_search(call)
if result.get("status") == "success" and result.get("result"):
return result["result"]
return None # 无可用搜索源,跳过前置搜索
# Gateway 可直接调用的工具(/tools/invoke),其余为 agent-session 工具需走 /hooks/agent
_GATEWAY_DIRECT_TOOLS = frozenset({
"web_search", "web_fetch", "browser",
"memory_search", "memory_get",
"sessions_list", "sessions_history", "session_status",
"agents_list", "cron", "message", "tts", "canvas", "nodes",
})
# 可本地执行的工具(无需经过 OpenClaw,直接本地完成)
_LOCAL_EXEC_TOOLS = frozenset({
"exec", "read", "write", "edit", "ls", "find", "grep", "process", "image",
"sessions_spawn", "sessions_send", "gateway", "agents_list", "agent_relay",
})
async def _execute_openclaw_tool_call(
call: Dict[str, Any],
source_agent_id: Optional[str] = None,
) -> Dict[str, Any]:
"""调用 OpenClaw 工具。
Gateway 级工具直接走 /tools/invoke;
agent-session 级工具(exec/read/write 等)走 /hooks/agent 让 agent 代执行。
"""
tool_name = call.get("tool_name", "")
tool_args = call.get("args", {})
if not tool_name:
return {
"tool_call": call, "result": "缺少 tool_name",
"status": "error", "service_name": "openclaw_tool", "tool_name": "unknown",
}
# web_search: 已登录走 Naga 代理,未登录有 key 走 Brave,都没有走 OpenClaw
if tool_name == "web_search":
if naga_auth.is_authenticated():
return await _execute_naga_search(call)
cfg = get_config()
if cfg.online_search.search_api_key:
return await _execute_brave_search(call)
# 本地可执行工具:直接在本机执行,不经过 OpenClaw agent session
if tool_name in _LOCAL_EXEC_TOOLS:
return await _execute_local_tool(call, tool_name, tool_args, source_agent_id=source_agent_id)
if not await _check_openclaw_available():
return {
"tool_call": call, "result": "OpenClaw 服务当前不可用,请稍后重试",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
try:
client = _get_openclaw_client()
t0 = _time.monotonic()
response = await client.post(
f"http://localhost:{get_server_port('agent_server')}/openclaw/tools/invoke",
json={"tool": tool_name, "args": tool_args},
)
elapsed = _time.monotonic() - t0
if response.status_code == 200:
result_data = response.json()
# 先检查 agent_server 层面的 success 标记(如 tool_not_found)
if not result_data.get("success", True):
error_msg = result_data.get("error") or result_data.get("detail") or "工具调用失败"
logger.error(f"[AgenticLoop] OpenClaw工具返回失败: {tool_name}, error={error_msg}")
return {
"tool_call": call, "result": f"调用失败: {error_msg}",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
# agent_server 返回 { success: true, result: { ok, result: { content: [...] } } }
# invoke_tool 包了一层,需解开两层 result 才能到 OpenClaw 的原始工具输出
result_content = result_data.get("result", result_data)
if isinstance(result_content, dict) and "result" in result_content:
result_content = result_content["result"]
# 检查 OpenClaw 工具级别的错误(isError 标记 或 error 字段)
if isinstance(result_content, dict) and (result_content.get("isError") or "error" in result_content):
readable = _extract_openclaw_tool_result(result_content)
logger.error(f"[AgenticLoop] OpenClaw工具错误: {tool_name}, result={readable[:300]}")
return {
"tool_call": call, "result": f"工具执行错误: {readable}",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
readable = _extract_openclaw_tool_result(result_content)
# 检测嵌套在 content text 中的 JSON 错误(如 {"error": "missing_brave_api_key", ...})
if readable.lstrip().startswith("{"):
try:
parsed = json.loads(readable)
if isinstance(parsed, dict) and "error" in parsed:
error_msg = parsed.get("message") or str(parsed["error"])
logger.error(f"[AgenticLoop] OpenClaw工具错误: {tool_name}, error={error_msg}")
return {
"tool_call": call, "result": f"工具执行错误: {error_msg}",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
except (json.JSONDecodeError, TypeError):
pass
logger.info(f"[AgenticLoop] OpenClaw直接工具调用完成: {tool_name} 耗时 {elapsed:.2f}s, 结果长度={len(readable)}")
logger.info(f"[AgenticLoop] OpenClaw工具结果预览: {readable[:300]}")
return {
"tool_call": call, "result": readable,
"status": "success", "service_name": "openclaw_tool", "tool_name": tool_name,
}
else:
logger.error(f"[AgenticLoop] OpenClaw直接工具调用HTTP错误: {tool_name}, status={response.status_code}, body={response.text[:200]}")
return {
"tool_call": call, "result": f"调用失败: HTTP {response.status_code} - {response.text[:200]}",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
except Exception as e:
logger.error(f"[AgenticLoop] OpenClaw直接工具调用失败: {tool_name}, error={e}")
return {
"tool_call": call, "result": f"调用异常: {e}",
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
async def _execute_local_tool(
call: Dict[str, Any],
tool_name: str,
tool_args: Dict[str, Any],
source_agent_id: Optional[str] = None,
) -> Dict[str, Any]:
"""本地直接执行 agent-session 级工具(exec/read/write/ls/grep 等),不经过 OpenClaw。"""
import subprocess as _sp
from pathlib import Path as _Path
def _ok(text: str) -> Dict[str, Any]:
return {
"tool_call": call, "result": text,
"status": "success", "service_name": "openclaw_tool", "tool_name": tool_name,
}
def _err(text: str) -> Dict[str, Any]:
return {
"tool_call": call, "result": text,
"status": "error", "service_name": "openclaw_tool", "tool_name": tool_name,
}
try:
if tool_name == "exec":
cmd = tool_args.get("command", "")
if not cmd:
return _err("缺少 command 参数")
timeout = min(tool_args.get("timeout", 60), 300)
workdir = tool_args.get("workdir")
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=workdir,
)
try:
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
proc.kill()
return _err(f"命令执行超时 ({timeout}s)")
out = (stdout or b"").decode(errors="replace")
err = (stderr or b"").decode(errors="replace")
text = out
if err:
text += f"\n[stderr]\n{err}" if out else err
if proc.returncode != 0:
text += f"\n[exit code: {proc.returncode}]"
return _ok(text[:50000] if text else "(无输出)")
elif tool_name == "read":
fp = tool_args.get("file_path", "")
if not fp:
return _err("缺少 file_path 参数")
p = _Path(fp).expanduser()
if not p.exists():
return _err(f"文件不存在: {fp}")
content = p.read_text(encoding="utf-8", errors="replace")
return _ok(content[:100000])
elif tool_name == "write":
fp = tool_args.get("file_path", "")
content = tool_args.get("content", "")
if not fp:
return _err("缺少 file_path 参数")
p = _Path(fp).expanduser()
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
return _ok(f"已写入 {fp} ({len(content)} 字符)")
elif tool_name == "edit":
fp = tool_args.get("file_path", "")
old = tool_args.get("old_string", "")
new = tool_args.get("new_string", "")
if not fp or not old:
return _err("缺少 file_path 或 old_string 参数")
p = _Path(fp).expanduser()
if not p.exists():
return _err(f"文件不存在: {fp}")
text = p.read_text(encoding="utf-8", errors="replace")
if old not in text:
return _err(f"未找到要替换的文本")
text = text.replace(old, new, 1)
p.write_text(text, encoding="utf-8")
return _ok(f"已替换 {fp}")
elif tool_name == "ls":
path = tool_args.get("path", ".")
p = _Path(path).expanduser()
if not p.is_dir():
return _err(f"目录不存在: {path}")
entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name))
lines = []
for e in entries[:500]:
prefix = "d " if e.is_dir() else " "
lines.append(f"{prefix}{e.name}")
return _ok("\n".join(lines) if lines else "(空目录)")
elif tool_name == "find":
pattern = tool_args.get("pattern", "*")
path = tool_args.get("path", ".")
p = _Path(path).expanduser()
matches = sorted(p.rglob(pattern))[:200]
return _ok("\n".join(str(m) for m in matches) if matches else "未找到匹配文件")
elif tool_name == "grep":
import re as _re
pattern = tool_args.get("pattern", "")
path = tool_args.get("path", ".")
include = tool_args.get("include", "")
if not pattern:
return _err("缺少 pattern 参数")
p = _Path(path).expanduser()
glob_pat = include if include else "**/*"
files = p.rglob(glob_pat) if p.is_dir() else [p]
results = []
try:
regex = _re.compile(pattern)
except _re.error as e:
return _err(f"正则表达式错误: {e}")
for f in files:
if not f.is_file() or f.stat().st_size > 2_000_000:
continue
try:
for i, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
if regex.search(line):
results.append(f"{f}:{i}: {line.rstrip()}")
if len(results) >= 200:
break
except Exception:
continue
if len(results) >= 200:
break
return _ok("\n".join(results) if results else "未找到匹配")
elif tool_name == "agents_list":
return _ok(format_agent_directory_text())
elif tool_name == "agent_relay":
return await _execute_agent_relay(call, tool_args, source_agent_id)
elif tool_name == "image":
url = tool_args.get("url", "")
return _err(f"image 工具暂不支持本地执行,请使用 openclaw__agent 模式: {url}")
elif tool_name == "process":
return _err("process 工具暂不支持本地执行,请使用 openclaw__agent 模式")
else:
# sessions_spawn, sessions_send, gateway 等走 OpenClaw agent session 降级
return await _execute_openclaw_session_tool(call, tool_name, tool_args)
except Exception as e:
logger.error(f"[AgenticLoop] 本地工具执行失败: {tool_name}, error={e}")
return _err(f"执行失败: {e}")
async def _execute_agent_relay(
call: Dict[str, Any],
tool_args: Dict[str, Any],
source_agent_id: Optional[str],
) -> Dict[str, Any]:
target_agent_id = str(tool_args.get("target_agent_id") or "").strip() or None
target_agent_name = str(tool_args.get("target_agent_name") or "").strip() or None
message = str(tool_args.get("message") or "").strip()
if not message:
return {
"tool_call": call,
"result": "缺少 message 参数",
"status": "error",
"service_name": "agent_directory",
"tool_name": "agent_relay",
}
if not target_agent_id and not target_agent_name:
return {
"tool_call": call,
"result": "缺少目标干员,请先调用 agents_list 再指定 target_agent_id 或 target_agent_name",
"status": "error",
"service_name": "agent_directory",
"tool_name": "agent_relay",
}
target = resolve_agent_descriptor(agent_id=target_agent_id, agent_name=target_agent_name, include_builtin=True)
if target is None:
return {
"tool_call": call,
"result": "目标干员不存在,请先调用 agents_list 检查通讯录",
"status": "error",
"service_name": "agent_directory",
"tool_name": "agent_relay",
}
payload = {
"message": message,
"target_agent_id": target.id,
"source_agent_id": source_agent_id,
"purpose": tool_args.get("purpose"),
"context": tool_args.get("context"),
"timeout_seconds": max(5, min(int(tool_args.get("timeout_seconds", 120) or 120), 600)),
}
try:
client = _get_openclaw_client()
response = await client.post(
f"http://localhost:{get_server_port('api_server')}/agents/relay",
json=payload,
timeout=payload["timeout_seconds"] + 30,
)
if response.status_code != 200:
return {
"tool_call": call,
"result": f"转发失败: HTTP {response.status_code} {response.text[:300]}",
"status": "error",
"service_name": "agent_directory",
"tool_name": "agent_relay",
}
data = response.json()
if not data.get("success", False):
return {
"tool_call": call,
"result": data.get("error") or "目标干员未返回成功结果",
"status": "error",
"service_name": "agent_directory",
"tool_name": "agent_relay",
}
reply = str(data.get("reply") or "").strip() or "(目标干员未返回正文)"
result_text = (
f"目标干员: {data.get('target', {}).get('name', target.name)}\n"
f"目标引擎: {data.get('target', {}).get('engine', target.engine)}\n"
f"回复:\n{reply}"
)
return {