-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
1432 lines (1246 loc) · 52.2 KB
/
Copy pathagent.py
File metadata and controls
1432 lines (1246 loc) · 52.2 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
# 后端八股网站:xiaolincoding.com
# Agent网站:xiaolinnote.com
# 简历模版:jianli.xiaolinnote.com
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any
from pydantic import ValidationError
from kkcode.client import LLMClient
from kkcode.context import (
CompactBoundary,
CompactCircuitBreaker,
CompactEvent,
RecoveryState,
apply_tool_result_budget,
auto_compact,
ensure_session_dir,
is_spill_readback,
)
from kkcode.conversation import ConversationManager, ToolResultBlock, ToolUseBlock
from kkcode.conversation import ThinkingBlock as ConvThinkingBlock
from kkcode.conversation_pairing import REJECTED_TOOL_RESULT
from kkcode.hooks import HookContext, HookEngine
from kkcode.memory.auto_memory import MemoryManager
from kkcode.permissions import (
PermissionChecker,
PermissionMode,
)
from kkcode.prompts import (
build_environment_context,
build_plan_mode_reminder,
build_system_prompt,
)
from kkcode.tools import ToolRegistry
from kkcode.tools.base import (
MAX_OUTPUT_CHARS,
StreamEnd,
StreamEvent,
TextDelta,
ThinkingComplete,
ThinkingDelta,
ToolCallComplete,
ToolCallDelta,
ToolCallStart,
ToolResult,
)
log = logging.getLogger(__name__)
MEMORY_EXTRACTION_INTERVAL = 1
MAX_TOKENS_CEILING = 64000
MAX_OUTPUT_TOKENS_RECOVERIES = 3
# ---------------------------------------------------------------------------
# AgentEvent 事件类型
# ---------------------------------------------------------------------------
@dataclass
class StreamText:
text: str
@dataclass
class ThinkingText:
text: str
@dataclass
class RetryEvent:
reason: str
wait: float = 0.0
@dataclass
class ToolUseEvent:
tool_name: str
tool_id: str
arguments: dict[str, Any]
@dataclass
class ToolResultEvent:
tool_id: str
tool_name: str
output: str
is_error: bool
elapsed: float
@dataclass
class TurnComplete:
turn: int
@dataclass
class LoopComplete:
total_turns: int
@dataclass
class UsageEvent:
input_tokens: int
output_tokens: int
@dataclass
class ErrorEvent:
message: str
@dataclass
class CompactNotification:
before_tokens: int
message: str
# 结构化 boundary(摘要 + 原文保留尾部),UI/session 层用它持久化 compact_boundary 记录。
# 失败路径下为 None。
boundary: CompactBoundary | None = None
@dataclass
class HookEvent:
hook_id: str
event: str
output: str
success: bool
class PermissionResponse(Enum):
ALLOW = "allow"
DENY = "deny"
ALLOW_ALWAYS = "allow_always"
@dataclass
class PermissionRequest:
tool_name: str
description: str
future: asyncio.Future[PermissionResponse]
AgentEvent = (
StreamText
| ThinkingText
| RetryEvent
| ToolUseEvent
| ToolResultEvent
| TurnComplete
| LoopComplete
| UsageEvent
| ErrorEvent
| PermissionRequest
| CompactNotification
| HookEvent
)
# ---------------------------------------------------------------------------
# LLM 响应收集器
# ---------------------------------------------------------------------------
@dataclass
class ThinkingBlock:
thinking: str
signature: str
@dataclass
class LLMResponse:
text: str = ""
tool_calls: list[ToolCallComplete] = field(default_factory=list)
thinking_blocks: list[ThinkingBlock] = field(default_factory=list)
stop_reason: str = ""
input_tokens: int = 0
output_tokens: int = 0
cache_read: int = 0
cache_creation: int = 0
class StreamCollector:
def __init__(self) -> None:
self.response = LLMResponse()
async def consume(
self, stream: AsyncIterator[StreamEvent]
) -> AsyncIterator[AgentEvent]:
async for event in stream:
if isinstance(event, TextDelta):
self.response.text += event.text
yield StreamText(text=event.text)
elif isinstance(event, ThinkingDelta):
yield ThinkingText(text=event.text)
elif isinstance(event, ThinkingComplete):
self.response.thinking_blocks.append(
ThinkingBlock(thinking=event.thinking, signature=event.signature)
)
elif isinstance(event, ToolCallStart):
pass
elif isinstance(event, ToolCallDelta):
pass
elif isinstance(event, ToolCallComplete):
self.response.tool_calls.append(event)
yield ToolUseEvent(
tool_name=event.tool_name,
tool_id=event.tool_id,
arguments=event.arguments,
)
elif isinstance(event, StreamEnd):
self.response.stop_reason = event.stop_reason
self.response.input_tokens = event.input_tokens
self.response.output_tokens = event.output_tokens
self.response.cache_read = event.cache_read
self.response.cache_creation = event.cache_creation
# ---------------------------------------------------------------------------
# tool 批量执行
# ---------------------------------------------------------------------------
@dataclass
class ToolBatch:
concurrent: bool
calls: list[ToolCallComplete]
def partition_tool_calls(
tool_calls: list[ToolCallComplete],
registry: ToolRegistry,
) -> list[ToolBatch]:
batches: list[ToolBatch] = []
for tc in tool_calls:
tool = registry.get(tc.tool_name)
safe = (
tool is not None
and tool.is_concurrency_safe
and registry.is_enabled(tc.tool_name)
)
if safe and batches and batches[-1].concurrent:
batches[-1].calls.append(tc)
else:
batches.append(ToolBatch(concurrent=safe, calls=[tc]))
return batches
# ---------------------------------------------------------------------------
# streaming 执行器 — 在 LLM streaming 期间启动 tool 执行
# ---------------------------------------------------------------------------
@dataclass
class _ToolExecResult:
tool_id: str
tool_name: str
result: ToolResult
elapsed: float
class StreamingExecutor:
def __init__(self) -> None:
self._tasks: list[tuple[int, asyncio.Task[_ToolExecResult]]] = []
self._order = 0
def submit(
self,
coro: Any,
) -> None:
task = asyncio.create_task(coro)
self._tasks.append((self._order, task))
self._order += 1
async def collect_results(self) -> list[_ToolExecResult]:
if not self._tasks:
return []
tasks = [t for _, t in sorted(self._tasks, key=lambda x: x[0])]
results = await asyncio.gather(*tasks, return_exceptions=True)
out: list[_ToolExecResult] = []
for r in results:
if isinstance(r, Exception):
out.append(
_ToolExecResult(
tool_id="",
tool_name="",
result=ToolResult(
output=f"Tool execution error: {r}", is_error=True
),
elapsed=0.0,
)
)
else:
out.append(r)
return out
# ---------------------------------------------------------------------------
# Agent 主循环
# ---------------------------------------------------------------------------
# 延迟工具清单提醒的固定开头。用它在历史里回认这条提醒还在不在:compact 把历史压
# 成摘要之后原来那条就没了,得重发一遍
DEFERRED_REMINDER_MARKER = "The following deferred tools are available via ToolSearch."
class Agent:
def __init__(
self,
client: LLMClient,
registry: ToolRegistry,
protocol: str,
work_dir: str = ".",
max_iterations: int = 0,
permission_checker: PermissionChecker | None = None,
context_window: int = 200_000,
instructions_content: str = "",
memory_manager: MemoryManager | None = None,
hook_engine: HookEngine | None = None,
) -> None:
self.client = client
self.registry = registry
self.protocol = protocol
self.work_dir = work_dir
self.max_iterations = max_iterations
self.permission_checker = permission_checker
self.permission_mode: PermissionMode = (
permission_checker.mode if permission_checker else PermissionMode.DEFAULT
)
self.context_window = context_window
self.compact_breaker = CompactCircuitBreaker()
# 保存重建工作上下文所需的快照,在 Layer 2 压缩对话后使用:
# 最近的文件读取和 skill 调用。每次 ReadFile / skill 调用时记录,
# auto_compact 触发阈值时消费。
self.recovery_state: RecoveryState = RecoveryState()
self.total_input_tokens = 0
self.total_output_tokens = 0
self.instructions_content = instructions_content
self.memory_manager = memory_manager
self.hook_engine = hook_engine
self._loop_count = 0
# 上一次告诉模型的延迟工具清单,按字典序。跟当前清单一比就知道工具池有没有
# 变,没变就不重发那条提醒
self._announced_deferred: list[str] = []
# 记忆提取合并策略:_extracting 期间触发新请求会标记 _pending_extraction,
# _extracting: 标记是否有提取正在进行
# _pending_extraction: 提取期间又触发了新请求,标记需要尾随提取
self._extracting = False
self._pending_extraction = False
self._consolidator: MemoryConsolidator | None = None
if memory_manager is not None:
from kkcode.memory.consolidation import MemoryConsolidator
self._consolidator = MemoryConsolidator(work_dir)
self.session_id: str = ""
self.active_skills: dict[str, str] = {}
self._skill_catalog: str = ""
self._agent_catalog: str = ""
self._agent_catalog_list: list[tuple[str, str]] = []
self.agent_id: str = uuid.uuid4().hex[:12]
self.parent_id: str | None = None
self.trace_id: str | None = None
self.team_name: str = ""
self._team_manager: Any = None
# coordinator 模式的开关,由配置显式打开
self.enable_coordinator_mode: bool = False
self.notification_fn: Callable[[], list[str]] | None = None
self.file_history: Any = None
# 非阻塞 memory recall:prefetch task 与主 LLM 调用并行,工具执行后注入
self.memory_recall_task: Any | None = None
self._memory_recall_consumed: bool = False
def _announce_deferred_tools(self, conversation: ConversationManager) -> None:
"""把延迟工具名清单告诉模型,只在需要的时候发。
dispatch 模式下这些工具永远不会进 tools[],必须额外告诉模型调用要走
mcp_call,否则它读完 schema 也不知道从哪儿调。
这条提醒是 append 进历史的,发过一次就一直在上下文里,之后每轮再发一遍只
是拿同样的内容占窗口:六十来个 MCP 工具一份清单五百多 token,四十轮下来
就是两万多。所以只在两种情况重发,池子变了(MCP 是异步连上的,服务器也
可能掉线重连),或者历史里那条已经被 compact 压掉了。后者靠回扫历史发现,
这样就不用在 compact 那边额外挂钩子。
"""
deferred_names = self.registry.get_deferred_tool_names()
if not deferred_names:
return
pool_changed = deferred_names != self._announced_deferred
if not pool_changed and conversation.has_reminder_containing(
DEFERRED_REMINDER_MARKER
):
return
from kkcode.mcp.loading_strategy import McpLoadingMode
tail = (
", then invoke them with the mcp_call tool"
if self.registry.mcp_loading_mode is McpLoadingMode.DISPATCH
else " before calling them"
)
conversation.add_system_reminder(
DEFERRED_REMINDER_MARKER
+ " Their schemas are NOT loaded - use ToolSearch with "
'query "select:<name>[,<name>...]" to load tool schemas'
+ tail
+ ":\n"
+ "\n".join(deferred_names)
)
self._announced_deferred = deferred_names
@property
def session_dir(self) -> Path:
# 溢写目录跟随当前会话 id(resume 换会话后自动指向新目录)
return ensure_session_dir(self.work_dir, self.session_id)
@property
def _transcript_path(self) -> str:
if self.session_id:
return str(
Path(self.work_dir)
/ ".kkcode"
/ "sessions"
/ f"{self.session_id}.jsonl"
)
return ""
@property
def plan_mode(self) -> bool:
return self.permission_mode == PermissionMode.PLAN
@property
def coordinator_mode(self) -> bool:
"""coordinator 模式是否生效,只看配置开关。
不看团队是否存在:模式在会话中途切换会留下麻烦,已经发出去的调度指引
留在对话历史里撤不回来,模型会照着过期的约束继续做事。
配置说了算,从第一轮到最后一轮都是同一套规则。
"""
return self.enable_coordinator_mode
_plan_path_cache: Path | None = None
def _get_plan_path(self) -> Path:
if self._plan_path_cache is not None:
return self._plan_path_cache
import datetime
import random
_ADJECTIVES = [
"bold",
"bright",
"calm",
"cool",
"deep",
"fair",
"fast",
"fine",
"glad",
"keen",
"kind",
"lean",
"mild",
"neat",
"pure",
"safe",
"slim",
"soft",
"tall",
"warm",
"wise",
"grand",
"swift",
"vivid",
]
_NOUNS = [
"sketch",
"draft",
"spark",
"bloom",
"trail",
"ridge",
"creek",
"grove",
"cliff",
"cloud",
"field",
"forge",
"frost",
"haven",
"pearl",
"stone",
"storm",
"river",
"tower",
"delta",
"flame",
"orbit",
"pulse",
"shore",
]
plans_dir = Path(self.work_dir) / ".kkcode" / "plans"
plans_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.datetime.now().strftime("%m%d-%H%M")
slug = f"{random.choice(_ADJECTIVES)}-{random.choice(_NOUNS)}-{ts}"
self._plan_path_cache = plans_dir / f"{slug}.md"
return self._plan_path_cache
def set_permission_mode(self, mode: PermissionMode) -> None:
self.permission_mode = mode
if self.permission_checker:
self.permission_checker.mode = mode
def activate_skill(self, name: str, prompt_body: str) -> None:
self.active_skills[name] = prompt_body
def clear_active_skills(self) -> None:
self.active_skills.clear()
def set_skill_catalog(self, catalog: str) -> None:
self._skill_catalog = catalog
def set_agent_catalog(
self, catalog: str, catalog_list: list[tuple[str, str]] | None = None
) -> None:
self._agent_catalog = catalog
if catalog_list is not None:
self._agent_catalog_list = catalog_list
def _build_hook_context(self, event: str, **kwargs: str | dict) -> HookContext:
return HookContext(
event_name=event,
tool_name=str(kwargs.get("tool_name", "")),
tool_args=kwargs.get("tool_args", {}),
file_path=str(kwargs.get("file_path", "")),
message=str(kwargs.get("message", "")),
error=str(kwargs.get("error", "")),
)
def _infer_file_path(self, args: dict) -> str:
return str(args.get("file_path", args.get("path", "")))
def _drain_hook_events(self) -> list[HookEvent]:
if not self.hook_engine:
return []
return [
HookEvent(
hook_id=n.hook_id,
event=n.event,
output=n.output,
success=n.success,
)
for n in self.hook_engine.drain_notifications()
]
async def run(self, conversation: ConversationManager) -> AsyncIterator[AgentEvent]:
self._current_conversation = conversation
env_context = build_environment_context(
self.work_dir, self.active_skills, self._skill_catalog, self._agent_catalog
)
conversation.inject_environment(env_context)
memory_content = self.memory_manager.load() if self.memory_manager else ""
conversation.inject_long_term_memory(self.instructions_content, memory_content)
if self.hook_engine:
ctx = self._build_hook_context("session_start")
await self.hook_engine.run_hooks("session_start", ctx)
for he in self._drain_hook_events():
yield he
iteration = 0
max_tokens_escalated = False
output_recoveries = 0
while True:
iteration += 1
if self.max_iterations > 0 and iteration > self.max_iterations:
yield ErrorEvent(
message=f"Agent reached maximum iterations ({self.max_iterations})"
)
break
if self.hook_engine:
ctx = self._build_hook_context("turn_start")
await self.hook_engine.run_hooks("turn_start", ctx)
for he in self._drain_hook_events():
yield he
self._consume_mailbox(conversation)
if self.notification_fn:
for note in self.notification_fn():
conversation.add_system_reminder(note)
if self.hook_engine:
ctx = self._build_hook_context("pre_send")
await self.hook_engine.run_hooks("pre_send", ctx)
for he in self._drain_hook_events():
yield he
hook_prompts = (
self.hook_engine.get_prompt_messages() if self.hook_engine else None
)
system = build_system_prompt(
hook_prompts=hook_prompts, work_dir=self.work_dir
)
if self.plan_mode:
plan_path = str(self._get_plan_path())
if self.permission_checker:
self.permission_checker.plan_file_path = plan_path
plan_exists = self._get_plan_path().exists()
plan_reminder = build_plan_mode_reminder(
plan_path, plan_exists, iteration
)
conversation.add_system_reminder(plan_reminder)
# Coordinator 模式:工具集被收窄的同时注入调度指引。
# 走 system-reminder 而不是替换系统提示词:长会话里开头那份约束会被淹没,
# 每轮追加一次才拉得回来,而且 Lead 仍然需要身份、环境、项目指令和记忆这些基础段落。
if self.coordinator_mode:
from kkcode.teams.coordinator import get_coordinator_reminder
conversation.add_system_reminder(
get_coordinator_reminder(
iteration,
agent_catalog=self._agent_catalog_list or None,
)
)
if self.hook_engine:
for note in self.hook_engine.drain_notifications():
conversation.add_system_reminder(
f"Hook [{note.hook_id}] {note.event}: {note.output}"
)
self._announce_deferred_tools(conversation)
tools = self.registry.get_all_schemas(self.protocol)
# Layer 2: 接近 context window 上限时自动 compact
# Layer 1(工具结果预算)在结果入历史时已处理完,历史里的内容
# 就是最终大小,直接用 conversation.history 估算
compact_result = await auto_compact(
conversation,
self.client,
self.context_window,
self.session_dir,
protocol=self.protocol,
breaker=self.compact_breaker,
recovery=self.recovery_state,
tool_schemas=self.registry.get_all_schemas(self.protocol),
transcript_path=self._transcript_path,
)
if isinstance(compact_result, CompactEvent):
yield CompactNotification(
before_tokens=compact_result.before_tokens,
message=f"上下文已压缩(压缩前 {compact_result.before_tokens:,} tokens)",
boundary=compact_result.boundary,
)
conversation.inject_environment(env_context)
mem = self.memory_manager.load() if self.memory_manager else ""
conversation.inject_long_term_memory(self.instructions_content, mem)
elif isinstance(compact_result, str):
yield ErrorEvent(message=compact_result)
collector = StreamCollector()
executor = StreamingExecutor()
deferred_tool_calls: list[ToolCallComplete] = []
llm_stream = self.client.stream(conversation, system=system, tools=tools)
async for event in collector.consume(llm_stream):
# 流式工具执行:收到完整 tool_use 就立刻提交执行,不等整个响应结束
if isinstance(event, ToolUseEvent):
tc = collector.response.tool_calls[-1]
# 需要交互式权限确认的工具延迟到流结束后顺序执行
tool = self.registry.get(tc.tool_name)
needs_ask = False
if tool and self.permission_checker:
decision = self.permission_checker.check(tool, tc.arguments)
needs_ask = decision.effect == "ask"
if needs_ask:
deferred_tool_calls.append(tc)
else:
executor.submit(self._execute_single_tool_direct(tc))
yield event
response = collector.response
if self.hook_engine:
ctx = self._build_hook_context("post_receive", message=response.text)
await self.hook_engine.run_hooks("post_receive", ctx)
for he in self._drain_hook_events():
yield he
self.total_input_tokens += response.input_tokens
self.total_output_tokens += response.output_tokens
yield UsageEvent(
input_tokens=self.total_input_tokens,
output_tokens=self.total_output_tokens,
)
conv_thinking = [
ConvThinkingBlock(thinking=tb.thinking, signature=tb.signature)
for tb in response.thinking_blocks
]
if response.stop_reason == "max_tokens":
if not max_tokens_escalated:
self.client.set_max_output_tokens(MAX_TOKENS_CEILING)
max_tokens_escalated = True
if response.text:
conversation.add_assistant_message(
response.text, thinking_blocks=conv_thinking
)
conversation.add_user_message(
"Output token limit hit. Resume directly from where you stopped. "
"Do not apologize or repeat previous content. Pick up mid-thought if needed."
)
yield RetryEvent(reason="max_tokens escalation")
continue
elif output_recoveries < MAX_OUTPUT_TOKENS_RECOVERIES:
output_recoveries += 1
conversation.add_assistant_message(
response.text, thinking_blocks=conv_thinking
)
conversation.add_user_message(
"Output token limit hit. Resume directly from where you stopped. "
"Break remaining work into smaller pieces."
)
yield RetryEvent(
reason=f"max_tokens recovery {output_recoveries}/{MAX_OUTPUT_TOKENS_RECOVERIES}"
)
continue
else:
output_recoveries = 0
if not response.tool_calls:
conversation.add_assistant_message(
response.text, thinking_blocks=conv_thinking
)
self._loop_count += 1
if (
self._loop_count % MEMORY_EXTRACTION_INTERVAL == 0
and self.memory_manager
):
asyncio.ensure_future(self._extract_memories(conversation))
if self._consolidator is not None:
asyncio.ensure_future(
self._consolidator.maybe_run(
self.client, conversation, self.protocol
)
)
if self.hook_engine:
ctx = self._build_hook_context("turn_end")
await self.hook_engine.run_hooks("turn_end", ctx)
ctx = self._build_hook_context("session_end")
await self.hook_engine.run_hooks("session_end", ctx)
for he in self._drain_hook_events():
yield he
if self.file_history is not None:
summary = (
response.text[:60] + "..."
if len(response.text) > 60
else response.text
)
self.file_history.make_snapshot(len(conversation.history), summary)
yield LoopComplete(total_turns=iteration)
break
tool_uses = [
ToolUseBlock(
tool_use_id=tc.tool_id,
tool_name=tc.tool_name,
arguments=tc.arguments,
)
for tc in response.tool_calls
]
conversation.add_assistant_message(
response.text, tool_uses, thinking_blocks=conv_thinking
)
# 在 assistant 回复加入历史后锚定实际用量:基线(input + cache + output)
# 覆盖到当前位置,因此下一轮迭代顶部的 auto-compact 检查只需对
# 接下来追加的 tool results 做字符估算。
conversation.record_usage_anchor(
response.input_tokens,
response.output_tokens,
response.cache_read,
response.cache_creation,
)
# 溢写文件的回读结果豁免溢写:把模型刚读回来的内容再写盘换成
# 预览,模型就永远看不到全文,还会在「读回、溢写」之间打转
exempt_ids = {
tc.tool_id
for tc in response.tool_calls
if is_spill_readback(tc.tool_name, tc.arguments, self.session_dir)
}
# 收集流式执行器中已提交的工具结果(工具在 LLM 流式输出期间已开始执行)
tool_results: list[ToolResultBlock] = []
streaming_results = await executor.collect_results()
for br in streaming_results:
content = self._maybe_persist_or_truncate(
br.tool_id, br.result.output, exempt_ids
)
tool_results.append(
ToolResultBlock(
tool_use_id=br.tool_id,
content=content,
is_error=br.result.is_error,
content_blocks=br.result.content_blocks,
)
)
yield ToolResultEvent(
tool_id=br.tool_id,
tool_name=br.tool_name,
output=br.result.output,
is_error=br.result.is_error,
elapsed=br.elapsed,
)
# 需要交互式权限确认的工具,在流结束后顺序执行
for tc in deferred_tool_calls:
result: ToolResult | None = None
elapsed = 0.0
async for item in self._execute_tool(tc):
if isinstance(item, PermissionRequest):
yield item
else:
result, elapsed = item
if result is None:
result = ToolResult(
output="Error: no result from tool", is_error=True
)
content = self._maybe_persist_or_truncate(
tc.tool_id, result.output, exempt_ids
)
tool_results.append(
ToolResultBlock(
tool_use_id=tc.tool_id,
content=content,
is_error=result.is_error,
content_blocks=result.content_blocks,
)
)
yield ToolResultEvent(
tool_id=tc.tool_id,
tool_name=tc.tool_name,
output=result.output,
is_error=result.is_error,
elapsed=elapsed,
)
exit_plan_called = any(
tc.tool_name == "ExitPlanMode" for tc in response.tool_calls
)
# 聚合预算:一轮并行工具的结果落在同一条消息里,单条阈值管不住
# 合计超限的情况。进历史前把整批处理完,消息一出生就是终态
apply_tool_result_budget(tool_results, self.session_dir, exempt_ids)
conversation.add_tool_results_message(tool_results)
# 非阻塞 memory recall:工具执行完后检查 prefetch 是否就绪
if self.memory_recall_task and not self._memory_recall_consumed:
if self.memory_recall_task.done():
try:
recall = self.memory_recall_task.result()
if recall:
conversation.add_system_reminder(recall)
except Exception:
pass
self._memory_recall_consumed = True
if exit_plan_called:
yield TurnComplete(turn=iteration)
yield LoopComplete(total_turns=iteration)
break
if self.hook_engine:
ctx = self._build_hook_context("turn_end")
await self.hook_engine.run_hooks("turn_end", ctx)
for he in self._drain_hook_events():
yield he
yield TurnComplete(turn=iteration)
def _consume_mailbox(self, conversation: ConversationManager) -> None:
if not self.team_name or not self._team_manager:
return
try:
mailbox = self._team_manager.get_mailbox(self.team_name)
if mailbox is None:
return
messages = mailbox.consume(self.agent_id)
for msg in messages:
prefix = f"[Message from {msg.from_agent}]"
if msg.type != "text":
prefix = f"[{msg.type} from {msg.from_agent}]"
content = f"{prefix} {msg.text}"
conversation.add_user_message(content)
except Exception as e:
log.debug("Mailbox consumption failed: %s", e)
def _build_permission_description(self, tc: ToolCallComplete) -> str:
"""为 HITL 权限确认生成人类可读的操作描述。"""
return PermissionChecker.describe_tool_action(tc.tool_name, tc.arguments)
async def _execute_single_tool_direct(
self, tc: ToolCallComplete
) -> _ToolExecResult:
tool = self.registry.get(tc.tool_name)
start = time.monotonic()
if tool is None:
# 工具名不存在只回一条错误结果,让模型自己换个工具重来,不打断循环。
return _ToolExecResult(
tool_id=tc.tool_id,
tool_name=tc.tool_name,
result=ToolResult(
output=f"Error: unknown tool '{tc.tool_name}'", is_error=True
),
elapsed=time.monotonic() - start,
)
if not self.registry.is_enabled(tc.tool_name):
return _ToolExecResult(
tool_id=tc.tool_id,
tool_name=tc.tool_name,
result=ToolResult(
output=f"Error: tool '{tc.tool_name}' is disabled", is_error=True
),
elapsed=time.monotonic() - start,
)
if self.permission_checker:
decision = self.permission_checker.check(tool, tc.arguments)
if decision.effect == "deny":
return _ToolExecResult(
tool_id=tc.tool_id,
tool_name=tc.tool_name,
result=ToolResult(
output=f"Permission denied: {decision.reason}", is_error=True
),
elapsed=time.monotonic() - start,
)
try:
params = tool.params_model.model_validate(tc.arguments)
result = await tool.execute(params)
except ValidationError as e:
result = ToolResult(
output=f"Parameter validation error: {e}", is_error=True
)
except Exception as e:
result = ToolResult(output=f"Tool execution error: {e}", is_error=True)
self._snapshot_for_recovery(tc, result)
return _ToolExecResult(
tool_id=tc.tool_id,
tool_name=tc.tool_name,
result=result,
elapsed=time.monotonic() - start,
)
async def _execute_batch_parallel(
self, calls: list[ToolCallComplete]
) -> list[_ToolExecResult]:
tasks = [self._execute_single_tool_direct(tc) for tc in calls]
return list(await asyncio.gather(*tasks))
async def _execute_tool(
self, tc: ToolCallComplete
) -> AsyncIterator[tuple[ToolResult, float]]:
tool = self.registry.get(tc.tool_name)
start = time.monotonic()
if tool is None:
# 工具名不存在只回一条错误结果,让模型自己换个工具重来,不打断循环。
result = ToolResult(
output=f"Error: unknown tool '{tc.tool_name}'", is_error=True
)
elapsed = time.monotonic() - start
yield result, elapsed
return