klaude-code 1.2.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- klaude_code/__init__.py +0 -0
- klaude_code/cli/__init__.py +1 -0
- klaude_code/cli/main.py +298 -0
- klaude_code/cli/runtime.py +331 -0
- klaude_code/cli/session_cmd.py +80 -0
- klaude_code/command/__init__.py +43 -0
- klaude_code/command/clear_cmd.py +20 -0
- klaude_code/command/command_abc.py +92 -0
- klaude_code/command/diff_cmd.py +138 -0
- klaude_code/command/export_cmd.py +86 -0
- klaude_code/command/help_cmd.py +51 -0
- klaude_code/command/model_cmd.py +43 -0
- klaude_code/command/prompt-dev-docs-update.md +56 -0
- klaude_code/command/prompt-dev-docs.md +46 -0
- klaude_code/command/prompt-init.md +45 -0
- klaude_code/command/prompt_command.py +69 -0
- klaude_code/command/refresh_cmd.py +43 -0
- klaude_code/command/registry.py +110 -0
- klaude_code/command/status_cmd.py +111 -0
- klaude_code/command/terminal_setup_cmd.py +252 -0
- klaude_code/config/__init__.py +11 -0
- klaude_code/config/config.py +177 -0
- klaude_code/config/list_model.py +162 -0
- klaude_code/config/select_model.py +67 -0
- klaude_code/const/__init__.py +133 -0
- klaude_code/core/__init__.py +0 -0
- klaude_code/core/agent.py +165 -0
- klaude_code/core/executor.py +485 -0
- klaude_code/core/manager/__init__.py +19 -0
- klaude_code/core/manager/agent_manager.py +127 -0
- klaude_code/core/manager/llm_clients.py +42 -0
- klaude_code/core/manager/llm_clients_builder.py +49 -0
- klaude_code/core/manager/sub_agent_manager.py +86 -0
- klaude_code/core/prompt.py +89 -0
- klaude_code/core/prompts/prompt-claude-code.md +98 -0
- klaude_code/core/prompts/prompt-codex.md +331 -0
- klaude_code/core/prompts/prompt-gemini.md +43 -0
- klaude_code/core/prompts/prompt-subagent-explore.md +27 -0
- klaude_code/core/prompts/prompt-subagent-oracle.md +23 -0
- klaude_code/core/prompts/prompt-subagent-webfetch.md +46 -0
- klaude_code/core/prompts/prompt-subagent.md +8 -0
- klaude_code/core/reminders.py +445 -0
- klaude_code/core/task.py +237 -0
- klaude_code/core/tool/__init__.py +75 -0
- klaude_code/core/tool/file/__init__.py +0 -0
- klaude_code/core/tool/file/apply_patch.py +492 -0
- klaude_code/core/tool/file/apply_patch_tool.md +1 -0
- klaude_code/core/tool/file/apply_patch_tool.py +204 -0
- klaude_code/core/tool/file/edit_tool.md +9 -0
- klaude_code/core/tool/file/edit_tool.py +274 -0
- klaude_code/core/tool/file/multi_edit_tool.md +42 -0
- klaude_code/core/tool/file/multi_edit_tool.py +199 -0
- klaude_code/core/tool/file/read_tool.md +14 -0
- klaude_code/core/tool/file/read_tool.py +326 -0
- klaude_code/core/tool/file/write_tool.md +8 -0
- klaude_code/core/tool/file/write_tool.py +146 -0
- klaude_code/core/tool/memory/__init__.py +0 -0
- klaude_code/core/tool/memory/memory_tool.md +16 -0
- klaude_code/core/tool/memory/memory_tool.py +462 -0
- klaude_code/core/tool/memory/skill_loader.py +245 -0
- klaude_code/core/tool/memory/skill_tool.md +24 -0
- klaude_code/core/tool/memory/skill_tool.py +97 -0
- klaude_code/core/tool/shell/__init__.py +0 -0
- klaude_code/core/tool/shell/bash_tool.md +43 -0
- klaude_code/core/tool/shell/bash_tool.py +123 -0
- klaude_code/core/tool/shell/command_safety.py +363 -0
- klaude_code/core/tool/sub_agent_tool.py +83 -0
- klaude_code/core/tool/todo/__init__.py +0 -0
- klaude_code/core/tool/todo/todo_write_tool.md +182 -0
- klaude_code/core/tool/todo/todo_write_tool.py +121 -0
- klaude_code/core/tool/todo/update_plan_tool.md +3 -0
- klaude_code/core/tool/todo/update_plan_tool.py +104 -0
- klaude_code/core/tool/tool_abc.py +25 -0
- klaude_code/core/tool/tool_context.py +106 -0
- klaude_code/core/tool/tool_registry.py +78 -0
- klaude_code/core/tool/tool_runner.py +252 -0
- klaude_code/core/tool/truncation.py +170 -0
- klaude_code/core/tool/web/__init__.py +0 -0
- klaude_code/core/tool/web/mermaid_tool.md +21 -0
- klaude_code/core/tool/web/mermaid_tool.py +76 -0
- klaude_code/core/tool/web/web_fetch_tool.md +8 -0
- klaude_code/core/tool/web/web_fetch_tool.py +159 -0
- klaude_code/core/turn.py +220 -0
- klaude_code/llm/__init__.py +21 -0
- klaude_code/llm/anthropic/__init__.py +3 -0
- klaude_code/llm/anthropic/client.py +221 -0
- klaude_code/llm/anthropic/input.py +200 -0
- klaude_code/llm/client.py +49 -0
- klaude_code/llm/input_common.py +239 -0
- klaude_code/llm/openai_compatible/__init__.py +3 -0
- klaude_code/llm/openai_compatible/client.py +211 -0
- klaude_code/llm/openai_compatible/input.py +109 -0
- klaude_code/llm/openai_compatible/tool_call_accumulator.py +80 -0
- klaude_code/llm/openrouter/__init__.py +3 -0
- klaude_code/llm/openrouter/client.py +200 -0
- klaude_code/llm/openrouter/input.py +160 -0
- klaude_code/llm/openrouter/reasoning_handler.py +209 -0
- klaude_code/llm/registry.py +22 -0
- klaude_code/llm/responses/__init__.py +3 -0
- klaude_code/llm/responses/client.py +216 -0
- klaude_code/llm/responses/input.py +167 -0
- klaude_code/llm/usage.py +109 -0
- klaude_code/protocol/__init__.py +4 -0
- klaude_code/protocol/commands.py +21 -0
- klaude_code/protocol/events.py +163 -0
- klaude_code/protocol/llm_param.py +147 -0
- klaude_code/protocol/model.py +287 -0
- klaude_code/protocol/op.py +89 -0
- klaude_code/protocol/op_handler.py +28 -0
- klaude_code/protocol/sub_agent.py +348 -0
- klaude_code/protocol/tools.py +15 -0
- klaude_code/session/__init__.py +4 -0
- klaude_code/session/export.py +624 -0
- klaude_code/session/selector.py +76 -0
- klaude_code/session/session.py +474 -0
- klaude_code/session/templates/export_session.html +1434 -0
- klaude_code/trace/__init__.py +3 -0
- klaude_code/trace/log.py +168 -0
- klaude_code/ui/__init__.py +91 -0
- klaude_code/ui/core/__init__.py +1 -0
- klaude_code/ui/core/display.py +103 -0
- klaude_code/ui/core/input.py +71 -0
- klaude_code/ui/core/stage_manager.py +55 -0
- klaude_code/ui/modes/__init__.py +1 -0
- klaude_code/ui/modes/debug/__init__.py +1 -0
- klaude_code/ui/modes/debug/display.py +36 -0
- klaude_code/ui/modes/exec/__init__.py +1 -0
- klaude_code/ui/modes/exec/display.py +63 -0
- klaude_code/ui/modes/repl/__init__.py +51 -0
- klaude_code/ui/modes/repl/clipboard.py +152 -0
- klaude_code/ui/modes/repl/completers.py +429 -0
- klaude_code/ui/modes/repl/display.py +60 -0
- klaude_code/ui/modes/repl/event_handler.py +375 -0
- klaude_code/ui/modes/repl/input_prompt_toolkit.py +198 -0
- klaude_code/ui/modes/repl/key_bindings.py +170 -0
- klaude_code/ui/modes/repl/renderer.py +281 -0
- klaude_code/ui/renderers/__init__.py +0 -0
- klaude_code/ui/renderers/assistant.py +21 -0
- klaude_code/ui/renderers/common.py +8 -0
- klaude_code/ui/renderers/developer.py +158 -0
- klaude_code/ui/renderers/diffs.py +215 -0
- klaude_code/ui/renderers/errors.py +16 -0
- klaude_code/ui/renderers/metadata.py +190 -0
- klaude_code/ui/renderers/sub_agent.py +71 -0
- klaude_code/ui/renderers/thinking.py +39 -0
- klaude_code/ui/renderers/tools.py +551 -0
- klaude_code/ui/renderers/user_input.py +65 -0
- klaude_code/ui/rich/__init__.py +1 -0
- klaude_code/ui/rich/live.py +65 -0
- klaude_code/ui/rich/markdown.py +308 -0
- klaude_code/ui/rich/quote.py +34 -0
- klaude_code/ui/rich/searchable_text.py +71 -0
- klaude_code/ui/rich/status.py +240 -0
- klaude_code/ui/rich/theme.py +274 -0
- klaude_code/ui/terminal/__init__.py +1 -0
- klaude_code/ui/terminal/color.py +244 -0
- klaude_code/ui/terminal/control.py +147 -0
- klaude_code/ui/terminal/notifier.py +107 -0
- klaude_code/ui/terminal/progress_bar.py +87 -0
- klaude_code/ui/utils/__init__.py +1 -0
- klaude_code/ui/utils/common.py +108 -0
- klaude_code/ui/utils/debouncer.py +42 -0
- klaude_code/version.py +163 -0
- klaude_code-1.2.6.dist-info/METADATA +178 -0
- klaude_code-1.2.6.dist-info/RECORD +167 -0
- klaude_code-1.2.6.dist-info/WHEEL +4 -0
- klaude_code-1.2.6.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import shlex
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SafetyCheckResult:
|
|
7
|
+
"""Result of a safety check with detailed error information."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, is_safe: bool, error_msg: str = ""):
|
|
10
|
+
self.is_safe = is_safe
|
|
11
|
+
self.error_msg = error_msg
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _is_valid_sed_n_arg(s: str | None) -> bool:
|
|
15
|
+
if not s:
|
|
16
|
+
return False
|
|
17
|
+
# Matches: Np or M,Np where M,N are positive integers
|
|
18
|
+
return bool(re.fullmatch(r"\d+(,\d+)?p", s))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _is_safe_awk_program(program: str) -> SafetyCheckResult:
|
|
22
|
+
lowered = program.lower()
|
|
23
|
+
|
|
24
|
+
if "`" in program:
|
|
25
|
+
return SafetyCheckResult(False, "awk: backticks not allowed in program")
|
|
26
|
+
if "$(" in program:
|
|
27
|
+
return SafetyCheckResult(False, "awk: command substitution not allowed in program")
|
|
28
|
+
if "|&" in program:
|
|
29
|
+
return SafetyCheckResult(False, "awk: background pipeline not allowed in program")
|
|
30
|
+
|
|
31
|
+
if "system(" in lowered:
|
|
32
|
+
return SafetyCheckResult(False, "awk: system() call not allowed in program")
|
|
33
|
+
|
|
34
|
+
if re.search(r"(?<![|&>])\bprint\s*\|", program, re.IGNORECASE):
|
|
35
|
+
return SafetyCheckResult(False, "awk: piping output to external command not allowed")
|
|
36
|
+
if re.search(r"\bprintf\s*\|", program, re.IGNORECASE):
|
|
37
|
+
return SafetyCheckResult(False, "awk: piping output to external command not allowed")
|
|
38
|
+
|
|
39
|
+
return SafetyCheckResult(True)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_safe_awk_argv(argv: list[str]) -> SafetyCheckResult:
|
|
43
|
+
if len(argv) < 2:
|
|
44
|
+
return SafetyCheckResult(False, "awk: Missing program")
|
|
45
|
+
|
|
46
|
+
program: str | None = None
|
|
47
|
+
|
|
48
|
+
i = 1
|
|
49
|
+
while i < len(argv):
|
|
50
|
+
arg = argv[i]
|
|
51
|
+
|
|
52
|
+
if arg in {"-f", "--file", "--source"} or arg.startswith("-f"):
|
|
53
|
+
return SafetyCheckResult(False, "awk: -f/--file not allowed")
|
|
54
|
+
|
|
55
|
+
if arg in {"-e", "--exec"}:
|
|
56
|
+
if i + 1 >= len(argv):
|
|
57
|
+
return SafetyCheckResult(False, "awk: Missing program for -e")
|
|
58
|
+
script = argv[i + 1]
|
|
59
|
+
program_check = _is_safe_awk_program(script)
|
|
60
|
+
if not program_check.is_safe:
|
|
61
|
+
return program_check
|
|
62
|
+
if program is None:
|
|
63
|
+
program = script
|
|
64
|
+
i += 2
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
if arg.startswith("-"):
|
|
68
|
+
i += 1
|
|
69
|
+
continue
|
|
70
|
+
|
|
71
|
+
if program is None:
|
|
72
|
+
program_check = _is_safe_awk_program(arg)
|
|
73
|
+
if not program_check.is_safe:
|
|
74
|
+
return program_check
|
|
75
|
+
program = arg
|
|
76
|
+
i += 1
|
|
77
|
+
|
|
78
|
+
if program is None:
|
|
79
|
+
return SafetyCheckResult(False, "awk: Missing program")
|
|
80
|
+
|
|
81
|
+
return SafetyCheckResult(True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _is_safe_rm_argv(argv: list[str]) -> SafetyCheckResult:
|
|
85
|
+
"""Check safety of rm command arguments."""
|
|
86
|
+
# Enforce strict safety rules for rm operands
|
|
87
|
+
# - Forbid absolute paths, tildes, wildcards (*?[), and trailing '/'
|
|
88
|
+
# - Resolve each operand with realpath and ensure it stays under CWD
|
|
89
|
+
# - If -r/-R/-rf/-fr present: only allow relative paths whose targets
|
|
90
|
+
# exist and are not symbolic links
|
|
91
|
+
|
|
92
|
+
cwd = os.getcwd()
|
|
93
|
+
workspace_root = os.path.realpath(cwd)
|
|
94
|
+
|
|
95
|
+
recursive = False
|
|
96
|
+
end_of_opts = False
|
|
97
|
+
operands: list[str] = []
|
|
98
|
+
|
|
99
|
+
for arg in argv[1:]:
|
|
100
|
+
if not end_of_opts and arg == "--":
|
|
101
|
+
end_of_opts = True
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
if not end_of_opts and arg.startswith("-") and arg != "-":
|
|
105
|
+
# Parse short or long options
|
|
106
|
+
if arg.startswith("--"):
|
|
107
|
+
# Recognize common long options
|
|
108
|
+
if arg == "--recursive":
|
|
109
|
+
recursive = True
|
|
110
|
+
# Other long options are ignored for safety purposes
|
|
111
|
+
continue
|
|
112
|
+
# Combined short options like -rf
|
|
113
|
+
for ch in arg[1:]:
|
|
114
|
+
if ch in ("r", "R"):
|
|
115
|
+
recursive = True
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# Operand (path)
|
|
119
|
+
operands.append(arg)
|
|
120
|
+
|
|
121
|
+
# Reject dangerous operand patterns
|
|
122
|
+
wildcard_chars = {"*", "?", "["}
|
|
123
|
+
|
|
124
|
+
for op in operands:
|
|
125
|
+
# Disallow absolute paths
|
|
126
|
+
if os.path.isabs(op):
|
|
127
|
+
return SafetyCheckResult(False, f"rm: Absolute path not allowed: '{op}'")
|
|
128
|
+
# Disallow tildes
|
|
129
|
+
if op.startswith("~") or "/~/" in op or "~/" in op:
|
|
130
|
+
return SafetyCheckResult(False, f"rm: Tilde expansion not allowed: '{op}'")
|
|
131
|
+
# Disallow wildcards
|
|
132
|
+
if any(c in op for c in wildcard_chars):
|
|
133
|
+
return SafetyCheckResult(False, f"rm: Wildcards not allowed: '{op}'")
|
|
134
|
+
# Disallow trailing slash (avoid whole-dir deletes)
|
|
135
|
+
if op.endswith("/"):
|
|
136
|
+
return SafetyCheckResult(False, f"rm: Trailing slash not allowed: '{op}'")
|
|
137
|
+
|
|
138
|
+
# Resolve and ensure stays within workspace_root
|
|
139
|
+
op_abs = os.path.realpath(os.path.join(cwd, op))
|
|
140
|
+
try:
|
|
141
|
+
if os.path.commonpath([op_abs, workspace_root]) != workspace_root:
|
|
142
|
+
return SafetyCheckResult(False, f"rm: Path escapes workspace: '{op}' -> '{op_abs}'")
|
|
143
|
+
except Exception as e:
|
|
144
|
+
# Different drives or resolution errors
|
|
145
|
+
return SafetyCheckResult(False, f"rm: Path resolution failed for '{op}': {e}")
|
|
146
|
+
|
|
147
|
+
if recursive:
|
|
148
|
+
# For recursive deletion, require operand exists and is not a symlink
|
|
149
|
+
op_lpath = os.path.join(cwd, op)
|
|
150
|
+
if not os.path.exists(op_lpath):
|
|
151
|
+
return SafetyCheckResult(False, f"rm -r: Target does not exist: '{op}'")
|
|
152
|
+
if os.path.islink(op_lpath):
|
|
153
|
+
return SafetyCheckResult(False, f"rm -r: Cannot delete symlink recursively: '{op}'")
|
|
154
|
+
|
|
155
|
+
# If no operands provided, allow (harmless, will fail at runtime)
|
|
156
|
+
return SafetyCheckResult(True)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _is_safe_trash_argv(argv: list[str]) -> SafetyCheckResult:
|
|
160
|
+
"""Check safety of trash command arguments."""
|
|
161
|
+
# Apply similar safety rules as rm but slightly more permissive
|
|
162
|
+
# - Forbid absolute paths, tildes, wildcards (*?[), and trailing '/'
|
|
163
|
+
# - Resolve each operand with realpath and ensure it stays under CWD
|
|
164
|
+
# - Unlike rm, allow symlinks since trash is less destructive
|
|
165
|
+
|
|
166
|
+
cwd = os.getcwd()
|
|
167
|
+
workspace_root = os.path.realpath(cwd)
|
|
168
|
+
|
|
169
|
+
end_of_opts = False
|
|
170
|
+
operands: list[str] = []
|
|
171
|
+
|
|
172
|
+
for arg in argv[1:]:
|
|
173
|
+
if not end_of_opts and arg == "--":
|
|
174
|
+
end_of_opts = True
|
|
175
|
+
continue
|
|
176
|
+
|
|
177
|
+
if not end_of_opts and arg.startswith("-") and arg != "-":
|
|
178
|
+
# Skip options for trash command
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
# Operand (path)
|
|
182
|
+
operands.append(arg)
|
|
183
|
+
|
|
184
|
+
# Reject dangerous operand patterns
|
|
185
|
+
wildcard_chars = {"*", "?", "["}
|
|
186
|
+
|
|
187
|
+
for op in operands:
|
|
188
|
+
# Disallow absolute paths
|
|
189
|
+
if os.path.isabs(op):
|
|
190
|
+
return SafetyCheckResult(False, f"trash: Absolute path not allowed: '{op}'")
|
|
191
|
+
# Disallow tildes
|
|
192
|
+
if op.startswith("~") or "/~/" in op or "~/" in op:
|
|
193
|
+
return SafetyCheckResult(False, f"trash: Tilde expansion not allowed: '{op}'")
|
|
194
|
+
# Disallow wildcards
|
|
195
|
+
if any(c in op for c in wildcard_chars):
|
|
196
|
+
return SafetyCheckResult(False, f"trash: Wildcards not allowed: '{op}'")
|
|
197
|
+
# Disallow trailing slash (avoid whole-dir operations)
|
|
198
|
+
if op.endswith("/"):
|
|
199
|
+
return SafetyCheckResult(False, f"trash: Trailing slash not allowed: '{op}'")
|
|
200
|
+
|
|
201
|
+
# Resolve and ensure stays within workspace_root
|
|
202
|
+
op_abs = os.path.realpath(os.path.join(cwd, op))
|
|
203
|
+
try:
|
|
204
|
+
if os.path.commonpath([op_abs, workspace_root]) != workspace_root:
|
|
205
|
+
return SafetyCheckResult(False, f"trash: Path escapes workspace: '{op}' -> '{op_abs}'")
|
|
206
|
+
except Exception as e:
|
|
207
|
+
# Different drives or resolution errors
|
|
208
|
+
return SafetyCheckResult(False, f"trash: Path resolution failed for '{op}': {e}")
|
|
209
|
+
|
|
210
|
+
# If no operands provided, allow (harmless, will fail at runtime)
|
|
211
|
+
return SafetyCheckResult(True)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _is_safe_argv(argv: list[str]) -> SafetyCheckResult:
|
|
215
|
+
if not argv:
|
|
216
|
+
return SafetyCheckResult(False, "Empty command")
|
|
217
|
+
|
|
218
|
+
cmd0 = argv[0]
|
|
219
|
+
|
|
220
|
+
# if _has_shell_redirection(argv):
|
|
221
|
+
# return SafetyCheckResult(False, "Shell redirection and pipelines are not allowed in single commands")
|
|
222
|
+
|
|
223
|
+
# Special handling for rm to prevent dangerous operations
|
|
224
|
+
if cmd0 == "rm":
|
|
225
|
+
return _is_safe_rm_argv(argv)
|
|
226
|
+
|
|
227
|
+
# Special handling for trash to prevent dangerous operations
|
|
228
|
+
if cmd0 == "trash":
|
|
229
|
+
return _is_safe_trash_argv(argv)
|
|
230
|
+
|
|
231
|
+
if cmd0 == "find":
|
|
232
|
+
unsafe_opts = {
|
|
233
|
+
"-exec": "command execution",
|
|
234
|
+
"-execdir": "command execution",
|
|
235
|
+
"-ok": "interactive command execution",
|
|
236
|
+
"-okdir": "interactive command execution",
|
|
237
|
+
"-delete": "file deletion",
|
|
238
|
+
"-fls": "file output",
|
|
239
|
+
"-fprint": "file output",
|
|
240
|
+
"-fprint0": "file output",
|
|
241
|
+
"-fprintf": "formatted file output",
|
|
242
|
+
}
|
|
243
|
+
for arg in argv[1:]:
|
|
244
|
+
if arg in unsafe_opts:
|
|
245
|
+
return SafetyCheckResult(False, f"find: {unsafe_opts[arg]} option '{arg}' not allowed")
|
|
246
|
+
return SafetyCheckResult(True)
|
|
247
|
+
|
|
248
|
+
if cmd0 == "git":
|
|
249
|
+
sub = argv[1] if len(argv) > 1 else None
|
|
250
|
+
if not sub:
|
|
251
|
+
return SafetyCheckResult(False, "git: Missing subcommand")
|
|
252
|
+
|
|
253
|
+
# Allow most local git operations, but block remote operations
|
|
254
|
+
allowed_git_cmds = {
|
|
255
|
+
"add",
|
|
256
|
+
"branch",
|
|
257
|
+
"checkout",
|
|
258
|
+
"commit",
|
|
259
|
+
"config",
|
|
260
|
+
"diff",
|
|
261
|
+
"fetch",
|
|
262
|
+
"init",
|
|
263
|
+
"log",
|
|
264
|
+
"merge",
|
|
265
|
+
"mv",
|
|
266
|
+
"rebase",
|
|
267
|
+
"reset",
|
|
268
|
+
"restore",
|
|
269
|
+
"revert",
|
|
270
|
+
"rm",
|
|
271
|
+
"show",
|
|
272
|
+
"stash",
|
|
273
|
+
"status",
|
|
274
|
+
"switch",
|
|
275
|
+
"tag",
|
|
276
|
+
"clone",
|
|
277
|
+
"worktree",
|
|
278
|
+
}
|
|
279
|
+
# Block remote operations
|
|
280
|
+
blocked_git_cmds = {"push", "pull", "remote"}
|
|
281
|
+
|
|
282
|
+
if sub in blocked_git_cmds:
|
|
283
|
+
return SafetyCheckResult(False, f"git: Remote operation '{sub}' not allowed")
|
|
284
|
+
if sub not in allowed_git_cmds:
|
|
285
|
+
return SafetyCheckResult(False, f"git: Subcommand '{sub}' not in allow list")
|
|
286
|
+
return SafetyCheckResult(True)
|
|
287
|
+
|
|
288
|
+
# Build tools and linters - allow all subcommands
|
|
289
|
+
if cmd0 in {
|
|
290
|
+
"cargo",
|
|
291
|
+
"uv",
|
|
292
|
+
"go",
|
|
293
|
+
"ruff",
|
|
294
|
+
"pyright",
|
|
295
|
+
"make",
|
|
296
|
+
"isort",
|
|
297
|
+
"npm",
|
|
298
|
+
"pnpm",
|
|
299
|
+
"bun",
|
|
300
|
+
}:
|
|
301
|
+
return SafetyCheckResult(True)
|
|
302
|
+
|
|
303
|
+
if cmd0 == "sed":
|
|
304
|
+
# Allow sed -n patterns (line printing)
|
|
305
|
+
if len(argv) >= 3 and argv[1] == "-n" and _is_valid_sed_n_arg(argv[2]):
|
|
306
|
+
return SafetyCheckResult(True)
|
|
307
|
+
# Allow simple text replacement: sed 's/old/new/g' file
|
|
308
|
+
# or sed -i 's/old/new/g' file for in-place editing
|
|
309
|
+
if len(argv) >= 3:
|
|
310
|
+
# Find the sed script argument (usually starts with 's/')
|
|
311
|
+
for arg in argv[1:]:
|
|
312
|
+
if arg.startswith("s/") or arg.startswith("s|"):
|
|
313
|
+
# Basic safety check: no command execution in replacement
|
|
314
|
+
if ";" in arg:
|
|
315
|
+
return SafetyCheckResult(False, f"sed: Command separator ';' not allowed in '{arg}'")
|
|
316
|
+
if "`" in arg:
|
|
317
|
+
return SafetyCheckResult(False, f"sed: Backticks not allowed in '{arg}'")
|
|
318
|
+
if "$(" in arg:
|
|
319
|
+
return SafetyCheckResult(False, f"sed: Command substitution not allowed in '{arg}'")
|
|
320
|
+
return SafetyCheckResult(True)
|
|
321
|
+
return SafetyCheckResult(
|
|
322
|
+
False,
|
|
323
|
+
"sed: Only text replacement (s/old/new/) or line printing (-n 'Np') is allowed",
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
if cmd0 == "awk":
|
|
327
|
+
return _is_safe_awk_argv(argv)
|
|
328
|
+
|
|
329
|
+
# Default allow when command is not explicitly restricted
|
|
330
|
+
return SafetyCheckResult(True)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def is_safe_command(command: str) -> SafetyCheckResult:
|
|
334
|
+
"""Determine if a command is safe enough to run.
|
|
335
|
+
|
|
336
|
+
The check is intentionally lightweight: it blocks only a small set of
|
|
337
|
+
obviously dangerous patterns (rm/trash/git remotes, unsafe sed/awk,
|
|
338
|
+
find -exec/-delete, etc.) and otherwise lets the real shell surface
|
|
339
|
+
syntax errors (for example, unmatched quotes in complex multiline
|
|
340
|
+
scripts).
|
|
341
|
+
"""
|
|
342
|
+
|
|
343
|
+
# Try to parse into an argv-style list first. If this fails (e.g. due
|
|
344
|
+
# to unterminated quotes in a complex heredoc), treat the command as
|
|
345
|
+
# safe here and let bash itself perform syntax checking instead of
|
|
346
|
+
# blocking execution pre-emptively.
|
|
347
|
+
try:
|
|
348
|
+
argv = shlex.split(command, posix=True)
|
|
349
|
+
except ValueError:
|
|
350
|
+
# If we cannot reliably parse the command (e.g. due to unterminated
|
|
351
|
+
# quotes in a complex heredoc), treat it as safe here and let the
|
|
352
|
+
# real shell surface any syntax errors instead of blocking execution
|
|
353
|
+
# pre-emptively.
|
|
354
|
+
return SafetyCheckResult(True)
|
|
355
|
+
|
|
356
|
+
# All further safety checks are done directly on the parsed argv via
|
|
357
|
+
# _is_safe_argv. We intentionally avoid trying to re-interpret complex
|
|
358
|
+
# shell sequences here and rely on the real shell to handle syntax.
|
|
359
|
+
|
|
360
|
+
if not argv:
|
|
361
|
+
return SafetyCheckResult(False, "Empty command")
|
|
362
|
+
|
|
363
|
+
return _is_safe_argv(argv)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Generic sub-agent tool implementation.
|
|
2
|
+
|
|
3
|
+
This module provides a single tool class that can handle all sub-agent invocations
|
|
4
|
+
based on their SubAgentProfile configuration.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
from typing import TYPE_CHECKING, ClassVar
|
|
12
|
+
|
|
13
|
+
from klaude_code.core.tool.tool_abc import ToolABC
|
|
14
|
+
from klaude_code.core.tool.tool_context import current_run_subtask_callback
|
|
15
|
+
from klaude_code.protocol import llm_param, model
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from klaude_code.protocol.sub_agent import SubAgentProfile
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SubAgentTool(ToolABC):
|
|
22
|
+
"""Generic tool implementation for all sub-agents.
|
|
23
|
+
|
|
24
|
+
Each sub-agent type gets its own dynamically generated subclass with the
|
|
25
|
+
appropriate profile attached as a class variable.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
_profile: ClassVar[SubAgentProfile]
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def for_profile(cls, profile: SubAgentProfile) -> type[SubAgentTool]:
|
|
32
|
+
"""Create a tool class for a specific sub-agent profile."""
|
|
33
|
+
return type(
|
|
34
|
+
f"{profile.name}Tool",
|
|
35
|
+
(SubAgentTool,),
|
|
36
|
+
{"_profile": profile},
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def schema(cls) -> llm_param.ToolSchema:
|
|
41
|
+
profile = cls._profile
|
|
42
|
+
return llm_param.ToolSchema(
|
|
43
|
+
name=profile.name,
|
|
44
|
+
type="function",
|
|
45
|
+
description=profile.description,
|
|
46
|
+
parameters=profile.parameters,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
async def call(cls, arguments: str) -> model.ToolResultItem:
|
|
51
|
+
profile = cls._profile
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
args = json.loads(arguments)
|
|
55
|
+
except json.JSONDecodeError as e:
|
|
56
|
+
return model.ToolResultItem(status="error", output=f"Invalid JSON arguments: {e}")
|
|
57
|
+
|
|
58
|
+
runner = current_run_subtask_callback.get()
|
|
59
|
+
if runner is None:
|
|
60
|
+
return model.ToolResultItem(status="error", output="No subtask runner available in this context")
|
|
61
|
+
|
|
62
|
+
# Build the prompt using the profile's prompt builder
|
|
63
|
+
prompt = profile.prompt_builder(args)
|
|
64
|
+
description = args.get("description", "")
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
result = await runner(
|
|
68
|
+
model.SubAgentState(
|
|
69
|
+
sub_agent_type=profile.name,
|
|
70
|
+
sub_agent_desc=description,
|
|
71
|
+
sub_agent_prompt=prompt,
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
except asyncio.CancelledError:
|
|
75
|
+
raise
|
|
76
|
+
except Exception as e:
|
|
77
|
+
return model.ToolResultItem(status="error", output=f"Failed to run subtask: {e}")
|
|
78
|
+
|
|
79
|
+
return model.ToolResultItem(
|
|
80
|
+
status="success" if not result.error else "error",
|
|
81
|
+
output=result.task_result or "",
|
|
82
|
+
ui_extra=model.ToolResultUIExtra(type=model.ToolResultUIExtraType.SESSION_ID, session_id=result.session_id),
|
|
83
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
2
|
+
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
3
|
+
|
|
4
|
+
#### When to Use This Tool
|
|
5
|
+
Use this tool proactively in these scenarios:
|
|
6
|
+
|
|
7
|
+
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
|
8
|
+
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
|
9
|
+
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
|
10
|
+
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
|
11
|
+
5. After receiving new instructions - Immediately capture user requirements as todos
|
|
12
|
+
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
|
|
13
|
+
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
|
|
14
|
+
|
|
15
|
+
#### When NOT to Use This Tool
|
|
16
|
+
|
|
17
|
+
Skip using this tool when:
|
|
18
|
+
1. There is only a single, straightforward task
|
|
19
|
+
2. The task is trivial and tracking it provides no organizational benefit
|
|
20
|
+
3. The task can be completed in less than 3 trivial steps
|
|
21
|
+
4. The task is purely conversational or informational
|
|
22
|
+
|
|
23
|
+
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
|
24
|
+
|
|
25
|
+
#### Examples of When to Use the Todo List
|
|
26
|
+
|
|
27
|
+
<example>
|
|
28
|
+
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
|
|
29
|
+
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
|
|
30
|
+
*Creates todo list with the following items:*
|
|
31
|
+
1. Creating dark mode toggle component in Settings page
|
|
32
|
+
2. Adding dark mode state management (context/store)
|
|
33
|
+
3. Implementing CSS-in-JS styles for dark theme
|
|
34
|
+
4. Updating existing components to support theme switching
|
|
35
|
+
5. Running tests and build process, addressing any failures or errors that occur
|
|
36
|
+
*Begins working on the first task*
|
|
37
|
+
|
|
38
|
+
<reasoning>
|
|
39
|
+
The assistant used the todo list because:
|
|
40
|
+
1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
|
|
41
|
+
2. The user explicitly requested tests and build be run afterward
|
|
42
|
+
3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
|
|
43
|
+
</reasoning>
|
|
44
|
+
</example>
|
|
45
|
+
|
|
46
|
+
<example>
|
|
47
|
+
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
|
|
48
|
+
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
|
|
49
|
+
*Uses grep or search tools to locate all instances of getCwd in the codebase*
|
|
50
|
+
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
|
|
51
|
+
*Creates todo list with specific items for each file that needs updating*
|
|
52
|
+
|
|
53
|
+
<reasoning>
|
|
54
|
+
The assistant used the todo list because:
|
|
55
|
+
1. First, the assistant searched to understand the scope of the task
|
|
56
|
+
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
|
|
57
|
+
3. The todo list helps ensure every instance is tracked and updated systematically
|
|
58
|
+
4. This approach prevents missing any occurrences and maintains code consistency
|
|
59
|
+
</reasoning>
|
|
60
|
+
</example>
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
<example>
|
|
64
|
+
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
|
|
65
|
+
Assistant: I'll help implement these features. First, let's add all the features to the todo list.
|
|
66
|
+
*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
|
|
67
|
+
Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
|
|
68
|
+
|
|
69
|
+
<reasoning>
|
|
70
|
+
The assistant used the todo list because:
|
|
71
|
+
1. The user provided multiple complex features to implement in a comma separated list
|
|
72
|
+
2. The todo list helps organize these large features into manageable tasks
|
|
73
|
+
3. This approach allows for tracking progress across the entire implementation
|
|
74
|
+
</reasoning>
|
|
75
|
+
</example>
|
|
76
|
+
|
|
77
|
+
<example>
|
|
78
|
+
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
|
|
79
|
+
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
|
|
80
|
+
*Reviews component structure, render patterns, state management, and data fetching*
|
|
81
|
+
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
|
|
82
|
+
*Creates todo list with items like: 1) Implementing memoization for expensive calculations in ProductList, 2) Adding virtualization for long lists in Dashboard, 3) Optimizing image loading in Gallery component, 4) Fixing state update loops in ShoppingCart, 5) Reviewing bundle size and implementing code splitting*
|
|
83
|
+
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
|
|
84
|
+
|
|
85
|
+
<reasoning>
|
|
86
|
+
The assistant used the todo list because:
|
|
87
|
+
1. First, the assistant examined the codebase to identify specific performance issues
|
|
88
|
+
2. Based on this analysis, it identified multiple optimization opportunities
|
|
89
|
+
3. Performance optimization is a non-trivial task requiring multiple steps
|
|
90
|
+
4. The todo list helps methodically track improvements across different components
|
|
91
|
+
5. This systematic approach ensures all performance bottlenecks are addressed
|
|
92
|
+
</reasoning>
|
|
93
|
+
</example>
|
|
94
|
+
|
|
95
|
+
#### Examples of When NOT to Use the Todo List
|
|
96
|
+
|
|
97
|
+
<example>
|
|
98
|
+
User: How do I print 'Hello World' in Python?
|
|
99
|
+
Assistant: In Python, you can print "Hello World" with this simple code:
|
|
100
|
+
|
|
101
|
+
python
|
|
102
|
+
print("Hello World")
|
|
103
|
+
|
|
104
|
+
This will output the text "Hello World" to the console when executed.</assistant>
|
|
105
|
+
|
|
106
|
+
<reasoning>
|
|
107
|
+
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
|
108
|
+
</reasoning>
|
|
109
|
+
</example>
|
|
110
|
+
|
|
111
|
+
<example>
|
|
112
|
+
User: What does the git status command do?
|
|
113
|
+
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
|
|
114
|
+
|
|
115
|
+
<reasoning>
|
|
116
|
+
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
|
|
117
|
+
</reasoning>
|
|
118
|
+
</example>
|
|
119
|
+
|
|
120
|
+
<example>
|
|
121
|
+
User: Can you add a comment to the calculateTotal function to explain what it does?
|
|
122
|
+
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
|
|
123
|
+
* Uses the Edit tool to add a comment to the calculateTotal function *
|
|
124
|
+
|
|
125
|
+
<reasoning>
|
|
126
|
+
The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
|
|
127
|
+
</reasoning>
|
|
128
|
+
</example>
|
|
129
|
+
|
|
130
|
+
<example>
|
|
131
|
+
User: Run npm install for me and tell me what happens.
|
|
132
|
+
Assistant: I'll run the npm install command for you.
|
|
133
|
+
|
|
134
|
+
*Executes: npm install*
|
|
135
|
+
|
|
136
|
+
The command completed successfully. Here's the output:
|
|
137
|
+
[Output of npm install command]
|
|
138
|
+
|
|
139
|
+
All dependencies have been installed according to your package.json file.
|
|
140
|
+
|
|
141
|
+
<reasoning>
|
|
142
|
+
The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
|
|
143
|
+
</reasoning>
|
|
144
|
+
</example>
|
|
145
|
+
|
|
146
|
+
#### Task States and Management
|
|
147
|
+
|
|
148
|
+
1. **Task States**: Use these states to track progress:
|
|
149
|
+
- pending: Task not yet started
|
|
150
|
+
- in_progress: Currently working on (limit to ONE task at a time)
|
|
151
|
+
- completed: Task finished successfully
|
|
152
|
+
|
|
153
|
+
**IMPORTANT**: Task descriptions must have two forms:
|
|
154
|
+
- content: The imperative form describing what needs to be done (e.g., "Run tests", "Build the project")
|
|
155
|
+
- activeForm: The present continuous form shown during execution (e.g., "Running tests", "Building the project")
|
|
156
|
+
|
|
157
|
+
2. **Task Management**:
|
|
158
|
+
- Update task status in real-time as you work
|
|
159
|
+
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
|
160
|
+
- Exactly ONE task must be in_progress at any time (not less, not more)
|
|
161
|
+
- Complete current tasks before starting new ones
|
|
162
|
+
- Remove tasks that are no longer relevant from the list entirely
|
|
163
|
+
|
|
164
|
+
3. **Task Completion Requirements**:
|
|
165
|
+
- ONLY mark a task as completed when you have FULLY accomplished it
|
|
166
|
+
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
|
167
|
+
- When blocked, create a new task describing what needs to be resolved
|
|
168
|
+
- Never mark a task as completed if:
|
|
169
|
+
- Tests are failing
|
|
170
|
+
- Implementation is partial
|
|
171
|
+
- You encountered unresolved errors
|
|
172
|
+
- You couldn't find necessary files or dependencies
|
|
173
|
+
|
|
174
|
+
4. **Task Breakdown**:
|
|
175
|
+
- Create specific, actionable items
|
|
176
|
+
- Break complex tasks into smaller, manageable steps
|
|
177
|
+
- Use clear, descriptive task names
|
|
178
|
+
- Always provide both forms:
|
|
179
|
+
- content: "Fix authentication bug"
|
|
180
|
+
- activeForm: "Fixing authentication bug"
|
|
181
|
+
|
|
182
|
+
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|