-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2197 lines (1929 loc) · 81.2 KB
/
Copy pathapp.py
File metadata and controls
2197 lines (1929 loc) · 81.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 os
import random
import re
import time as _time
from pathlib import Path
from typing import Any
from rich.markup import escape
from rich.text import Text as RichText
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical, VerticalScroll
from textual.message import Message as TMessage
from textual.theme import Theme
from textual.widgets import Markdown, OptionList, Static, TextArea
from textual.widgets.option_list import Option
from kkcode import crashlog
from kkcode.agent import (
Agent,
CompactNotification,
ErrorEvent,
HookEvent,
LoopComplete,
PermissionRequest,
RetryEvent,
StreamText,
ThinkingText,
ToolResultEvent,
ToolUseEvent,
TurnComplete,
UsageEvent,
)
from kkcode.agents.loader import AgentLoader
from kkcode.agents.notification import inject_task_notifications
from kkcode.agents.task_manager import TaskManager
from kkcode.agents.trace import TraceManager
from kkcode.client import (
AuthenticationError,
LLMClient,
LLMError,
create_client,
resolve_context_window,
)
from kkcode.commands import (
CommandContext,
CommandRegistry,
complete,
parse_command,
)
from kkcode.commands.completion import CompletionPopup
from kkcode.commands.handlers import register_all_commands
from kkcode.commands.handlers.skill_register import register_skill_commands
from kkcode.commands.handlers.tasks import create_tasks_command
from kkcode.commands.handlers.worktree import create_worktree_command
from kkcode.config import MCPServerConfig, ProviderConfig
from kkcode.conversation import ConversationManager, Message
from kkcode.hooks import HookContext, HookEngine
from kkcode.mcp import ConnectResult, MCPManager
from kkcode.mcp.tool_wrapper import mcp_tool_name_prefix
from kkcode.memory import (
MemoryManager,
Session,
SessionManager,
find_relevant_memories,
generate_session_summary,
load_instructions,
make_compact_boundary,
render_reminder,
)
from kkcode.permissions import (
DangerousCommandDetector,
PathSandbox,
PermissionChecker,
PermissionMode,
RuleEngine,
)
from kkcode.skills.executor import SkillExecutor
from kkcode.skills.loader import SkillLoader
from kkcode.teammate_tree import TeammateTree
from kkcode.tools import ToolRegistry, create_default_registry
from kkcode.tools.agent_tool import AgentTool
from kkcode.tools.ask_user import AskUserEvent, AskUserTool
from kkcode.tools.impl.tool_search import ToolSearchTool
from kkcode.tools.install_skill import InstallSkillTool
from kkcode.tools.load_skill import LoadSkill
from kkcode.tools.mcp_call import McpCallTool
from kkcode.worktree.cleanup import start_stale_cleanup_task
from kkcode.worktree.manager import WorktreeManager
MAX_TRUNCATED_LINES = 20
MAX_AT_REF_BYTES = 10240
_AT_REF_RE = re.compile(r"@([\w./_\-]+(?:\.[\w]+)*)")
_SKIP_DIRS = {
".git",
"node_modules",
".venv",
"__pycache__",
".kkcode",
"build",
".gradle",
}
def scan_files_for_at(prefix: str, work_dir: str, limit: int = 10) -> list[str]:
matches: list[str] = []
base = (
os.path.join(work_dir, os.path.dirname(prefix)) if "/" in prefix else work_dir
)
name_prefix = os.path.basename(prefix).lower()
if not os.path.isdir(base):
return matches
try:
for entry in sorted(os.listdir(base)):
if entry in _SKIP_DIRS or entry.startswith("."):
continue
if entry.lower().startswith(name_prefix):
rel = (
os.path.join(os.path.dirname(prefix), entry)
if "/" in prefix
else entry
)
if os.path.isdir(os.path.join(base, entry)):
rel += "/"
matches.append(rel)
if len(matches) >= limit:
break
except OSError:
pass
return matches
def expand_at_refs(text: str, work_dir: str) -> str:
def _replace(m: re.Match) -> str:
rel_path = m.group(1)
full_path = os.path.join(work_dir, rel_path)
if not os.path.isfile(full_path):
return m.group(0)
try:
content = open(full_path, encoding="utf-8", errors="replace").read(
MAX_AT_REF_BYTES
)
return f"[File: {rel_path}]\n```\n{content}\n```"
except Exception:
return m.group(0)
return _AT_REF_RE.sub(_replace, text)
class ChatInput(TextArea):
BINDINGS = [
Binding("enter", "submit", "Submit", priority=True),
Binding("shift+enter", "newline", "Newline", priority=True),
Binding("ctrl+j", "newline", "Newline", priority=True),
Binding("tab", "complete", "Complete", priority=True),
Binding("escape", "dismiss_popup", "Dismiss", priority=True),
Binding("up", "nav_up", "Navigate up", priority=True),
Binding("down", "nav_down", "Navigate down", priority=True),
]
class Submitted(TMessage):
def __init__(self, text: str) -> None:
super().__init__()
self.text = text
class TabComplete(TMessage):
def __init__(self, text: str) -> None:
super().__init__()
self.text = text
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.cursor_blink = False
self._history: list[str] = []
self._history_index: int = -1
self._history_draft: str = ""
self._history_file: Path | None = None
def load_history(self, work_dir: str) -> None:
self._history_file = Path(work_dir) / ".kkcode" / "history"
if self._history_file.exists():
try:
lines = self._history_file.read_text(encoding="utf-8").splitlines()
self._history = [l for l in lines if l.strip()]
except Exception:
pass
def _persist_entry(self, text: str) -> None:
if self._history_file is None:
return
try:
self._history_file.parent.mkdir(parents=True, exist_ok=True)
with open(self._history_file, "a", encoding="utf-8") as f:
f.write(text + "\n")
except Exception:
pass
def _popup(self) -> CompletionPopup | None:
try:
return self.app.query_one(CompletionPopup)
except Exception:
return None
def action_submit(self) -> None:
popup = self._popup()
if popup is not None and popup.is_visible:
selected = popup.get_selected()
popup.hide()
if selected:
self._history.append(selected)
self._persist_entry(selected)
self._history_index = -1
self._history_draft = ""
self.post_message(self.Submitted(selected))
self.clear()
return
text = self.text.strip()
if text:
self._history.append(text)
self._persist_entry(text)
self._history_index = -1
self._history_draft = ""
self.post_message(self.Submitted(text))
self.clear()
def action_newline(self) -> None:
self.insert("\n")
def action_complete(self) -> None:
popup = self._popup()
if popup is not None and popup.is_visible:
selected = popup.get_selected()
if selected:
popup.hide()
self.clear()
self.insert(selected + " ")
return
text = self.text.strip()
if text.startswith("/"):
self.post_message(self.TabComplete(text))
else:
self.insert("\t")
def action_dismiss_popup(self) -> None:
popup = self._popup()
if popup is not None:
popup.hide()
def action_nav_up(self) -> None:
popup = self._popup()
if popup is not None and popup.is_visible:
popup.move_up()
return
if not self._history:
return
if self._history_index == -1:
self._history_draft = self.text
self._history_index = len(self._history) - 1
elif self._history_index > 0:
self._history_index -= 1
else:
return
self.clear()
self.insert(self._history[self._history_index])
def action_nav_down(self) -> None:
popup = self._popup()
if popup is not None and popup.is_visible:
popup.move_down()
return
if self._history_index == -1:
return
if self._history_index < len(self._history) - 1:
self._history_index += 1
self.clear()
self.insert(self._history[self._history_index])
else:
self._history_index = -1
self.clear()
self.insert(self._history_draft)
class AtFileRequest(TMessage):
def __init__(self, prefix: str) -> None:
super().__init__()
self.prefix = prefix
class SlashMenuUpdate(TMessage):
def __init__(self, prefix: str | None) -> None:
super().__init__()
self.prefix = prefix
def on_text_area_changed(self, event: TextArea.Changed) -> None:
text = self.text
if text.startswith("/") and self._history_index < 0:
prefix = text[1:]
if " " not in prefix and "\n" not in prefix:
self.post_message(self.SlashMenuUpdate(prefix))
else:
self.post_message(self.SlashMenuUpdate(None))
else:
self.post_message(self.SlashMenuUpdate(None))
at_idx = text.rfind("@")
if at_idx < 0:
return
after = text[at_idx + 1 :]
if " " in after or "\n" in after:
return
if after:
self.post_message(self.AtFileRequest(after))
COLLAPSIBLE_TOOLS = {"ReadFile", "Glob", "Grep", "ToolSearch"}
def _is_subagent_tool(tool_name: str) -> bool:
return tool_name == "Agent"
def _tool_title(tool_name: str, arguments: dict[str, Any]) -> str:
if tool_name == "ReadFile":
path = os.path.basename(arguments.get("file_path", ""))
return f"Read {path}" if path else "Read"
if tool_name == "WriteFile":
path = os.path.basename(arguments.get("file_path", ""))
content = arguments.get("content", "")
lines = content.count("\n") + 1 if content else 0
return f"Write {path} ({lines} lines)" if path else "Write"
if tool_name == "EditFile":
path = os.path.basename(arguments.get("file_path", ""))
return f"Edit {path}" if path else "Edit"
if tool_name == "Bash":
cmd = arguments.get("command", "")
short = cmd[:50] + "…" if len(cmd) > 50 else cmd
return f"Bash: {short}" if short else "Bash"
if tool_name == "Glob":
return f"Glob: {arguments.get('pattern', '')}"
if tool_name == "Grep":
return f"Grep: {arguments.get('pattern', '')}"
return tool_name
def _format_detail(tool_name: str, arguments: dict[str, Any], output: str) -> str:
parts: list[str] = []
if tool_name == "Bash":
parts.append(f" IN {arguments.get('command', '')}")
parts.append("")
for line in output.splitlines():
parts.append(f" OUT {line}")
elif tool_name == "EditFile":
# EditFile 的 output 是 build_diff() 生成的带行号 diff 文本:
# "+ " 开头绿色、"- " 开头红色,其余(上下文行/摘要行)走 dim。
# 转义 Rich markup 特殊字符,避免代码里的方括号被当成标签解析。
for line in output.splitlines()[:MAX_TRUNCATED_LINES]:
escaped = escape(line)
if line.startswith("+ "):
parts.append(f" [green]{escaped}[/]")
elif line.startswith("- "):
parts.append(f" [red]{escaped}[/]")
else:
parts.append(f" [dim]{escaped}[/]")
total = output.count("\n") + 1
if total > MAX_TRUNCATED_LINES:
parts.append(f" [dim]… ({total - MAX_TRUNCATED_LINES} more lines)[/]")
elif tool_name in ("ReadFile", "WriteFile"):
parts.append(f" {arguments.get('file_path', '')}")
parts.append("")
for line in output.splitlines()[:MAX_TRUNCATED_LINES]:
parts.append(f" {line}")
total = output.count("\n") + 1
if total > MAX_TRUNCATED_LINES:
parts.append(f" … ({total - MAX_TRUNCATED_LINES} more lines)")
else:
for line in output.splitlines()[:MAX_TRUNCATED_LINES]:
parts.append(f" {line}")
total = output.count("\n") + 1
if total > MAX_TRUNCATED_LINES:
parts.append(f" … ({total - MAX_TRUNCATED_LINES} more lines)")
return "\n".join(parts)
class ToolCallBlock(Static, can_focus=True):
def __init__(
self, tool_name: str, arguments: dict[str, Any], **kwargs: Any
) -> None:
super().__init__(**kwargs)
self.tool_name = tool_name
self._arguments = arguments
self._title = _tool_title(tool_name, arguments)
self._full_output = ""
self._is_error = False
self._elapsed = 0.0
self._collapsed = True
self._loading = True
self._render_loading()
def _render_loading(self) -> None:
self.update(f" ● {self._title} …")
self.add_class("tool-block-loading")
def set_result(self, output: str, is_error: bool, elapsed: float) -> None:
self._full_output = output
self._is_error = is_error
self._elapsed = elapsed
self._loading = False
self.remove_class("tool-block-loading")
if is_error:
self.add_class("tool-block-error")
# EditFile 的 diff 是最高频需要的信息,默认直接展开,不用等用户点
# 或按 ctrl+o;其余工具仍然默认折叠,避免刷屏。
if self.tool_name == "EditFile" and not is_error:
self._collapsed = False
self._render_expanded()
else:
self._collapsed = True
self._render_collapsed()
def _render_collapsed(self) -> None:
if self._is_error:
self.update(f" ✗ {self._title} ({self._elapsed:.1f}s)")
else:
self.update(f" ✓ {self._title} ({self._elapsed:.1f}s)")
def _render_expanded(self) -> None:
if self._is_error:
header = f" ✗ {self._title} ({self._elapsed:.1f}s)"
else:
header = f" ✓ {self._title} ({self._elapsed:.1f}s)"
detail = _format_detail(self.tool_name, self._arguments, self._full_output)
self.update(f"{header}\n{detail}")
def on_click(self) -> None:
if self._loading:
return
self._collapsed = not self._collapsed
if self._collapsed:
self._render_collapsed()
else:
self._render_expanded()
_MODE_CYCLE = [
PermissionMode.DEFAULT,
PermissionMode.ACCEPT_EDITS,
PermissionMode.PLAN,
PermissionMode.BYPASS,
]
_MODE_COLORS = {
PermissionMode.DEFAULT: "dim",
PermissionMode.ACCEPT_EDITS: "green",
PermissionMode.PLAN: "yellow",
PermissionMode.BYPASS: "red",
}
SPINNER_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
def _to_past_tense(verb: str) -> str:
"""把现在进行时动词转换为过去式。"""
if verb.endswith("ing"):
stem = verb[:-3]
if stem.endswith("e"):
return stem + "d"
if stem and stem[-1] in "atutitet":
return stem + "ed"
return stem + "ed"
return verb + "ed"
THINKING_VERBS = [
"Accomplishing",
"Architecting",
"Baking",
"Beboppin'",
"Befuddling",
"Bloviating",
"Boogieing",
"Boondoggling",
"Bootstrapping",
"Brewing",
"Calculating",
"Canoodling",
"Caramelizing",
"Cascading",
"Cerebrating",
"Choreographing",
"Churning",
"Coalescing",
"Cogitating",
"Combobulating",
"Composing",
"Computing",
"Concocting",
"Considering",
"Contemplating",
"Cooking",
"Crafting",
"Creating",
"Crunching",
"Crystallizing",
"Cultivating",
"Deciphering",
"Deliberating",
"Dilly-dallying",
"Discombobulating",
"Doodling",
"Elucidating",
"Enchanting",
"Envisioning",
"Fermenting",
"Finagling",
"Flambéing",
"Flibbertigibbeting",
"Flummoxing",
"Forging",
"Frolicking",
"Gallivanting",
"Garnishing",
"Generating",
"Germinating",
"Grooving",
"Harmonizing",
"Hatching",
"Honking",
"Hullaballooing",
"Ideating",
"Imagining",
"Improvising",
"Incubating",
"Inferring",
"Infusing",
"Kneading",
"Lollygagging",
"Manifesting",
"Marinating",
"Meandering",
"Metamorphosing",
"Mewing",
"Moonwalking",
"Moseying",
"Mulling",
"Musing",
"Noodling",
"Orbiting",
"Orchestrating",
"Percolating",
"Philosophising",
"Pondering",
"Pontificating",
"Pouncing",
"Purring",
"Puzzling",
"Razzle-dazzling",
"Ruminating",
"Scampering",
"Simmering",
"Sketching",
"Spelunking",
"Spinning",
"Sprouting",
"Synthesizing",
"Thinking",
"Tinkering",
"Transfiguring",
"Transmuting",
"Undulating",
"Unfurling",
"Unravelling",
"Vibing",
"Wandering",
"Whisking",
"Working",
"Wrangling",
"Zigzagging",
] # 共 105 个 TUI 快捷键动词
class ToolGroupSummary(Static, can_focus=True):
def __init__(self, count: int, total_elapsed: float, **kwargs: Any) -> None:
label = f"● Done ({count} tool uses · {total_elapsed:.1f}s) (ctrl+o to expand)"
super().__init__(label, **kwargs)
self._count = count
self._total = total_elapsed
self._expanded = False
def _refresh_display(self) -> None:
if self._expanded:
self.update(f"▼ Done ({self._count} tool uses · {self._total:.1f}s)")
else:
self.update(
f"● Done ({self._count} tool uses · {self._total:.1f}s)"
" (ctrl+o to expand)"
)
def toggle(self) -> None:
self._expanded = not self._expanded
self._refresh_display()
def on_click(self) -> None:
self.toggle()
class SubAgentBlock(Static, can_focus=True):
def __init__(self, agent_type: str, description: str, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._agent_type = agent_type or "agent"
self._description = description[:60] if description else ""
self._done = False
self._is_error = False
self._elapsed = 0.0
self._collapsed = True
self._result_preview = ""
self._tool_count = 0
self._render_running()
def _render_running(self) -> None:
desc = f"({self._description})" if self._description else ""
self.update(f"● {self._agent_type}{desc}\n Running…")
def set_result(self, output: str, is_error: bool, elapsed: float) -> None:
self._done = True
self._is_error = is_error
self._elapsed = elapsed
self._result_preview = output[:300] if output else ""
self._parse_stats(output)
self._render_done()
def _parse_stats(self, output: str) -> None:
import re
m = re.search(r"(\d+)\s+tool", output[:200])
if m:
self._tool_count = int(m.group(1))
def _render_done(self) -> None:
desc = f"({self._description})" if self._description else ""
tool_info = f"{self._tool_count} tool uses · " if self._tool_count else ""
if self._collapsed:
self.update(
f"● {self._agent_type}{desc}\n"
f" ⎿ Done ({tool_info}{self._elapsed:.1f}s) (ctrl+o to expand)"
)
else:
self.update(
f"● {self._agent_type}{desc}\n"
f" ⎿ Done ({tool_info}{self._elapsed:.1f}s)\n"
f" {self._result_preview}"
)
def on_click(self) -> None:
if not self._done:
return
self._collapsed = not self._collapsed
self._render_done()
_KKCODE_THEME = Theme(
name="kkcode",
primary="#875FFF",
background="#1a1a1a",
surface="#1a1a1a",
panel="#1a1a1a",
dark=True,
)
class KKCodeApp(App):
CSS_PATH = "styles.tcss"
TITLE = "KKCode"
INLINE_PADDING = 0
theme = "kkcode"
BINDINGS = [
Binding("ctrl+c", "handle_ctrl_c", "Quit", priority=True),
Binding("escape", "cancel", "Cancel", priority=True),
Binding("shift+tab", "cycle_mode", "Cycle mode", priority=True),
Binding("ctrl+o", "toggle_tool_blocks", "Toggle tools", priority=True),
]
def __init__(
self,
providers: list[ProviderConfig],
permission_mode: PermissionMode = PermissionMode.DEFAULT,
mcp_servers: list[MCPServerConfig] | None = None,
hook_engine: HookEngine | None = None,
enable_fork: bool = True,
enable_verification_agent: bool = False,
worktree_config: Any = None,
teammate_mode: str = "",
enable_coordinator_mode: bool = False,
driver_class: type | None = None,
sandbox_config: Any = None,
) -> None:
super().__init__(driver_class=driver_class)
self.providers = providers
self._initial_permission_mode = permission_mode
self._mcp_server_configs = mcp_servers or []
self.hook_engine = hook_engine
self._enable_fork = enable_fork
self._enable_verification_agent = enable_verification_agent
self._worktree_config = worktree_config
self._teammate_mode = teammate_mode
self._enable_coordinator_mode = enable_coordinator_mode
from kkcode.config import SandboxAppConfig
self._sandbox_cfg: SandboxAppConfig = sandbox_config or SandboxAppConfig()
self.client: LLMClient | None = None
self.conversation = ConversationManager()
self.registry: ToolRegistry = create_default_registry()
self.agent: Agent | None = None
self.mcp_manager: MCPManager | None = None
self._mcp_init_task: asyncio.Task[None] | None = None
self._selected_provider: ProviderConfig | None = None
self._streaming = False
self._thinking_start: float = 0.0
self._thinking_verb: str = ""
self._spinner_idx: int = 0
self._spinner_timer = None
self._spinner_label: Static | None = None
self._mcp_server_info: str = ""
self._agent_task: asyncio.Task[None] | None = None
self._subagent_task: asyncio.Task[None] | None = None
self._subagent_start_time: float | None = None
self.session_manager: SessionManager | None = None
self.session: Session | None = None
self.memory_manager: MemoryManager | None = None
self._instructions_content: str = ""
self.command_registry = CommandRegistry()
register_all_commands(self.command_registry)
self.skill_loader: SkillLoader | None = None
self.skill_executor: SkillExecutor | None = None
self._load_skill_tool: LoadSkill | None = None
self.agent_loader: AgentLoader | None = None
self.task_manager: TaskManager = TaskManager()
self.trace_manager: TraceManager = TraceManager()
self._notification_check_task: asyncio.Task[None] | None = None
self.worktree_manager: WorktreeManager | None = None
self._stale_cleanup_task: asyncio.Task[None] | None = None
self._current_streaming_label: Static | None = None
self._current_ai_row: Vertical | None = None
self._current_accumulated_text: str = ""
self._mcp_instructions: str = ""
self._mcp_instructions_ok: bool = False
self._mcp_connecting: bool = False
self._teammate_tree: TeammateTree | None = None
self._teammate_timer = None
# 记录本次会话是否曾退出过 Plan Mode,用于重入时注入提示
self._has_exited_plan_mode: bool = False
@staticmethod
def _make_banner(model: str = "", work_dir: str = "") -> RichText:
t = RichText()
t.append(" /\\_/\\ ", style="bold color(99)")
t.append("KKCode v0.1.0\n", style="color(242)")
t.append("( o.o ) ", style="bold color(99)")
t.append(f"{model}\n" if model else "\n", style="color(242)")
t.append(" > ^ < ", style="bold color(99)")
t.append(work_dir, style="color(242)")
return t
def compose(self) -> ComposeResult:
yield Static(self._make_banner(), id="title-bar")
if len(self.providers) > 1:
with Vertical(id="provider-select"):
yield Static("Select a Provider", id="select-label")
yield OptionList(
*[
Option(f"{p.name} [{p.model}]", id=p.name)
for p in self.providers
],
id="provider-list",
)
yield VerticalScroll(id="chat-area")
with Vertical(id="input-area"):
yield ChatInput(id="chat-input")
with Horizontal(id="status-bar"):
yield Static(" default", id="mode-label")
yield Static("", id="teammates-label")
yield Static("", id="model-label")
yield CompletionPopup()
def _handle_exception(self, error: Exception) -> None:
"""接管 Textual 的未处理异常入口,先把现场落盘再交回框架。
框架拿到未处理异常后会把 traceback 画到终端然后结束应用,终端一关
就什么都不剩了。事件处理器、后台 worker、刷新回调抛出的异常都汇聚
到这里,写进崩溃日志才能在事后定位。
"""
crashlog.record_exception("textual", error)
super()._handle_exception(error)
def on_mount(self) -> None:
self.register_theme(_KKCODE_THEME)
self.theme = "kkcode"
if len(self.providers) == 1:
self._select_provider(self.providers[0])
else:
self.query_one("#chat-area").display = False
self.query_one("#input-area").display = False
def _select_provider(self, provider: ProviderConfig) -> None:
self._selected_provider = provider
try:
self.client = create_client(provider)
except AuthenticationError as e:
self._show_error(str(e))
return
work_dir = os.getcwd()
home = Path.home()
# 根据配置决定是否启用 OS 级沙箱自动放行
sandbox_auto_allow = self._sandbox_cfg.enabled and self._sandbox_cfg.auto_allow
checker = PermissionChecker(
detector=DangerousCommandDetector(),
sandbox=PathSandbox(work_dir),
rule_engine=RuleEngine(
user_rules_path=home / ".kkcode" / "permissions.yaml",
project_rules_path=Path(work_dir) / ".kkcode" / "permissions.yaml",
local_rules_path=Path(work_dir) / ".kkcode" / "permissions.local.yaml",
),
mode=self._initial_permission_mode,
sandbox_enabled=sandbox_auto_allow,
)
# 如果配置启用了沙箱,为 Bash 工具挂载 OS 沙箱
if self._sandbox_cfg.enabled:
from kkcode.sandbox import SandboxConfig, create_sandbox
os_sandbox = create_sandbox()
if os_sandbox and os_sandbox.available():
sandbox_config = SandboxConfig(
allow_write=[work_dir, "/tmp"],
deny_write=[
f"{work_dir}/.kkcode/config.yaml",
f"{work_dir}/.kkcode/permissions.local.yaml",
],
network_enabled=self._sandbox_cfg.network_enabled,
)
bash_tool = self.registry.get("Bash")
if bash_tool:
bash_tool.sandbox = os_sandbox
bash_tool.sandbox_config = sandbox_config
self._instructions_content = load_instructions(work_dir)
self.memory_manager = MemoryManager(work_dir)
self.session_manager = SessionManager(work_dir)
self.session_manager.cleanup()
self.session = self.session_manager.create()
from kkcode.filehistory import FileHistory
self.file_history = FileHistory(work_dir, self.session.session_id)
for tool in self.registry.list_tools():
if hasattr(tool, "file_history"):
tool.file_history = self.file_history
load_skill_tool = LoadSkill()
self.registry.register(load_skill_tool)
self._load_skill_tool = load_skill_tool
install_skill_tool = InstallSkillTool()
self.registry.register(install_skill_tool)
self._install_skill_tool = install_skill_tool
self.registry.register(
ToolSearchTool(self.registry, protocol=provider.protocol)
)
# mcp_call 必须在 MCP 连接之前就注册好。等连上再按加载模式决定注不注册,
# 本身就是一次中途改动 tools[],缓存前缀照样断。
self.registry.register(McpCallTool(self.registry))
self.registry.register(AskUserTool())
from kkcode.tools.exit_plan_mode import ExitPlanModeTool
self._exit_plan_tool = ExitPlanModeTool()
self.registry.register(self._exit_plan_tool)
self.agent = Agent(
client=self.client,
registry=self.registry,
protocol=provider.protocol,
work_dir=work_dir,
permission_checker=checker,
context_window=provider.get_context_window(),
instructions_content=self._instructions_content,
memory_manager=self.memory_manager,
hook_engine=self.hook_engine,
)
self.agent.file_history = self.file_history
self.agent.session_id = self.session.session_id
self._exit_plan_tool._is_plan_mode = lambda: self.agent.plan_mode
self._exit_plan_tool._plan_exists = lambda: self.agent._get_plan_path().exists()
# Layer 2: 在后台异步拉取模型的 context window,不阻塞启动流程。
# agent 已经有一个同步解析的窗口值(来自配置 / 映射表 / 默认值);
# 如果异步拉取成功,就原地升级为更准确的值。
self.run_worker(self._resolve_context_window(provider), exclusive=False)
self.skill_loader = SkillLoader(work_dir)
self.skill_loader.load_all()
load_skill_tool.set_loader(self.skill_loader)
load_skill_tool.set_agent(self.agent)
install_skill_tool.set_loader(self.skill_loader)
self.skill_executor = SkillExecutor(
agent=self.agent,
client=self.client,
protocol=provider.protocol,
)
load_skill_tool.set_executor(self.skill_executor)
catalog = self.skill_loader.get_catalog()
if catalog:
lines = [
"You can use the following Skills:",
"",
]
for name, desc in catalog:
lines.append(f"- {name}: {desc}")
lines.append("")
lines.append(
"If the user's request matches a Skill, call LoadSkill to activate it."
)
self.agent.set_skill_catalog("\n".join(lines))
register_skill_commands(
self.command_registry, self.skill_loader, self.skill_executor
)
# 安装新 skill 后重新注册斜杠命令,让 /<new-skill> 立即可用
def _on_skill_installed(name: str) -> None:
register_skill_commands(
self.command_registry, self.skill_loader, self.skill_executor
)
install_skill_tool.set_on_installed(_on_skill_installed)
# --- Worktree 系统初始化 ---
from kkcode.config import WorktreeConfig
wt_cfg = self._worktree_config or WorktreeConfig()
self.worktree_manager = WorktreeManager(
repo_root=work_dir,
symlink_directories=wt_cfg.symlink_directories,
)
restored = self.worktree_manager.restore_session()
if restored:
self.agent.work_dir = restored.worktree_path
wt_command = create_worktree_command(self.worktree_manager)
self.command_registry.register_sync(wt_command)
from kkcode.tools.enter_worktree import EnterWorktreeTool
from kkcode.tools.exit_worktree import ExitWorktreeTool
self.registry.register(
EnterWorktreeTool(worktree_manager=self.worktree_manager)
)
self.registry.register(ExitWorktreeTool(worktree_manager=self.worktree_manager))
self._stale_cleanup_task = asyncio.create_task(
start_stale_cleanup_task(
self.worktree_manager,
wt_cfg.stale_cleanup_interval,
wt_cfg.stale_cutoff_hours,
)
)
# --- 子 agent 系统初始化 ---
self.agent_loader = AgentLoader(
work_dir, enable_verification=self._enable_verification_agent
)
self.agent_loader.load_all()
# --- Agent 团队系统初始化 ---
from kkcode.teams.manager import TeamManager
from kkcode.tools.team_create import TeamCreateTool
from kkcode.tools.team_delete import TeamDeleteTool
self.team_manager = TeamManager(
worktree_manager=self.worktree_manager, trace_manager=self.trace_manager
)
agent_tool = AgentTool(