kimi-cli 0.40__py3-none-any.whl → 0.42__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.

Potentially problematic release.


This version of kimi-cli might be problematic. Click here for more details.

Files changed (55) hide show
  1. kimi_cli/CHANGELOG.md +27 -0
  2. kimi_cli/__init__.py +127 -359
  3. kimi_cli/agents/{koder → default}/agent.yaml +1 -1
  4. kimi_cli/agents/{koder → default}/system.md +1 -1
  5. kimi_cli/agentspec.py +115 -0
  6. kimi_cli/cli.py +249 -0
  7. kimi_cli/config.py +28 -14
  8. kimi_cli/constant.py +4 -0
  9. kimi_cli/exception.py +16 -0
  10. kimi_cli/llm.py +70 -0
  11. kimi_cli/metadata.py +5 -68
  12. kimi_cli/prompts/__init__.py +2 -2
  13. kimi_cli/session.py +81 -0
  14. kimi_cli/soul/__init__.py +102 -6
  15. kimi_cli/soul/agent.py +152 -0
  16. kimi_cli/soul/approval.py +1 -1
  17. kimi_cli/soul/compaction.py +4 -4
  18. kimi_cli/soul/kimisoul.py +39 -46
  19. kimi_cli/soul/runtime.py +94 -0
  20. kimi_cli/tools/dmail/__init__.py +1 -1
  21. kimi_cli/tools/file/glob.md +1 -1
  22. kimi_cli/tools/file/glob.py +2 -2
  23. kimi_cli/tools/file/grep.py +1 -1
  24. kimi_cli/tools/file/patch.py +2 -2
  25. kimi_cli/tools/file/read.py +1 -1
  26. kimi_cli/tools/file/replace.py +2 -2
  27. kimi_cli/tools/file/write.py +2 -2
  28. kimi_cli/tools/task/__init__.py +48 -40
  29. kimi_cli/tools/task/task.md +1 -1
  30. kimi_cli/tools/todo/__init__.py +1 -1
  31. kimi_cli/tools/utils.py +1 -1
  32. kimi_cli/tools/web/search.py +5 -2
  33. kimi_cli/ui/__init__.py +0 -69
  34. kimi_cli/ui/acp/__init__.py +8 -9
  35. kimi_cli/ui/print/__init__.py +21 -37
  36. kimi_cli/ui/shell/__init__.py +8 -19
  37. kimi_cli/ui/shell/liveview.py +1 -1
  38. kimi_cli/ui/shell/metacmd.py +5 -10
  39. kimi_cli/ui/shell/prompt.py +10 -3
  40. kimi_cli/ui/shell/setup.py +5 -5
  41. kimi_cli/ui/shell/update.py +2 -2
  42. kimi_cli/ui/shell/visualize.py +10 -7
  43. kimi_cli/utils/changelog.py +3 -1
  44. kimi_cli/wire/__init__.py +69 -0
  45. kimi_cli/{soul/wire.py → wire/message.py} +4 -39
  46. {kimi_cli-0.40.dist-info → kimi_cli-0.42.dist-info}/METADATA +51 -18
  47. kimi_cli-0.42.dist-info/RECORD +86 -0
  48. kimi_cli-0.42.dist-info/entry_points.txt +3 -0
  49. kimi_cli/agent.py +0 -261
  50. kimi_cli/agents/koder/README.md +0 -3
  51. kimi_cli/utils/provider.py +0 -70
  52. kimi_cli-0.40.dist-info/RECORD +0 -81
  53. kimi_cli-0.40.dist-info/entry_points.txt +0 -3
  54. /kimi_cli/agents/{koder → default}/sub.yaml +0 -0
  55. {kimi_cli-0.40.dist-info → kimi_cli-0.42.dist-info}/WHEEL +0 -0
kimi_cli/CHANGELOG.md CHANGED
@@ -9,6 +9,33 @@ Internal builds may append content to the Unreleased section.
9
9
  Only write entries that are worth mentioning to users.
10
10
  -->
11
11
 
12
+ ## [0.42] - 2025-10-28
13
+
14
+ ### Added
15
+
16
+ - Support Ctrl-J or Alt-Enter to insert a new line
17
+
18
+ ### Changed
19
+
20
+ - Change mode switch shortcut from Ctrl-K to Ctrl-X
21
+ - Improve overall robustness
22
+
23
+ ### Fixed
24
+
25
+ - Fix ACP server `no attribute` error
26
+
27
+ ## [0.41] - 2025-10-26
28
+
29
+ ### Fixed
30
+
31
+ - Fix a bug for Glob tool when no matching files are found
32
+ - Ensure reading files with UTF-8 encoding
33
+
34
+ ### Changed
35
+
36
+ - Disable reading command/query from stdin in shell mode
37
+ - Clarify the API platform selection in `/setup` meta command
38
+
12
39
  ## [0.40] - 2025-10-24
13
40
 
14
41
  ### Added
kimi_cli/__init__.py CHANGED
@@ -1,387 +1,155 @@
1
- import asyncio
2
1
  import contextlib
3
- import importlib.metadata
4
- import json
5
2
  import os
6
- import subprocess
7
- import sys
8
- import textwrap
9
3
  import warnings
10
- from datetime import datetime
4
+ from collections.abc import Generator
11
5
  from pathlib import Path
12
- from typing import Any, Literal
6
+ from typing import Any
13
7
 
14
- import click
15
8
  from pydantic import SecretStr
16
9
 
17
- from kimi_cli.agent import (
18
- DEFAULT_AGENT_FILE,
19
- AgentGlobals,
20
- BuiltinSystemPromptArgs,
21
- load_agent_with_mcp,
22
- load_agents_md,
23
- )
24
- from kimi_cli.config import (
25
- Config,
26
- ConfigError,
27
- LLMModel,
28
- LLMProvider,
29
- load_config,
30
- )
31
- from kimi_cli.metadata import Session, continue_session, new_session
32
- from kimi_cli.share import get_share_dir
33
- from kimi_cli.soul.approval import Approval
10
+ from kimi_cli.agentspec import DEFAULT_AGENT_FILE
11
+ from kimi_cli.config import LLMModel, LLMProvider, load_config
12
+ from kimi_cli.llm import augment_provider_with_env_vars, create_llm
13
+ from kimi_cli.session import Session
14
+ from kimi_cli.soul.agent import load_agent
34
15
  from kimi_cli.soul.context import Context
35
- from kimi_cli.soul.denwarenji import DenwaRenji
36
16
  from kimi_cli.soul.kimisoul import KimiSoul
17
+ from kimi_cli.soul.runtime import Runtime
37
18
  from kimi_cli.ui.acp import ACPServer
38
19
  from kimi_cli.ui.print import InputFormat, OutputFormat, PrintApp
39
- from kimi_cli.ui.shell import Reload, ShellApp
20
+ from kimi_cli.ui.shell import ShellApp
40
21
  from kimi_cli.utils.logging import StreamToLogger, logger
41
- from kimi_cli.utils.provider import augment_provider_with_env_vars, create_llm
42
22
 
43
- __version__ = importlib.metadata.version("kimi-cli")
44
- USER_AGENT = f"KimiCLI/{__version__}"
45
-
46
- UIMode = Literal["shell", "print", "acp"]
47
23
 
24
+ class KimiCLI:
25
+ @staticmethod
26
+ async def create(
27
+ session: Session,
28
+ *,
29
+ yolo: bool = False,
30
+ stream: bool = True, # TODO: remove this when we have a correct print mode impl
31
+ mcp_configs: list[dict[str, Any]] | None = None,
32
+ config_file: Path | None = None,
33
+ model_name: str | None = None,
34
+ agent_file: Path | None = None,
35
+ ) -> "KimiCLI":
36
+ """
37
+ Create a KimiCLI instance.
38
+
39
+ Args:
40
+ session (Session): A session created by `Session.create` or `Session.continue_`.
41
+ yolo (bool, optional): Approve all actions without confirmation. Defaults to False.
42
+ stream (bool, optional): Use stream mode when calling LLM API. Defaults to True.
43
+ config_file (Path | None, optional): Path to the configuration file. Defaults to None.
44
+ model_name (str | None, optional): Name of the model to use. Defaults to None.
45
+ agent_file (Path | None, optional): Path to the agent file. Defaults to None.
46
+
47
+ Raises:
48
+ FileNotFoundError: When the agent file is not found.
49
+ ConfigError(KimiCLIException): When the configuration is invalid.
50
+ AgentSpecError(KimiCLIException): When the agent specification is invalid.
51
+ """
52
+ config = load_config(config_file)
53
+ logger.info("Loaded config: {config}", config=config)
54
+
55
+ model: LLMModel | None = None
56
+ provider: LLMProvider | None = None
57
+
58
+ # try to use config file
59
+ if not model_name and config.default_model:
60
+ # no --model specified && default model is set in config
61
+ model = config.models[config.default_model]
62
+ provider = config.providers[model.provider]
63
+ if model_name and model_name in config.models:
64
+ # --model specified && model is set in config
65
+ model = config.models[model_name]
66
+ provider = config.providers[model.provider]
67
+
68
+ if not model:
69
+ model = LLMModel(provider="", model="", max_context_size=100_000)
70
+ provider = LLMProvider(type="kimi", base_url="", api_key=SecretStr(""))
71
+
72
+ # try overwrite with environment variables
73
+ assert provider is not None
74
+ assert model is not None
75
+ augment_provider_with_env_vars(provider, model)
76
+
77
+ if not provider.base_url or not model.model:
78
+ llm = None
79
+ else:
80
+ logger.info("Using LLM provider: {provider}", provider=provider)
81
+ logger.info("Using LLM model: {model}", model=model)
82
+ llm = create_llm(provider, model, stream=stream, session_id=session.id)
48
83
 
49
- @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
50
- @click.version_option(__version__)
51
- @click.option(
52
- "--verbose",
53
- is_flag=True,
54
- default=False,
55
- help="Print verbose information. Default: no.",
56
- )
57
- @click.option(
58
- "--debug",
59
- is_flag=True,
60
- default=False,
61
- help="Log debug information. Default: no.",
62
- )
63
- @click.option(
64
- "--agent-file",
65
- type=click.Path(exists=True, file_okay=True, dir_okay=False, path_type=Path),
66
- default=DEFAULT_AGENT_FILE,
67
- help="Custom agent specification file. Default: builtin Kimi Koder.",
68
- )
69
- @click.option(
70
- "--model",
71
- "-m",
72
- "model_name",
73
- type=str,
74
- default=None,
75
- help="LLM model to use. Default: default model set in config file.",
76
- )
77
- @click.option(
78
- "--work-dir",
79
- "-w",
80
- type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
81
- default=Path.cwd(),
82
- help="Working directory for the agent. Default: current directory.",
83
- )
84
- @click.option(
85
- "--continue",
86
- "-C",
87
- "continue_",
88
- is_flag=True,
89
- default=False,
90
- help="Continue the previous session for the working directory. Default: no.",
91
- )
92
- @click.option(
93
- "--command",
94
- "-c",
95
- "--query",
96
- "-q",
97
- "command",
98
- type=str,
99
- default=None,
100
- help="User query to the agent. Default: prompt interactively.",
101
- )
102
- @click.option(
103
- "--ui",
104
- "ui",
105
- type=click.Choice(["shell", "print", "acp"]),
106
- default="shell",
107
- help="UI mode to use. Default: shell.",
108
- )
109
- @click.option(
110
- "--print",
111
- "ui",
112
- flag_value="print",
113
- help="Run in print mode. Shortcut for `--ui print`.",
114
- )
115
- @click.option(
116
- "--acp",
117
- "ui",
118
- flag_value="acp",
119
- help="Start ACP server. Shortcut for `--ui acp`.",
120
- )
121
- @click.option(
122
- "--input-format",
123
- type=click.Choice(["text", "stream-json"]),
124
- default=None,
125
- help=(
126
- "Input format to use. Must be used with `--print` "
127
- "and the input must be piped in via stdin. "
128
- "Default: text."
129
- ),
130
- )
131
- @click.option(
132
- "--output-format",
133
- type=click.Choice(["text", "stream-json"]),
134
- default=None,
135
- help="Output format to use. Must be used with `--print`. Default: text.",
136
- )
137
- @click.option(
138
- "--mcp-config-file",
139
- type=click.Path(exists=True, file_okay=True, dir_okay=False, path_type=Path),
140
- multiple=True,
141
- help=(
142
- "MCP config file to load. Add this option multiple times to specify multiple MCP configs. "
143
- "Default: none."
144
- ),
145
- )
146
- @click.option(
147
- "--mcp-config",
148
- type=str,
149
- multiple=True,
150
- help=(
151
- "MCP config JSON to load. Add this option multiple times to specify multiple MCP configs. "
152
- "Default: none."
153
- ),
154
- )
155
- @click.option(
156
- "--yolo",
157
- "--yes",
158
- "-y",
159
- "--auto-approve",
160
- "yolo",
161
- is_flag=True,
162
- default=False,
163
- help="Automatically approve all actions. Default: no.",
164
- )
165
- def kimi(
166
- verbose: bool,
167
- debug: bool,
168
- agent_file: Path,
169
- model_name: str | None,
170
- work_dir: Path,
171
- continue_: bool,
172
- command: str | None,
173
- ui: UIMode,
174
- input_format: InputFormat | None,
175
- output_format: OutputFormat | None,
176
- mcp_config_file: list[Path],
177
- mcp_config: list[str],
178
- yolo: bool,
179
- ):
180
- """Kimi, your next CLI agent."""
181
- echo = click.echo if verbose else lambda *args, **kwargs: None
84
+ runtime = await Runtime.create(config, llm, session, yolo)
182
85
 
183
- logger.add(
184
- get_share_dir() / "logs" / "kimi.log",
185
- level="DEBUG" if debug else "INFO",
186
- rotation="06:00",
187
- retention="10 days",
188
- )
86
+ if agent_file is None:
87
+ agent_file = DEFAULT_AGENT_FILE
88
+ agent = await load_agent(agent_file, runtime, mcp_configs=mcp_configs or [])
189
89
 
190
- work_dir = work_dir.absolute()
90
+ context = Context(session.history_file)
91
+ await context.restore()
191
92
 
192
- if continue_:
193
- session = continue_session(work_dir)
194
- if session is None:
195
- raise click.BadOptionUsage(
196
- "--continue", "No previous session found for the working directory"
197
- )
198
- echo(f"✓ Continuing previous session: {session.id}")
199
- else:
200
- session = new_session(work_dir)
201
- echo(f"✓ Created new session: {session.id}")
202
- echo(f"✓ Session history file: {session.history_file}")
203
-
204
- if input_format is not None and ui != "print":
205
- raise click.BadOptionUsage(
206
- "--input-format",
207
- "Input format is only supported for print UI",
208
- )
209
- if output_format is not None and ui != "print":
210
- raise click.BadOptionUsage(
211
- "--output-format",
212
- "Output format is only supported for print UI",
93
+ soul = KimiSoul(
94
+ agent,
95
+ runtime,
96
+ context=context,
213
97
  )
214
-
215
- try:
216
- mcp_configs = [json.loads(conf.read_text()) for conf in mcp_config_file]
217
- except json.JSONDecodeError as e:
218
- raise click.BadOptionUsage("--mcp-config-file", f"Invalid JSON: {e}") from e
219
-
220
- try:
221
- mcp_configs += [json.loads(conf) for conf in mcp_config]
222
- except json.JSONDecodeError as e:
223
- raise click.BadOptionUsage("--mcp-config", f"Invalid JSON: {e}") from e
224
-
225
- while True:
98
+ return KimiCLI(soul, session)
99
+
100
+ def __init__(self, soul: KimiSoul, session: Session) -> None:
101
+ self._soul = soul
102
+ self._session = session
103
+
104
+ @property
105
+ def soul(self) -> KimiSoul:
106
+ """Get the KimiSoul instance."""
107
+ return self._soul
108
+
109
+ @property
110
+ def session(self) -> Session:
111
+ """Get the Session instance."""
112
+ return self._session
113
+
114
+ @contextlib.contextmanager
115
+ def _app_env(self) -> Generator[None]:
116
+ original_cwd = Path.cwd()
117
+ os.chdir(self._session.work_dir)
226
118
  try:
227
- try:
228
- config = load_config()
229
- except ConfigError as e:
230
- raise click.ClickException(f"Failed to load config: {e}") from e
231
- echo(f"✓ Loaded config: {config}")
232
-
233
- succeeded = asyncio.run(
234
- kimi_run(
235
- config=config,
236
- model_name=model_name,
237
- work_dir=work_dir,
238
- session=session,
239
- command=command,
240
- agent_file=agent_file,
241
- verbose=verbose,
242
- ui=ui,
243
- input_format=input_format,
244
- output_format=output_format,
245
- mcp_configs=mcp_configs,
246
- yolo=yolo,
247
- )
248
- )
249
- if not succeeded:
250
- sys.exit(1)
251
- break
252
- except Reload:
253
- continue
254
-
255
-
256
- async def kimi_run(
257
- *,
258
- config: Config,
259
- model_name: str | None,
260
- work_dir: Path,
261
- session: Session,
262
- command: str | None = None,
263
- agent_file: Path = DEFAULT_AGENT_FILE,
264
- verbose: bool = True,
265
- ui: UIMode = "shell",
266
- input_format: InputFormat | None = None,
267
- output_format: OutputFormat | None = None,
268
- mcp_configs: list[dict[str, Any]] | None = None,
269
- yolo: bool = False,
270
- ) -> bool:
271
- """Run Kimi CLI."""
272
- echo = click.echo if verbose else lambda *args, **kwargs: None
273
-
274
- model: LLMModel | None = None
275
- provider: LLMProvider | None = None
276
-
277
- # try to use config file
278
- if not model_name and config.default_model:
279
- # no --model specified && default model is set in config
280
- model = config.models[config.default_model]
281
- provider = config.providers[model.provider]
282
- if model_name and model_name in config.models:
283
- # --model specified && model is set in config
284
- model = config.models[model_name]
285
- provider = config.providers[model.provider]
286
-
287
- if not model:
288
- model = LLMModel(provider="", model="", max_context_size=100_000)
289
- provider = LLMProvider(type="kimi", base_url="", api_key=SecretStr(""))
290
-
291
- # try overwrite with environment variables
292
- assert provider is not None
293
- assert model is not None
294
- augment_provider_with_env_vars(provider, model)
295
-
296
- if not provider.base_url or not model.model:
297
- llm = None
298
- else:
299
- echo(f"✓ Using LLM provider: {provider}")
300
- echo(f"✓ Using LLM model: {model}")
301
- stream = ui != "print" # use non-streaming mode only for print UI
302
- llm = create_llm(provider, model, stream=stream, session_id=session.id)
303
-
304
- # TODO: support Windows
305
- ls = subprocess.run(["ls", "-la"], capture_output=True, text=True)
306
- agents_md = load_agents_md(work_dir) or ""
307
- if agents_md:
308
- echo(f"✓ Loaded agents.md: {textwrap.shorten(agents_md, width=100)}")
309
-
310
- agent_globals = AgentGlobals(
311
- config=config,
312
- llm=llm,
313
- builtin_args=BuiltinSystemPromptArgs(
314
- KIMI_NOW=datetime.now().astimezone().isoformat(),
315
- KIMI_WORK_DIR=work_dir,
316
- KIMI_WORK_DIR_LS=ls.stdout,
317
- KIMI_AGENTS_MD=agents_md,
318
- ),
319
- denwa_renji=DenwaRenji(),
320
- session=session,
321
- approval=Approval(yolo=yolo),
322
- )
323
- try:
324
- agent = await load_agent_with_mcp(agent_file, agent_globals, mcp_configs or [])
325
- except ValueError as e:
326
- raise click.BadParameter(f"Failed to load agent: {e}") from e
327
- echo(f"✓ Loaded agent: {agent.name}")
328
- echo(f"✓ Loaded system prompt: {textwrap.shorten(agent.system_prompt, width=100)}")
329
- echo(f"✓ Loaded tools: {[tool.name for tool in agent.toolset.tools]}")
330
-
331
- if command is not None:
332
- command = command.strip()
333
- if not command:
334
- raise click.BadParameter("Command cannot be empty")
335
-
336
- context = Context(session.history_file)
337
- restored = await context.restore()
338
- if restored:
339
- echo(f"✓ Restored history from {session.history_file}")
340
-
341
- soul = KimiSoul(
342
- agent,
343
- agent_globals,
344
- context=context,
345
- loop_control=config.loop_control,
346
- )
347
-
348
- original_cwd = Path.cwd()
349
- os.chdir(work_dir)
350
-
351
- try:
352
- if ui == "shell":
353
- if command is None and not sys.stdin.isatty():
354
- command = sys.stdin.read().strip()
355
- echo(f"✓ Read command from stdin: {command}")
119
+ # to ignore possible warnings from dateparser
120
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
121
+ with contextlib.redirect_stderr(StreamToLogger()):
122
+ yield
123
+ finally:
124
+ os.chdir(original_cwd)
356
125
 
126
+ async def run_shell_mode(self, command: str | None = None) -> bool:
127
+ with self._app_env():
357
128
  app = ShellApp(
358
- soul,
129
+ self._soul,
359
130
  welcome_info={
360
- "Directory": str(work_dir),
361
- "Session": session.id,
131
+ "Directory": str(self._session.work_dir),
132
+ "Session": self._session.id,
362
133
  },
363
134
  )
364
- # to ignore possible warnings from dateparser
365
- warnings.filterwarnings("ignore", category=DeprecationWarning)
366
- with contextlib.redirect_stderr(StreamToLogger()):
367
- return await app.run(command)
368
- elif ui == "print":
369
- app = PrintApp(soul, input_format or "text", output_format or "text")
370
135
  return await app.run(command)
371
- elif ui == "acp":
372
- if command is not None:
373
- logger.warning("ACP server ignores command argument")
374
- app = ACPServer(soul)
375
- return await app.run()
376
- else:
377
- raise click.BadParameter(f"Invalid UI mode: {ui}")
378
- finally:
379
- os.chdir(original_cwd)
380
-
381
-
382
- def main():
383
- kimi()
384
136
 
137
+ async def run_print_mode(
138
+ self,
139
+ input_format: InputFormat,
140
+ output_format: OutputFormat,
141
+ command: str | None = None,
142
+ ) -> bool:
143
+ with self._app_env():
144
+ app = PrintApp(
145
+ self._soul,
146
+ input_format,
147
+ output_format,
148
+ self._session.history_file,
149
+ )
150
+ return await app.run(command)
385
151
 
386
- if __name__ == "__main__":
387
- main()
152
+ async def run_acp_server(self) -> bool:
153
+ with self._app_env():
154
+ app = ACPServer(self._soul)
155
+ return await app.run()
@@ -19,6 +19,6 @@ agent:
19
19
  - "kimi_cli.tools.web:SearchWeb"
20
20
  - "kimi_cli.tools.web:FetchURL"
21
21
  subagents:
22
- koder:
22
+ coder:
23
23
  path: ./sub.yaml
24
24
  description: "Good at general software engineering tasks."
@@ -47,7 +47,7 @@ The operating environment is not in a sandbox. Any action especially mutation yo
47
47
 
48
48
  The current working directory is `${KIMI_WORK_DIR}`. This should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify the absolute path. Tools may require absolute paths for some parameters, if so, you should strictly follow the requirements.
49
49
 
50
- The `ls -la` output of current working directory is:
50
+ The directory listing of current working directory is:
51
51
 
52
52
  ```
53
53
  ${KIMI_WORK_DIR_LS}
kimi_cli/agentspec.py ADDED
@@ -0,0 +1,115 @@
1
+ from pathlib import Path
2
+ from typing import Any, NamedTuple
3
+
4
+ import yaml
5
+ from pydantic import BaseModel, Field
6
+
7
+ from kimi_cli.exception import AgentSpecError
8
+
9
+
10
+ def get_agents_dir() -> Path:
11
+ return Path(__file__).parent / "agents"
12
+
13
+
14
+ DEFAULT_AGENT_FILE = get_agents_dir() / "default" / "agent.yaml"
15
+
16
+
17
+ class AgentSpec(BaseModel):
18
+ """Agent specification."""
19
+
20
+ extend: str | None = Field(default=None, description="Agent file to extend")
21
+ name: str | None = Field(default=None, description="Agent name") # required
22
+ system_prompt_path: Path | None = Field(
23
+ default=None, description="System prompt path"
24
+ ) # required
25
+ system_prompt_args: dict[str, str] = Field(
26
+ default_factory=dict, description="System prompt arguments"
27
+ )
28
+ tools: list[str] | None = Field(default=None, description="Tools") # required
29
+ exclude_tools: list[str] | None = Field(default=None, description="Tools to exclude")
30
+ subagents: dict[str, "SubagentSpec"] | None = Field(default=None, description="Subagents")
31
+
32
+
33
+ class SubagentSpec(BaseModel):
34
+ """Subagent specification."""
35
+
36
+ path: Path = Field(description="Subagent file path")
37
+ description: str = Field(description="Subagent description")
38
+
39
+
40
+ class ResolvedAgentSpec(NamedTuple):
41
+ """Resolved agent specification."""
42
+
43
+ name: str
44
+ system_prompt_path: Path
45
+ system_prompt_args: dict[str, str]
46
+ tools: list[str]
47
+ exclude_tools: list[str]
48
+ subagents: dict[str, "SubagentSpec"]
49
+
50
+
51
+ def load_agent_spec(agent_file: Path) -> ResolvedAgentSpec:
52
+ """
53
+ Load agent specification from file.
54
+
55
+ Raises:
56
+ FileNotFoundError: If the agent spec file is not found.
57
+ AgentSpecError: If the agent spec is not valid.
58
+ """
59
+ agent_spec = _load_agent_spec(agent_file)
60
+ assert agent_spec.extend is None, "agent extension should be recursively resolved"
61
+ if agent_spec.name is None:
62
+ raise AgentSpecError("Agent name is required")
63
+ if agent_spec.system_prompt_path is None:
64
+ raise AgentSpecError("System prompt path is required")
65
+ if agent_spec.tools is None:
66
+ raise AgentSpecError("Tools are required")
67
+ return ResolvedAgentSpec(
68
+ name=agent_spec.name,
69
+ system_prompt_path=agent_spec.system_prompt_path,
70
+ system_prompt_args=agent_spec.system_prompt_args,
71
+ tools=agent_spec.tools,
72
+ exclude_tools=agent_spec.exclude_tools or [],
73
+ subagents=agent_spec.subagents or {},
74
+ )
75
+
76
+
77
+ def _load_agent_spec(agent_file: Path) -> AgentSpec:
78
+ assert agent_file.is_file(), "expect agent file to exist"
79
+ try:
80
+ with open(agent_file, encoding="utf-8") as f:
81
+ data: dict[str, Any] = yaml.safe_load(f)
82
+ except yaml.YAMLError as e:
83
+ raise AgentSpecError(f"Invalid YAML in agent spec file: {e}") from e
84
+
85
+ version = data.get("version", 1)
86
+ if version != 1:
87
+ raise AgentSpecError(f"Unsupported agent spec version: {version}")
88
+
89
+ agent_spec = AgentSpec(**data.get("agent", {}))
90
+ if agent_spec.system_prompt_path is not None:
91
+ agent_spec.system_prompt_path = agent_file.parent / agent_spec.system_prompt_path
92
+ if agent_spec.subagents is not None:
93
+ for v in agent_spec.subagents.values():
94
+ v.path = agent_file.parent / v.path
95
+ if agent_spec.extend:
96
+ if agent_spec.extend == "default":
97
+ base_agent_file = DEFAULT_AGENT_FILE
98
+ else:
99
+ base_agent_file = agent_file.parent / agent_spec.extend
100
+ base_agent_spec = _load_agent_spec(base_agent_file)
101
+ if agent_spec.name is not None:
102
+ base_agent_spec.name = agent_spec.name
103
+ if agent_spec.system_prompt_path is not None:
104
+ base_agent_spec.system_prompt_path = agent_spec.system_prompt_path
105
+ for k, v in agent_spec.system_prompt_args.items():
106
+ # system prompt args should be merged instead of overwritten
107
+ base_agent_spec.system_prompt_args[k] = v
108
+ if agent_spec.tools is not None:
109
+ base_agent_spec.tools = agent_spec.tools
110
+ if agent_spec.exclude_tools is not None:
111
+ base_agent_spec.exclude_tools = agent_spec.exclude_tools
112
+ if agent_spec.subagents is not None:
113
+ base_agent_spec.subagents = agent_spec.subagents
114
+ agent_spec = base_agent_spec
115
+ return agent_spec