forked from RTGS2017/NagaAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool_loop.py
More file actions
4096 lines (3728 loc) · 158 KB
/
tool_loop.py
File metadata and controls
4096 lines (3728 loc) · 158 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 hashlib
import json
import logging
import re
import time
import traceback
import uuid
from dataclasses import dataclass, field
from typing import Any, AsyncGenerator, Dict, List, Optional, Set, Tuple
from core.security.budget_guard import BudgetGuardController
from agents.memory.episodic_memory import archive_tool_results_for_session, build_reinjection_context
from agents.memory.semantic_graph import update_tool_result_topology_from_records
from system.config import get_config
from system.coding_intent import contains_direct_coding_signal, extract_latest_user_message
from system.gc_budget_guard import GCBudgetGuard, GCBudgetGuardConfig
from system.gc_memory_card import build_gc_memory_index_card
from system.gc_reader_bridge import build_gc_reader_followup_plan
from core.security import LeaseHandle, get_global_mutex_manager
from system.loop_cost_guard import LoopCostGuard, LoopCostThresholds
from system.router_arbiter import MAX_DELEGATE_TURNS, evaluate_workspace_conflict_retry
from system.tool_contract import ToolCallEnvelope
from core.supervisor.watchdog_daemon import WatchdogDaemon, WatchdogThresholds
from apiserver.native_tools import get_native_tool_executor
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# 循环策略与运行态
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class AgenticLoopPolicy:
"""Agentic loop 编排策略(配置驱动)。"""
max_rounds: int
enable_summary_round: bool
max_consecutive_tool_failures: int
max_consecutive_validation_failures: int
max_consecutive_no_tool_rounds: int
# Deprecated: natural-language no-tool feedback injection has been retired.
inject_no_tool_feedback: bool
tool_result_preview_chars: int
emit_workflow_stage_events: bool
max_parallel_tool_calls: int
retry_failed_tool_calls: bool
max_tool_retries: int
retry_backoff_seconds: float
gc_budget_guard_enabled: bool
gc_budget_repeat_threshold: int
gc_budget_window_size: int
@dataclass
class AgenticLoopRuntimeState:
"""Agentic loop 运行态统计。"""
round_num: int = 0
total_tool_calls: int = 0
total_tool_success: int = 0
total_tool_errors: int = 0
consecutive_tool_failures: int = 0
consecutive_validation_failures: int = 0
consecutive_no_tool_rounds: int = 0
gc_guard_repeat_count: int = 0
gc_guard_error_total: int = 0
gc_guard_success_total: int = 0
gc_guard_hit_total: int = 0
agent_state: Dict[str, Any] = field(default_factory=lambda: {"task_completed": False})
submit_result_called: bool = False
submit_result_round: int = 0
stop_reason: str = ""
@dataclass(frozen=True)
class ToolContractRolloutRuntime:
"""Structured tool-contract runtime policy.
The legacy result contract has been retired. Runtime policy now only
controls whether observability metadata is emitted alongside the canonical
structured payload.
"""
contract_mode: str = "structured_only"
emit_observability_metadata: bool = True
def snapshot(self) -> Dict[str, Any]:
return {
"contract_mode": self.contract_mode,
"emit_observability_metadata": bool(self.emit_observability_metadata),
}
@dataclass
class ParallelContractGateDecision:
"""Parallel contract gate decision payload for one planning round."""
actionable_calls: List[Dict[str, Any]]
messages: List[str]
force_serial: bool = False
readonly_downgraded: bool = False
dropped_mutating_calls: int = 0
validation_errors: List[str] | None = None
reason: str = ""
_TOOL_RESULT_NONE_MARKERS = {"", "(none)", "none", "null", "nil", "n/a", "undefined"}
_TOOL_RESULT_TAG_LINE_RE = re.compile(r"^\[([A-Za-z0-9_]+)\](?:\s*(.*))?$")
_BUDGET_GUARD_CONTROLLER: Optional[BudgetGuardController] = None
def _get_budget_guard_controller() -> BudgetGuardController:
global _BUDGET_GUARD_CONTROLLER
if _BUDGET_GUARD_CONTROLLER is None:
_BUDGET_GUARD_CONTROLLER = BudgetGuardController()
return _BUDGET_GUARD_CONTROLLER
def _clamp_int(value: Any, default: int, min_value: int, max_value: int) -> int:
try:
num = int(value)
except Exception:
return default
return max(min_value, min(max_value, num))
def _resolve_agentic_loop_policy(max_rounds_override: Optional[int]) -> AgenticLoopPolicy:
cfg = get_config()
handoff_cfg = getattr(cfg, "handoff", None)
loop_cfg = getattr(cfg, "agentic_loop", None)
fallback_rounds = 500
if handoff_cfg is not None:
fallback_rounds = _clamp_int(getattr(handoff_cfg, "max_loop_stream", 500), 500, 1, 5000)
configured_rounds = fallback_rounds
if loop_cfg is not None:
configured_rounds = _clamp_int(getattr(loop_cfg, "max_rounds_stream", fallback_rounds), fallback_rounds, 1, 5000)
if max_rounds_override is not None and int(max_rounds_override) > 0:
max_rounds = _clamp_int(max_rounds_override, configured_rounds, 1, 5000)
else:
max_rounds = configured_rounds
if loop_cfg is None:
return AgenticLoopPolicy(
max_rounds=max_rounds,
enable_summary_round=False,
max_consecutive_tool_failures=2,
max_consecutive_validation_failures=2,
max_consecutive_no_tool_rounds=2,
inject_no_tool_feedback=False,
tool_result_preview_chars=500,
emit_workflow_stage_events=True,
max_parallel_tool_calls=8,
retry_failed_tool_calls=True,
max_tool_retries=1,
retry_backoff_seconds=0.8,
gc_budget_guard_enabled=True,
gc_budget_repeat_threshold=3,
gc_budget_window_size=6,
)
return AgenticLoopPolicy(
max_rounds=max_rounds,
enable_summary_round=bool(getattr(loop_cfg, "enable_summary_round", False)),
max_consecutive_tool_failures=_clamp_int(
getattr(loop_cfg, "max_consecutive_tool_failures", 2), 2, 1, 20
),
max_consecutive_validation_failures=_clamp_int(
getattr(loop_cfg, "max_consecutive_validation_failures", 2), 2, 1, 20
),
max_consecutive_no_tool_rounds=_clamp_int(
getattr(loop_cfg, "max_consecutive_no_tool_rounds", 2), 2, 1, 20
),
inject_no_tool_feedback=False,
tool_result_preview_chars=_clamp_int(
getattr(loop_cfg, "tool_result_preview_chars", 500), 500, 120, 20000
),
emit_workflow_stage_events=bool(getattr(loop_cfg, "emit_workflow_stage_events", True)),
max_parallel_tool_calls=_clamp_int(getattr(loop_cfg, "max_parallel_tool_calls", 8), 8, 1, 64),
retry_failed_tool_calls=bool(getattr(loop_cfg, "retry_failed_tool_calls", True)),
max_tool_retries=_clamp_int(getattr(loop_cfg, "max_tool_retries", 1), 1, 0, 5),
retry_backoff_seconds=float(getattr(loop_cfg, "retry_backoff_seconds", 0.8)),
gc_budget_guard_enabled=bool(getattr(loop_cfg, "gc_budget_guard_enabled", True)),
gc_budget_repeat_threshold=_clamp_int(getattr(loop_cfg, "gc_budget_repeat_threshold", 3), 3, 2, 10),
gc_budget_window_size=_clamp_int(getattr(loop_cfg, "gc_budget_window_size", 6), 6, 2, 30),
)
def _build_agentic_loop_watchdog() -> Optional[WatchdogDaemon]:
cfg = get_config()
loop_cfg = getattr(cfg, "agentic_loop", None)
enabled = bool(getattr(loop_cfg, "watchdog_guard_enabled", True)) if loop_cfg is not None else True
if not enabled:
return None
warn_only = bool(getattr(loop_cfg, "watchdog_warn_only", True)) if loop_cfg is not None else True
consecutive_error_limit = _clamp_int(
getattr(loop_cfg, "watchdog_consecutive_error_limit", 5) if loop_cfg is not None else 5,
5,
1,
200,
)
tool_call_limit_per_minute = _clamp_int(
getattr(loop_cfg, "watchdog_tool_call_limit_per_minute", 10) if loop_cfg is not None else 10,
10,
1,
2000,
)
loop_window_seconds = _clamp_int(
getattr(loop_cfg, "watchdog_loop_window_seconds", 60) if loop_cfg is not None else 60,
60,
1,
3600,
)
task_cost_limit = float(
getattr(loop_cfg, "watchdog_task_cost_limit", 5.0) if loop_cfg is not None else 5.0
)
daily_cost_limit = float(
getattr(loop_cfg, "watchdog_daily_cost_limit", 50.0) if loop_cfg is not None else 50.0
)
loop_cost_guard = LoopCostGuard(
thresholds=LoopCostThresholds(
consecutive_error_limit=consecutive_error_limit,
tool_call_limit_per_minute=tool_call_limit_per_minute,
task_cost_limit=max(0.0, task_cost_limit),
daily_cost_limit=max(0.0, daily_cost_limit),
loop_window_seconds=loop_window_seconds,
)
)
return WatchdogDaemon(
thresholds=WatchdogThresholds(),
warn_only=warn_only,
loop_cost_guard=loop_cost_guard,
)
def _extract_tool_call_cost(result: Dict[str, Any]) -> float:
for key in ("call_cost", "tool_call_cost", "cost", "estimated_cost"):
value = result.get(key)
try:
amount = float(value)
except (TypeError, ValueError):
continue
if amount >= 0:
return amount
usage = result.get("usage")
if isinstance(usage, dict):
for key in ("total_cost", "estimated_cost"):
value = usage.get(key)
try:
amount = float(value)
except (TypeError, ValueError):
continue
if amount >= 0:
return amount
return 0.0
def _build_watchdog_guardrail_payload(
*,
signal: Dict[str, Any],
source: str,
round_num: int,
) -> Dict[str, Any]:
payload = {
"guard_type": "watchdog_loop_guard",
"source": source,
"round": int(round_num),
}
payload.update(signal)
return payload
def _resolve_watchdog_stop_reason(signal: Dict[str, Any]) -> str:
reason = str(signal.get("reason") or signal.get("reason_code") or "").strip().lower()
if reason:
normalized = reason.replace(" ", "_").replace("-", "_")
return f"watchdog_{normalized}"
return "watchdog_guard_hit"
def _should_stop_on_watchdog_signal(signal: Dict[str, Any]) -> bool:
action = str(signal.get("action") or "").strip().lower()
level = str(signal.get("level") or "").strip().lower()
if action in {"kill_agent_loop", "terminate_task_budget_exceeded", "pause_dispatch_and_escalate"}:
return True
if level == "critical" and action not in {"", "alert_only", "throttle_new_workloads"}:
return True
return False
def _resolve_tool_contract_rollout_runtime() -> ToolContractRolloutRuntime:
cfg = get_config()
rollout_cfg = getattr(cfg, "tool_contract_rollout", None)
if rollout_cfg is None:
return ToolContractRolloutRuntime()
emit_metadata = bool(getattr(rollout_cfg, "emit_observability_metadata", True))
return ToolContractRolloutRuntime(emit_observability_metadata=emit_metadata)
def _coalesce_result_text(result: Dict[str, Any]) -> str:
candidates = [
result.get("result"),
result.get("narrative_summary"),
result.get("display_preview"),
]
for value in candidates:
if value is None:
continue
text = str(value)
if text:
return text
return ""
def _clean_optional_ref(value: Any) -> str:
text = str(value if value is not None else "").strip()
if not text:
return ""
if text.lower() in _TOOL_RESULT_NONE_MARKERS:
return ""
return text
def _parse_tagged_tool_result_sections(result_text: str) -> Dict[str, str]:
sections: Dict[str, str] = {}
current_tag: Optional[str] = None
current_lines: List[str] = []
for line in str(result_text or "").splitlines():
stripped = line.strip()
matched = _TOOL_RESULT_TAG_LINE_RE.match(stripped)
if matched:
if current_tag is not None:
sections[current_tag] = "\n".join(current_lines).strip()
current_tag = str(matched.group(1) or "").strip().lower()
inline = str(matched.group(2) or "").strip()
current_lines = [inline] if inline else []
continue
if current_tag is not None:
current_lines.append(line.rstrip())
if current_tag is not None:
sections[current_tag] = "\n".join(current_lines).strip()
return sections
def _normalize_fetch_hints_value(value: Any) -> List[str]:
if value is None:
return []
raw_items: List[str]
if isinstance(value, list):
raw_items = [str(item or "").strip() for item in value]
else:
text = str(value or "").strip()
if not text:
raw_items = []
else:
raw_items = [segment.strip() for segment in text.split(",")]
hints: List[str] = []
seen = set()
for item in raw_items:
if not item:
continue
if item.lower() in _TOOL_RESULT_NONE_MARKERS:
continue
if item in seen:
continue
seen.add(item)
hints.append(item)
return hints
def _extract_result_text_preview(result_payload: Any) -> str:
if isinstance(result_payload, str):
text = result_payload
try:
parsed = json.loads(text)
except Exception:
return text
if isinstance(parsed, dict):
for key in ("narrative_summary", "display_preview", "message", "result"):
value = parsed.get(key)
candidate = str(value if value is not None else "").strip()
if candidate:
return candidate
return text
if isinstance(result_payload, dict):
for key in ("narrative_summary", "display_preview", "message", "result"):
value = result_payload.get(key)
text = str(value if value is not None else "").strip()
if text:
return text
try:
return json.dumps(result_payload, ensure_ascii=False)
except Exception:
return str(result_payload)
if result_payload is None:
return ""
return str(result_payload)
def _upgrade_tool_result_contract_payload(result: Dict[str, Any]) -> Dict[str, Any]:
normalized = dict(result or {})
result_payload = normalized.get("result")
has_legacy_payload = "result" in normalized
result_preview = _extract_result_text_preview(result_payload)
tagged = _parse_tagged_tool_result_sections(result_preview)
parsed_result_payload: Dict[str, Any] = {}
if isinstance(result_payload, dict):
parsed_result_payload = result_payload
elif isinstance(result_payload, str):
try:
maybe = json.loads(result_payload)
if isinstance(maybe, dict):
parsed_result_payload = maybe
except Exception:
parsed_result_payload = {}
# Prefer explicit new-contract fields; fallback to tagged blocks or legacy result text.
narrative_summary = str(
normalized.get("narrative_summary")
or parsed_result_payload.get("narrative_summary")
or parsed_result_payload.get("display_preview")
or parsed_result_payload.get("message")
or parsed_result_payload.get("result")
or tagged.get("narrative_summary")
or tagged.get("display_preview")
or result_preview
or ""
).strip()
display_preview = str(
normalized.get("display_preview")
or parsed_result_payload.get("display_preview")
or parsed_result_payload.get("narrative_summary")
or tagged.get("display_preview")
or narrative_summary
or ""
).strip()
# Some MCP/local tool paths may legally return empty/None payloads.
# In new-stack-only mode this should still be upgraded into new-contract fields
# instead of being treated as legacy-only output.
if has_legacy_payload and not narrative_summary and not display_preview:
status = str(normalized.get("status") or "").strip().lower()
service_name = str(normalized.get("service_name") or "").strip()
tool_name = str(normalized.get("tool_name") or "").strip()
status_text = "tool call returned empty payload"
if status == "success":
status_text = "tool call completed without output payload"
elif status == "error":
status_text = "tool call failed without error detail"
scope = " / ".join(part for part in (service_name, tool_name) if part)
narrative_summary = f"{status_text} ({scope})" if scope else status_text
display_preview = narrative_summary
if narrative_summary:
normalized.setdefault("narrative_summary", narrative_summary)
if display_preview:
normalized.setdefault("display_preview", display_preview)
forensic_ref = _clean_optional_ref(
normalized.get("forensic_artifact_ref")
or normalized.get("raw_result_ref")
or parsed_result_payload.get("forensic_artifact_ref")
or parsed_result_payload.get("raw_result_ref")
or tagged.get("forensic_artifact_ref")
or tagged.get("raw_result_ref")
)
if forensic_ref:
normalized.setdefault("forensic_artifact_ref", forensic_ref)
normalized.setdefault("raw_result_ref", forensic_ref)
if "fetch_hints" not in normalized:
hints = _normalize_fetch_hints_value(
parsed_result_payload.get("fetch_hints") or tagged.get("fetch_hints")
)
if hints:
normalized["fetch_hints"] = hints
if "critical_evidence" not in normalized:
critical_raw = parsed_result_payload.get("critical_evidence") or tagged.get("critical_evidence")
critical_value: Dict[str, Any] = {}
if isinstance(critical_raw, dict):
critical_value = dict(critical_raw)
elif isinstance(critical_raw, str):
text = critical_raw.strip()
if text and text.lower() not in _TOOL_RESULT_NONE_MARKERS:
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
critical_value = parsed
except Exception:
critical_value = {"summary": text}
if critical_value:
normalized["critical_evidence"] = critical_value
return normalized
def _has_new_contract_payload(result: Dict[str, Any]) -> bool:
return any(
bool(str(result.get(key) or "").strip())
for key in ("narrative_summary", "display_preview", "forensic_artifact_ref", "raw_result_ref", "critical_evidence")
)
def _truncate_preview_text(text: Any, *, limit: int) -> str:
normalized = str(text if text is not None else "")
return normalized[:limit] + "..." if len(normalized) > limit else normalized
def _build_frontend_preview(
*,
text: Any,
limit: int,
artifact_ref: str,
) -> Tuple[str, bool]:
normalized = str(text if text is not None else "")
if len(normalized) <= limit:
return normalized, False
if artifact_ref:
prefix = normalized[: min(limit, 320)]
return f"{prefix} ... [truncated, use artifact_reader on {artifact_ref}]", True
return normalized[:limit] + "...", True
def _build_contract_observability_metadata(
results: List[Dict[str, Any]],
*,
rollout: ToolContractRolloutRuntime,
) -> Dict[str, Any]:
metadata: Dict[str, Any] = {"snapshot": rollout.snapshot()}
if not rollout.emit_observability_metadata:
return metadata
stats = {
"result_count": len(results),
"structured_payload_count": 0,
}
for result in results:
meta = result.get("_contract_rollout")
if isinstance(meta, dict):
if bool(meta.get("structured_payload")):
stats["structured_payload_count"] += 1
continue
if _has_new_contract_payload(result):
stats["structured_payload_count"] += 1
metadata["stats"] = stats
return metadata
def _normalize_receipt_next_steps(raw_value: Any) -> List[str]:
if raw_value is None:
return []
if isinstance(raw_value, str):
text = raw_value.strip()
return [text] if text else []
if not isinstance(raw_value, list):
return []
normalized: List[str] = []
for item in raw_value:
text = str(item or "").strip()
if text:
normalized.append(text)
return normalized
def _build_default_receipt_next_steps(
*,
status: str,
risk_level: str,
artifact_ref: str,
error_code: str,
) -> List[str]:
suggestions: List[str] = []
normalized_status = status.lower()
normalized_risk = risk_level.lower()
if normalized_status == "error":
if error_code == _RISK_ERR_APPROVAL_REQUIRED:
return ["request_human_approval_then_retry"]
if error_code == _RISK_ERR_POLICY_BLOCKED:
return ["select_lower_risk_alternative", "request_policy_exception_if_justified"]
suggestions.append("inspect_error_and_retry")
if artifact_ref:
suggestions.append("read_artifact_with_artifact_reader")
return suggestions
if artifact_ref:
suggestions.append("follow_up_with_artifact_reader_if_needed")
if normalized_risk in {"write_repo", "deploy", "secrets", "self_modify"}:
suggestions.append("run_post_change_verification")
else:
suggestions.append("continue_next_planned_step")
return suggestions
def _build_tool_receipt(call: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
context = call.get("_context_metadata")
if not isinstance(context, dict):
context = {}
trace_id = str(call.get("_trace_id") or call.get("trace_id") or context.get("trace_id") or "").strip()
idempotency_key = str(call.get("idempotency_key") or context.get("idempotency_key") or "").strip()
risk_level = str(call.get("_risk_level") or call.get("risk_level") or context.get("risk_level") or "read_only").strip()
execution_scope = str(
call.get("_execution_scope") or call.get("execution_scope") or context.get("execution_scope") or "local"
).strip()
requires_global_mutex = bool(
call.get("_requires_global_mutex")
if "_requires_global_mutex" in call
else (call.get("requires_global_mutex") or context.get("requires_global_mutex"))
)
estimated_token_cost = _clamp_int(
call.get("estimated_token_cost", context.get("estimated_token_cost", 0)),
0,
0,
100_000_000,
)
budget_remaining_raw = call.get("budget_remaining", context.get("budget_remaining"))
budget_remaining: Optional[int] = None
if budget_remaining_raw is not None:
try:
budget_remaining = int(budget_remaining_raw)
except Exception:
budget_remaining = None
artifact_ref = str(result.get("forensic_artifact_ref") or result.get("raw_result_ref") or "").strip()
status = str(result.get("status", "unknown")).strip().lower()
error_code = str(result.get("error_code") or "").strip()
approval_required = bool(
call.get("_approval_required")
if "_approval_required" in call
else (call.get("approval_required") or context.get("approval_required"))
)
approval_policy = str(
call.get("_approval_policy")
or call.get("approvalPolicy")
or call.get("approval_policy")
or context.get("approval_policy")
or ""
).strip()
approval_granted = bool(call.get("approval_granted") or call.get("approved") or call.get("_approval_granted"))
next_steps = _normalize_receipt_next_steps(result.get("next_steps"))
if not next_steps:
next_steps = _build_default_receipt_next_steps(
status=status,
risk_level=risk_level,
artifact_ref=artifact_ref,
error_code=error_code,
)
risk_items: List[str] = []
if status == "error":
risk_items.append("tool_execution_failed")
if risk_level in {"write_repo", "deploy", "secrets", "self_modify"}:
risk_items.append(f"high_risk_action:{risk_level}")
if error_code == _RISK_ERR_APPROVAL_REQUIRED:
risk_items.append("approval_required_gate")
if error_code == _RISK_ERR_POLICY_BLOCKED:
risk_items.append("risk_policy_block_gate")
if requires_global_mutex:
risk_items.append("global_mutex_required")
if approval_required:
risk_items.append(f"approval_hook:{approval_policy or 'unspecified'}")
return {
"version": "ws10-004-v1",
"call_type": str(call.get("agentType") or "unknown"),
"service_name": str(result.get("service_name") or call.get("service_name") or "unknown"),
"tool_name": str(result.get("tool_name") or call.get("tool_name") or "unknown"),
"trace_id": trace_id,
"idempotency_key": idempotency_key,
"risk_level": risk_level,
"execution_scope": execution_scope,
"requires_global_mutex": requires_global_mutex,
"approval": {
"required": approval_required,
"policy": approval_policy or None,
"granted": approval_granted,
},
"budget": {
"estimated_token_cost": estimated_token_cost,
"budget_remaining": budget_remaining,
},
"result": {
"status": status,
"error_code": error_code or None,
"has_artifact": bool(artifact_ref),
"forensic_artifact_ref": artifact_ref or None,
},
"risk_items": risk_items,
"next_steps": next_steps,
}
def _attach_tool_receipt(call: Dict[str, Any], result: Dict[str, Any]) -> None:
if not isinstance(result, dict):
return
if not isinstance(call, dict):
call = {}
result["tool_receipt"] = _build_tool_receipt(call, result)
def _normalize_approval_policy(raw_value: Any) -> str:
value = str(raw_value or "").strip().lower()
if not value:
return ""
aliases = {
"on_request": "on-request",
"onrequest": "on-request",
"manual_approval": "manual",
"required_approval": "required",
"auto": "on-failure",
}
return aliases.get(value, value)
def _is_truthy_flag(value: Any) -> bool:
if isinstance(value, bool):
return value
if value is None:
return False
text = str(value).strip().lower()
return text in {"1", "true", "yes", "y", "on"}
def _resolve_call_risk_level(call: Dict[str, Any]) -> str:
return str(call.get("_risk_level") or call.get("risk_level") or "read_only").strip().lower() or "read_only"
def _evaluate_risk_gate(call: Dict[str, Any]) -> Dict[str, Any]:
risk_level = _resolve_call_risk_level(call)
if risk_level not in _HIGH_RISK_LEVELS:
call["_approval_required"] = False
normalized_policy = _normalize_approval_policy(
call.get("_approval_policy") or call.get("approvalPolicy") or call.get("approval_policy")
)
if normalized_policy:
call["_approval_policy"] = normalized_policy
call.setdefault("approvalPolicy", normalized_policy)
return {
"allowed": True,
"risk_level": risk_level,
"requires_approval": False,
"approval_policy": normalized_policy,
"approval_granted": _is_truthy_flag(call.get("approval_granted") or call.get("approved")),
}
normalized_policy = _normalize_approval_policy(
call.get("_approval_policy") or call.get("approvalPolicy") or call.get("approval_policy")
)
if not normalized_policy:
normalized_policy = _RISK_DEFAULT_APPROVAL_POLICY.get(risk_level, "on-request")
call["_approval_required"] = True
call["_approval_policy"] = normalized_policy
call.setdefault("approvalPolicy", normalized_policy)
approval_granted = _is_truthy_flag(call.get("approval_granted") or call.get("approved") or call.get("_approval_granted"))
if normalized_policy in _RISK_POLICY_BLOCKLIST:
return {
"allowed": False,
"risk_level": risk_level,
"requires_approval": True,
"approval_policy": normalized_policy,
"approval_granted": approval_granted,
"error_code": _RISK_ERR_POLICY_BLOCKED,
"reason": f"risk gate blocked: {risk_level} call has approval_policy={normalized_policy}",
}
if risk_level in {"secrets", "self_modify"} and not approval_granted:
return {
"allowed": False,
"risk_level": risk_level,
"requires_approval": True,
"approval_policy": normalized_policy,
"approval_granted": False,
"error_code": _RISK_ERR_APPROVAL_REQUIRED,
"reason": f"risk gate requires explicit human approval for {risk_level}",
}
if normalized_policy in _RISK_POLICY_STRICT_APPROVAL and not approval_granted:
return {
"allowed": False,
"risk_level": risk_level,
"requires_approval": True,
"approval_policy": normalized_policy,
"approval_granted": False,
"error_code": _RISK_ERR_APPROVAL_REQUIRED,
"reason": f"risk gate requires explicit approval when approval_policy={normalized_policy}",
}
return {
"allowed": True,
"risk_level": risk_level,
"requires_approval": True,
"approval_policy": normalized_policy,
"approval_granted": approval_granted,
}
def _is_retryable_tool_failure(call: Dict[str, Any], result: Dict[str, Any]) -> bool:
if bool(call.get("no_retry", False)):
return False
err_text = _coalesce_result_text(result)
non_retry_markers = [
"需要登录",
"缺少",
"不支持",
"参数",
"安全限制",
"Blocked",
"blocked",
"unauthorized",
"forbidden",
]
return not any(marker in err_text for marker in non_retry_markers)
def _summarize_results_for_frontend(
results: List[Dict[str, Any]],
preview_chars: int,
*,
rollout: Optional[ToolContractRolloutRuntime] = None,
) -> List[Dict[str, Any]]:
rollout_runtime = rollout or _resolve_tool_contract_rollout_runtime()
summaries: List[Dict[str, Any]] = []
limit = _clamp_int(preview_chars, 500, 120, 20000)
for r in results:
summary = {
"service_name": r.get("service_name", "unknown"),
"tool_name": r.get("tool_name", ""),
"status": r.get("status", "unknown"),
}
result_text = _coalesce_result_text(r)
artifact_ref = str(r.get("forensic_artifact_ref") or r.get("raw_result_ref") or "").strip()
preview_text = r.get("display_preview", r.get("narrative_summary", result_text))
preview_value, preview_truncated = _build_frontend_preview(
text=preview_text,
limit=limit,
artifact_ref=artifact_ref,
)
summary["preview"] = preview_value
if preview_truncated:
summary["preview_truncated"] = True
narrative_text = r.get("narrative_summary", r.get("display_preview", result_text))
narrative_value, narrative_truncated = _build_frontend_preview(
text=narrative_text,
limit=limit,
artifact_ref=artifact_ref,
)
summary["narrative_summary"] = narrative_value
if narrative_truncated:
summary["narrative_summary_truncated"] = True
if artifact_ref:
summary["forensic_artifact_ref"] = artifact_ref
if rollout_runtime.emit_observability_metadata:
meta = r.get("_contract_rollout")
if isinstance(meta, dict):
summary["contract_rollout"] = meta
receipt = r.get("tool_receipt")
if not isinstance(receipt, dict):
tool_call = r.get("tool_call")
if isinstance(tool_call, dict):
receipt = _build_tool_receipt(tool_call, r)
if isinstance(receipt, dict):
summary["tool_receipt"] = receipt
summaries.append(summary)
if r.get("conflict_ticket"):
summaries[-1]["conflict_ticket"] = str(r.get("conflict_ticket"))
if r.get("delegate_turns") is not None:
summaries[-1]["delegate_turns"] = _clamp_int(r.get("delegate_turns"), 0, 0, 10000)
if "freeze" in r:
summaries[-1]["freeze"] = bool(r.get("freeze"))
if "hitl" in r:
summaries[-1]["hitl"] = bool(r.get("hitl"))
router_arbiter = r.get("router_arbiter")
if isinstance(router_arbiter, dict):
summaries[-1]["router_arbiter"] = router_arbiter
gc_budget_guard = r.get("gc_budget_guard")
if isinstance(gc_budget_guard, dict):
summaries[-1]["gc_budget_guard"] = gc_budget_guard
if "guard_hit" in r:
summaries[-1]["guard_hit"] = bool(r.get("guard_hit"))
if r.get("guard_stop_reason"):
summaries[-1]["guard_stop_reason"] = str(r.get("guard_stop_reason"))
return summaries
def _build_tool_call_descriptions(actionable_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
descriptions: List[Dict[str, Any]] = []
for tc in actionable_calls:
descriptions.append(
{
"agentType": str(tc.get("agentType", "")),
"service_name": str(tc.get("service_name", "")),
"tool_name": str(tc.get("tool_name", "")),
"message": str(tc.get("message", ""))[:100],
"call_id": str(tc.get("_tool_call_id", "")),
"risk_level": str(tc.get("_risk_level", "read_only")),
"execution_scope": str(tc.get("_execution_scope", "local")),
"requires_global_mutex": bool(tc.get("_requires_global_mutex", False)),
}
)
return descriptions
def _extract_terminal_stream_error_text(text: str) -> str:
"""Detect fatal upstream stream errors that should stop the loop immediately."""
if not text:
return ""
normalized = " ".join(str(text).strip().split())
lowered = normalized.lower()
markers = (
"streaming call error",
"google streaming error",
"google live streaming error",
"llm service unavailable",
"chat call error",
"google api call error",
"login expired",
)
return normalized if any(marker in lowered for marker in markers) else ""
_CODING_KEYWORDS = (
"修复",
"实现",
"重构",
"改造",
"写代码",
"代码",
"开发",
"bug",
"fix",
"implement",
"refactor",
"coding",
"unit test",
"integration test",
"lint",
"compile",
"build",
"repo",
"repository",
)
_MUTATING_NATIVE_TOOL_NAMES = {"write_file", "git_checkout_file", "workspace_txn_apply"}
_SCHEMA_ERR_INPUT_INVALID = "E_SCHEMA_INPUT_INVALID"
_SCHEMA_ERR_OUTPUT_INVALID = "E_SCHEMA_OUTPUT_INVALID"
_RISK_ERR_APPROVAL_REQUIRED = "E_RISK_APPROVAL_REQUIRED"
_RISK_ERR_POLICY_BLOCKED = "E_RISK_POLICY_BLOCKED"
_NATIVE_TOOL_ALIASES = {
"read": "read_file",
"write": "write_file",
"cwd": "get_cwd",
"exec": "run_cmd",
"search": "search_keyword",
"docs": "query_docs",
"ls": "list_files",
"status": "git_status",
"diff": "git_diff",
"log": "git_log",
"show": "git_show",
"blame": "git_blame",
"grep": "search_keyword",
"changed": "git_changed_files",
"checkout": "git_checkout_file",
"python": "python_repl",
"python_exec": "python_repl",
"artifact": "artifact_reader",
"read_artifact": "artifact_reader",
"file_ast_chunk": "file_ast_chunk_read",
"readchunkbyrange": "file_ast_chunk_read",
"ast_edit": "file_ast_edit",
"file_ast_replace": "file_ast_edit",
"sleep_watch": "sleep_and_watch",
"watch_log": "sleep_and_watch",
"txn_apply": "workspace_txn_apply",
"scaffold_apply": "workspace_txn_apply",
"killswitch": "killswitch_plan",
"repl": "python_repl",
}
_SUPPORTED_NATIVE_TOOL_NAMES = {