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,127 @@
|
|
|
1
|
+
"""Agent and session manager.
|
|
2
|
+
|
|
3
|
+
This module contains :class:`AgentManager`, a helper responsible for
|
|
4
|
+
creating and tracking agents per session, applying model changes, and
|
|
5
|
+
clearing conversations. It is used by the executor context to keep
|
|
6
|
+
agent-related responsibilities separate from operation dispatch.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
|
|
13
|
+
from klaude_code.config import load_config
|
|
14
|
+
from klaude_code.core.agent import Agent, DefaultModelProfileProvider, ModelProfileProvider
|
|
15
|
+
from klaude_code.core.manager.llm_clients import LLMClients
|
|
16
|
+
from klaude_code.llm.registry import create_llm_client
|
|
17
|
+
from klaude_code.protocol import commands, events, model
|
|
18
|
+
from klaude_code.session.session import Session
|
|
19
|
+
from klaude_code.trace import DebugType, log_debug
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AgentManager:
|
|
23
|
+
"""Manager component that tracks agents and their sessions."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
event_queue: asyncio.Queue[events.Event],
|
|
28
|
+
llm_clients: LLMClients,
|
|
29
|
+
model_profile_provider: ModelProfileProvider | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
self._event_queue: asyncio.Queue[events.Event] = event_queue
|
|
32
|
+
self._llm_clients: LLMClients = llm_clients
|
|
33
|
+
self._model_profile_provider: ModelProfileProvider = model_profile_provider or DefaultModelProfileProvider()
|
|
34
|
+
self._active_agents: dict[str, Agent] = {}
|
|
35
|
+
|
|
36
|
+
async def emit_event(self, event: events.Event) -> None:
|
|
37
|
+
"""Emit an event to the shared event queue."""
|
|
38
|
+
|
|
39
|
+
await self._event_queue.put(event)
|
|
40
|
+
|
|
41
|
+
async def ensure_agent(self, session_id: str) -> Agent:
|
|
42
|
+
"""Return an existing agent for the session or create a new one."""
|
|
43
|
+
|
|
44
|
+
agent = self._active_agents.get(session_id)
|
|
45
|
+
if agent is not None:
|
|
46
|
+
return agent
|
|
47
|
+
|
|
48
|
+
session = Session.load(session_id)
|
|
49
|
+
profile = self._model_profile_provider.build_profile(self._llm_clients.main)
|
|
50
|
+
agent = Agent(session=session, profile=profile)
|
|
51
|
+
|
|
52
|
+
async for evt in agent.replay_history():
|
|
53
|
+
await self.emit_event(evt)
|
|
54
|
+
|
|
55
|
+
await self.emit_event(
|
|
56
|
+
events.WelcomeEvent(
|
|
57
|
+
work_dir=str(session.work_dir),
|
|
58
|
+
llm_config=self._llm_clients.main.get_llm_config(),
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
self._active_agents[session_id] = agent
|
|
63
|
+
log_debug(
|
|
64
|
+
f"Initialized agent for session: {session_id}",
|
|
65
|
+
style="cyan",
|
|
66
|
+
debug_type=DebugType.EXECUTION,
|
|
67
|
+
)
|
|
68
|
+
return agent
|
|
69
|
+
|
|
70
|
+
async def apply_model_change(self, agent: Agent, model_name: str) -> None:
|
|
71
|
+
"""Change the model used by an agent and notify the UI."""
|
|
72
|
+
|
|
73
|
+
config = load_config()
|
|
74
|
+
if config is None:
|
|
75
|
+
raise ValueError("Configuration must be initialized before changing model")
|
|
76
|
+
|
|
77
|
+
llm_config = config.get_model_config(model_name)
|
|
78
|
+
llm_client = create_llm_client(llm_config)
|
|
79
|
+
agent.set_model_profile(self._model_profile_provider.build_profile(llm_client))
|
|
80
|
+
|
|
81
|
+
developer_item = model.DeveloperMessageItem(
|
|
82
|
+
content=f"switched to model: {model_name}",
|
|
83
|
+
command_output=model.CommandOutput(command_name=commands.CommandName.MODEL),
|
|
84
|
+
)
|
|
85
|
+
agent.session.append_history([developer_item])
|
|
86
|
+
|
|
87
|
+
await self.emit_event(events.DeveloperMessageEvent(session_id=agent.session.id, item=developer_item))
|
|
88
|
+
await self.emit_event(events.WelcomeEvent(llm_config=llm_config, work_dir=str(agent.session.work_dir)))
|
|
89
|
+
|
|
90
|
+
async def apply_clear(self, agent: Agent) -> None:
|
|
91
|
+
"""Start a new conversation for an agent and notify the UI."""
|
|
92
|
+
|
|
93
|
+
old_session_id = agent.session.id
|
|
94
|
+
|
|
95
|
+
# Create a new session instance to replace the current one
|
|
96
|
+
new_session = Session(work_dir=agent.session.work_dir)
|
|
97
|
+
new_session.model_name = agent.session.model_name
|
|
98
|
+
|
|
99
|
+
# Replace the agent's session with the new one
|
|
100
|
+
agent.session = new_session
|
|
101
|
+
agent.session.save()
|
|
102
|
+
|
|
103
|
+
# Update the active_agents mapping
|
|
104
|
+
self._active_agents.pop(old_session_id, None)
|
|
105
|
+
self._active_agents[new_session.id] = agent
|
|
106
|
+
|
|
107
|
+
developer_item = model.DeveloperMessageItem(
|
|
108
|
+
content="started new conversation",
|
|
109
|
+
command_output=model.CommandOutput(command_name=commands.CommandName.CLEAR),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
await self.emit_event(events.DeveloperMessageEvent(session_id=agent.session.id, item=developer_item))
|
|
113
|
+
|
|
114
|
+
def get_active_agent(self, session_id: str) -> Agent | None:
|
|
115
|
+
"""Return the active agent for a session id if present."""
|
|
116
|
+
|
|
117
|
+
return self._active_agents.get(session_id)
|
|
118
|
+
|
|
119
|
+
def active_session_ids(self) -> list[str]:
|
|
120
|
+
"""Return a snapshot list of session ids that currently have agents."""
|
|
121
|
+
|
|
122
|
+
return list(self._active_agents.keys())
|
|
123
|
+
|
|
124
|
+
def all_active_agents(self) -> dict[str, Agent]:
|
|
125
|
+
"""Return a snapshot of all active agents keyed by session id."""
|
|
126
|
+
|
|
127
|
+
return dict(self._active_agents)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Container for main and sub-agent LLM clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from dataclasses import field as dataclass_field
|
|
7
|
+
|
|
8
|
+
from klaude_code.llm.client import LLMClientABC
|
|
9
|
+
from klaude_code.protocol.tools import SubAgentType
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _default_sub_clients() -> dict[SubAgentType, LLMClientABC]:
|
|
13
|
+
"""Return an empty mapping for sub-agent clients.
|
|
14
|
+
|
|
15
|
+
Defined separately so static type checkers can infer the dictionary
|
|
16
|
+
key and value types instead of treating them as ``Unknown``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
return {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class LLMClients:
|
|
24
|
+
"""Container for LLM clients used by main agent and sub-agents."""
|
|
25
|
+
|
|
26
|
+
main: LLMClientABC
|
|
27
|
+
sub_clients: dict[SubAgentType, LLMClientABC] = dataclass_field(default_factory=_default_sub_clients)
|
|
28
|
+
|
|
29
|
+
def get_client(self, sub_agent_type: SubAgentType | None = None) -> LLMClientABC:
|
|
30
|
+
"""Return client for a sub-agent type or the main client.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
sub_agent_type: Optional sub-agent type whose client should be returned.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The LLM client corresponding to the sub-agent type, or the main client
|
|
37
|
+
when no specialized client is available.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
if sub_agent_type is None:
|
|
41
|
+
return self.main
|
|
42
|
+
return self.sub_clients.get(sub_agent_type) or self.main
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Factory helpers for building :class:`LLMClients` from config."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from klaude_code.config import Config
|
|
6
|
+
from klaude_code.core.manager.llm_clients import LLMClients
|
|
7
|
+
from klaude_code.llm.client import LLMClientABC
|
|
8
|
+
from klaude_code.llm.registry import create_llm_client
|
|
9
|
+
from klaude_code.protocol.sub_agent import get_sub_agent_profile
|
|
10
|
+
from klaude_code.protocol.tools import SubAgentType
|
|
11
|
+
from klaude_code.trace import DebugType, log_debug
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_llm_clients(
|
|
15
|
+
config: Config,
|
|
16
|
+
*,
|
|
17
|
+
model_override: str | None = None,
|
|
18
|
+
enabled_sub_agents: list[SubAgentType] | None = None,
|
|
19
|
+
) -> LLMClients:
|
|
20
|
+
"""Create an ``LLMClients`` bundle driven by application config."""
|
|
21
|
+
|
|
22
|
+
# Resolve main agent LLM config
|
|
23
|
+
if model_override:
|
|
24
|
+
llm_config = config.get_model_config(model_override)
|
|
25
|
+
else:
|
|
26
|
+
llm_config = config.get_main_model_config()
|
|
27
|
+
|
|
28
|
+
log_debug(
|
|
29
|
+
"Main LLM config",
|
|
30
|
+
llm_config.model_dump_json(exclude_none=True),
|
|
31
|
+
style="yellow",
|
|
32
|
+
debug_type=DebugType.LLM_CONFIG,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
main_client = create_llm_client(llm_config)
|
|
36
|
+
sub_clients: dict[SubAgentType, LLMClientABC] = {}
|
|
37
|
+
|
|
38
|
+
# Initialize sub-agent clients
|
|
39
|
+
for sub_agent_type in enabled_sub_agents or []:
|
|
40
|
+
model_name = config.subagent_models.get(sub_agent_type)
|
|
41
|
+
if not model_name:
|
|
42
|
+
continue
|
|
43
|
+
profile = get_sub_agent_profile(sub_agent_type)
|
|
44
|
+
if not profile.enabled_for_model(main_client.model_name):
|
|
45
|
+
continue
|
|
46
|
+
sub_llm_config = config.get_model_config(model_name)
|
|
47
|
+
sub_clients[sub_agent_type] = create_llm_client(sub_llm_config)
|
|
48
|
+
|
|
49
|
+
return LLMClients(main=main_client, sub_clients=sub_clients)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Manager for running nested sub-agent tasks.
|
|
2
|
+
|
|
3
|
+
The :class:`SubAgentManager` encapsulates the logic for creating child
|
|
4
|
+
sessions, selecting appropriate LLM clients for sub-agents, and streaming
|
|
5
|
+
their events back to the shared event queue.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
|
|
12
|
+
from klaude_code.core.agent import Agent, ModelProfileProvider
|
|
13
|
+
from klaude_code.core.manager.llm_clients import LLMClients
|
|
14
|
+
from klaude_code.protocol import events, model
|
|
15
|
+
from klaude_code.protocol.sub_agent import SubAgentResult
|
|
16
|
+
from klaude_code.session.session import Session
|
|
17
|
+
from klaude_code.trace import DebugType, log_debug
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SubAgentManager:
|
|
21
|
+
"""Run sub-agent tasks and forward their events to the UI."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
event_queue: asyncio.Queue[events.Event],
|
|
26
|
+
llm_clients: LLMClients,
|
|
27
|
+
model_profile_provider: ModelProfileProvider,
|
|
28
|
+
) -> None:
|
|
29
|
+
self._event_queue: asyncio.Queue[events.Event] = event_queue
|
|
30
|
+
self._llm_clients: LLMClients = llm_clients
|
|
31
|
+
self._model_profile_provider: ModelProfileProvider = model_profile_provider
|
|
32
|
+
|
|
33
|
+
async def emit_event(self, event: events.Event) -> None:
|
|
34
|
+
"""Emit an event to the shared event queue."""
|
|
35
|
+
|
|
36
|
+
await self._event_queue.put(event)
|
|
37
|
+
|
|
38
|
+
async def run_subagent(self, parent_agent: Agent, state: model.SubAgentState) -> SubAgentResult:
|
|
39
|
+
"""Run a nested sub-agent task and return its result."""
|
|
40
|
+
|
|
41
|
+
# Create a child session under the same workdir
|
|
42
|
+
parent_session = parent_agent.session
|
|
43
|
+
child_session = Session(work_dir=parent_session.work_dir)
|
|
44
|
+
child_session.sub_agent_state = state
|
|
45
|
+
|
|
46
|
+
child_profile = self._model_profile_provider.build_profile(
|
|
47
|
+
self._llm_clients.get_client(state.sub_agent_type),
|
|
48
|
+
state.sub_agent_type,
|
|
49
|
+
)
|
|
50
|
+
child_agent = Agent(session=child_session, profile=child_profile)
|
|
51
|
+
|
|
52
|
+
log_debug(
|
|
53
|
+
f"Running sub-agent {state.sub_agent_type} in session {child_session.id}",
|
|
54
|
+
style="cyan",
|
|
55
|
+
debug_type=DebugType.EXECUTION,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
# Not emit the subtask's user input since task tool call is already rendered
|
|
60
|
+
result: str = ""
|
|
61
|
+
sub_agent_input = model.UserInputPayload(text=state.sub_agent_prompt, images=None)
|
|
62
|
+
async for event in child_agent.run_task(sub_agent_input):
|
|
63
|
+
# Capture TaskFinishEvent content for return
|
|
64
|
+
if isinstance(event, events.TaskFinishEvent):
|
|
65
|
+
result = event.task_result
|
|
66
|
+
await self.emit_event(event)
|
|
67
|
+
return SubAgentResult(task_result=result, session_id=child_session.id)
|
|
68
|
+
except asyncio.CancelledError:
|
|
69
|
+
# Propagate cancellation so tooling can treat it as user interrupt
|
|
70
|
+
log_debug(
|
|
71
|
+
f"Subagent task for {state.sub_agent_type} was cancelled",
|
|
72
|
+
style="yellow",
|
|
73
|
+
debug_type=DebugType.EXECUTION,
|
|
74
|
+
)
|
|
75
|
+
raise
|
|
76
|
+
except Exception as exc: # pragma: no cover - defensive logging
|
|
77
|
+
log_debug(
|
|
78
|
+
f"Subagent task failed: [{exc.__class__.__name__}] {str(exc)}",
|
|
79
|
+
style="red",
|
|
80
|
+
debug_type=DebugType.EXECUTION,
|
|
81
|
+
)
|
|
82
|
+
return SubAgentResult(
|
|
83
|
+
task_result=f"Subagent task failed: [{exc.__class__.__name__}] {str(exc)}",
|
|
84
|
+
session_id="",
|
|
85
|
+
error=True,
|
|
86
|
+
)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import shutil
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from importlib.resources import files
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
COMMAND_DESCRIPTIONS: dict[str, str] = {
|
|
8
|
+
"rg": "ripgrep - fast text search",
|
|
9
|
+
"fd": "fd - simple and fast alternative to find",
|
|
10
|
+
"tree": "tree - directory listing as a tree",
|
|
11
|
+
"sg": "ast-grep - AST-aware code search",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
# Mapping from logical prompt keys to resource file paths under the core/prompt directory.
|
|
15
|
+
PROMPT_FILES: dict[str, str] = {
|
|
16
|
+
"main_codex": "prompts/prompt-codex.md",
|
|
17
|
+
"main_claude": "prompts/prompt-claude-code.md",
|
|
18
|
+
"main_gemini": "prompts/prompt-gemini.md", # https://ai.google.dev/gemini-api/docs/prompting-strategies?hl=zh-cn#agentic-si-template
|
|
19
|
+
# Sub-agent prompts keyed by their name
|
|
20
|
+
"Task": "prompts/prompt-subagent.md",
|
|
21
|
+
"Oracle": "prompts/prompt-subagent-oracle.md",
|
|
22
|
+
"Explore": "prompts/prompt-subagent-explore.md",
|
|
23
|
+
"WebFetchAgent": "prompts/prompt-subagent-webfetch.md",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@lru_cache(maxsize=None)
|
|
28
|
+
def get_system_prompt(model_name: str, sub_agent_type: str | None = None) -> str:
|
|
29
|
+
"""Get system prompt content for the given model and sub-agent type."""
|
|
30
|
+
|
|
31
|
+
cwd = Path.cwd()
|
|
32
|
+
today = datetime.datetime.now().strftime("%Y-%m-%d")
|
|
33
|
+
is_git_repo = (cwd / ".git").exists()
|
|
34
|
+
|
|
35
|
+
available_tools: list[str] = []
|
|
36
|
+
for command, desc in COMMAND_DESCRIPTIONS.items():
|
|
37
|
+
if shutil.which(command) is not None:
|
|
38
|
+
available_tools.append(f"{command}: {desc}")
|
|
39
|
+
|
|
40
|
+
if sub_agent_type is None:
|
|
41
|
+
match model_name:
|
|
42
|
+
case name if "gpt-5" in name:
|
|
43
|
+
file_key = "main_codex"
|
|
44
|
+
case name if "gemini" in name:
|
|
45
|
+
file_key = "main_gemini"
|
|
46
|
+
case _:
|
|
47
|
+
file_key = "main_claude"
|
|
48
|
+
else:
|
|
49
|
+
file_key = sub_agent_type
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
prompt_path = PROMPT_FILES[file_key]
|
|
53
|
+
except KeyError as exc:
|
|
54
|
+
raise ValueError(f"Unknown prompt key: {file_key}") from exc
|
|
55
|
+
|
|
56
|
+
base_prompt = (
|
|
57
|
+
files(__package__)
|
|
58
|
+
.joinpath(prompt_path)
|
|
59
|
+
.read_text(encoding="utf-8")
|
|
60
|
+
.format(
|
|
61
|
+
working_directory=str(cwd),
|
|
62
|
+
date=today,
|
|
63
|
+
is_git_repo=is_git_repo,
|
|
64
|
+
model_name=model_name,
|
|
65
|
+
)
|
|
66
|
+
.strip()
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
env_lines: list[str] = [
|
|
70
|
+
"",
|
|
71
|
+
"",
|
|
72
|
+
"Here is useful information about the environment you are running in:",
|
|
73
|
+
"<env>",
|
|
74
|
+
f"Working directory: {cwd}",
|
|
75
|
+
f"Today's Date: {today}",
|
|
76
|
+
f"Is directory a git repo: {is_git_repo}",
|
|
77
|
+
f"You are powered by the model: {model_name}",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
if available_tools:
|
|
81
|
+
env_lines.append("Prefer to use the following CLI utilities:")
|
|
82
|
+
for tool in available_tools:
|
|
83
|
+
env_lines.append(f"- {tool}")
|
|
84
|
+
|
|
85
|
+
env_lines.append("</env>")
|
|
86
|
+
|
|
87
|
+
env_info = "\n".join(env_lines)
|
|
88
|
+
|
|
89
|
+
return base_prompt + env_info
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
2
|
+
|
|
3
|
+
## Tone and style
|
|
4
|
+
- Never use emojis.
|
|
5
|
+
- Your output will be displayed on a command line interface. Your responses should be short and concise. You can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
6
|
+
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
7
|
+
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
|
|
8
|
+
|
|
9
|
+
## Professional objectivity
|
|
10
|
+
Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if Claude honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs. Avoid using over-the-top validation or excessive praise when responding to users such as "You're absolutely right" or similar phrases.
|
|
11
|
+
|
|
12
|
+
## Planning without timelines
|
|
13
|
+
When planning tasks, provide concrete implementation steps without time estimates. Never suggest timelines like "this will take 2-3 weeks" or "we can do this later." Focus on what needs to be done, not when. Break work into actionable steps and let users decide scheduling.
|
|
14
|
+
|
|
15
|
+
## Task Management
|
|
16
|
+
You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
|
17
|
+
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
|
|
18
|
+
|
|
19
|
+
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
|
|
23
|
+
<example>
|
|
24
|
+
user: Run the build and fix any type errors
|
|
25
|
+
assistant: I'm going to use the TodoWrite tool to write the following items to the todo list:
|
|
26
|
+
- Run the build
|
|
27
|
+
- Fix any type errors
|
|
28
|
+
|
|
29
|
+
I'm now going to run the build using Bash.
|
|
30
|
+
|
|
31
|
+
Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list.
|
|
32
|
+
|
|
33
|
+
marking the first todo as in_progress
|
|
34
|
+
|
|
35
|
+
Let me start working on the first item...
|
|
36
|
+
|
|
37
|
+
The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
|
|
38
|
+
..
|
|
39
|
+
..
|
|
40
|
+
</example>
|
|
41
|
+
In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
|
|
42
|
+
|
|
43
|
+
<example>
|
|
44
|
+
user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
|
|
45
|
+
assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task.
|
|
46
|
+
Adding the following todos to the todo list:
|
|
47
|
+
1. Research existing metrics tracking in the codebase
|
|
48
|
+
2. Design the metrics collection system
|
|
49
|
+
3. Implement core metrics tracking functionality
|
|
50
|
+
4. Create export functionality for different formats
|
|
51
|
+
|
|
52
|
+
Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
|
|
53
|
+
|
|
54
|
+
I'm going to search for any existing metrics or telemetry code in the project.
|
|
55
|
+
|
|
56
|
+
I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
|
|
57
|
+
|
|
58
|
+
[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
|
|
59
|
+
</example>
|
|
60
|
+
|
|
61
|
+
## Doing tasks
|
|
62
|
+
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
63
|
+
- NEVER propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first. Understand existing code before suggesting modifications.
|
|
64
|
+
- Use the TodoWrite tool to plan the task if required
|
|
65
|
+
- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities. If you notice that you wrote insecure code, immediately fix it.
|
|
66
|
+
- Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.
|
|
67
|
+
- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability. Don't add docstrings, comments, or type annotations to code you didn't change. Only add comments where the logic isn't self-evident.
|
|
68
|
+
- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs). Don't use feature flags or backwards-compatibility shims when you can just change the code.
|
|
69
|
+
- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. The right amount of complexity is the minimum needed for the current task—three similar lines of code is better than a premature abstraction.
|
|
70
|
+
- Avoid backwards-compatibility hacks like renaming unused `_vars`, re-exporting types, adding `// removed` comments for removed code, etc. If something is unused, delete it completely.
|
|
71
|
+
|
|
72
|
+
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
|
|
73
|
+
|
|
74
|
+
## Tool usage policy
|
|
75
|
+
- When doing file search, prefer to use the Explore tool in order to reduce context usage.
|
|
76
|
+
- You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
|
|
77
|
+
- If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple Task tool calls.
|
|
78
|
+
- Use specialized tools instead of bash commands when possible, as this provides a better user experience. For file operations, use dedicated tools: Read for reading files instead of cat/head/tail, Edit for editing instead of sed/awk. NEVER use bash echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
|
|
79
|
+
- VERY IMPORTANT: When exploring the codebase to gather context or to answer a question that is not a needle query for a specific file/class/function, it is CRITICAL that you use the Explore tool instead of running search commands directly.
|
|
80
|
+
<example>
|
|
81
|
+
user: Where are errors from the client handled?
|
|
82
|
+
assistant: [Uses the Explore tool to find the files that handle client errors instead of using Glob or Grep directly]
|
|
83
|
+
</example>
|
|
84
|
+
<example>
|
|
85
|
+
user: What is the codebase structure?
|
|
86
|
+
assistant: [Uses the Explore tool]
|
|
87
|
+
</example>
|
|
88
|
+
|
|
89
|
+
## Memory
|
|
90
|
+
MEMORY PROTOCOL:
|
|
91
|
+
1. Use the `view` command of your `Memory` tool to check for earlier progress.
|
|
92
|
+
2. ... (work on the task) ...
|
|
93
|
+
- As you make progress, record status / progress / thoughts etc in your memory.
|
|
94
|
+
ASSUME INTERRUPTION: Your context window might be reset at any moment, so you risk losing any progress that is not recorded in your memory directory.
|
|
95
|
+
|
|
96
|
+
Note: when editing your memory folder, always try to keep its content up-to-date, coherent and organized. You can rename or delete files that are no longer relevant. Do not create new files unless necessary.
|
|
97
|
+
|
|
98
|
+
Only write down information relevant to current project in your memory system.
|