code-puppy 1.0.2__tar.gz → 1.0.4__tar.gz

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.
Files changed (49) hide show
  1. {code_puppy-1.0.2 → code_puppy-1.0.4}/PKG-INFO +1 -1
  2. code_puppy-1.0.4/code_puppy/agents/__init__.py +13 -0
  3. code_puppy-1.0.4/code_puppy/agents/base_agent.py +53 -0
  4. code_puppy-1.0.4/code_puppy/agents/builtins.py +67 -0
  5. code_puppy-1.0.4/code_puppy/agents/definition.py +138 -0
  6. code_puppy-1.0.4/code_puppy/agents/picker.py +89 -0
  7. code_puppy-1.0.4/code_puppy/agents/plugin.py +284 -0
  8. code_puppy-1.0.4/code_puppy/agents/plugin_agents.py +142 -0
  9. code_puppy-1.0.4/code_puppy/agents/spec.py +172 -0
  10. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/builtin_plugins.py +9 -1
  11. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/splash/__init__.py +65 -3
  12. code_puppy-1.0.4/code_puppy/universal_constructor.py +284 -0
  13. {code_puppy-1.0.2 → code_puppy-1.0.4}/pyproject.toml +1 -1
  14. {code_puppy-1.0.2 → code_puppy-1.0.4}/.gitignore +0 -0
  15. {code_puppy-1.0.2 → code_puppy-1.0.4}/LICENSE +0 -0
  16. {code_puppy-1.0.2 → code_puppy-1.0.4}/README.md +0 -0
  17. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/__init__.py +0 -0
  18. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/__main__.py +0 -0
  19. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/_art.py +0 -0
  20. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/api_keys.py +0 -0
  21. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/branding.py +0 -0
  22. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/callbacks.py +1 -1
  23. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/colors.py +0 -0
  24. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/compat/__init__.py +0 -0
  25. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/compat/bridge.py +0 -0
  26. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/compat/tools.py +0 -0
  27. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/config.py +0 -0
  28. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/distribution.py +0 -0
  29. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/first_run.py +0 -0
  30. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/former_name.py +0 -0
  31. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/i18n/__init__.py +0 -0
  32. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/identity.py +0 -0
  33. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/legacy_sessions.py +0 -0
  34. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/legacy_store.py +0 -0
  35. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/main.py +0 -0
  36. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/messaging/__init__.py +0 -0
  37. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/messaging/bus.py +0 -0
  38. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/migrate/__init__.py +0 -0
  39. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/migrate/runner.py +0 -0
  40. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/migrate/sources.py +0 -0
  41. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/migrate/translate.py +0 -0
  42. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/personality.py +0 -0
  43. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/plugins/__init__.py +0 -0
  44. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/plugins/source_only.py +0 -0
  45. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/plugins/trust.py +0 -0
  46. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/splash/__main__.py +0 -0
  47. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/splash/canvas.py +0 -0
  48. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/splash/scenes.py +0 -0
  49. {code_puppy-1.0.2 → code_puppy-1.0.4}/code_puppy/update.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: code-puppy
3
- Version: 1.0.2
3
+ Version: 1.0.4
4
4
  Summary: Code generation agent
5
5
  Project-URL: repository, https://github.com/mpfaffenberger/code_puppy
6
6
  Project-URL: HomePage, https://github.com/mpfaffenberger/code_puppy
@@ -0,0 +1,13 @@
1
+ """Code Puppy's agents: the roster, the JSON files, and the definitions built from them.
2
+
3
+ ``plugin`` is the ``agents`` plugin Code Puppy ships: it adds the chosen
4
+ agent's prompt and tool list to the main agent, offers ``/agent``, and hands
5
+ every agent to the model as a ``delegate_task`` target.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from code_puppy.agents import plugin
11
+ from code_puppy.agents.plugin import Agents
12
+
13
+ __all__ = ["Agents", "plugin"]
@@ -0,0 +1,53 @@
1
+ """Thin 0.0.x ``BaseAgent`` facade so 0.0.x plugin agents import and register.
2
+
3
+ 0.0.x plugins that register Python agent classes via ``register_agents``
4
+ subclass ``code_puppy.agents.base_agent.BaseAgent``. Code Puppy 1.0 reads
5
+ their metadata (``name``, ``display_name``, ``description``,
6
+ ``get_system_prompt``, ``get_user_prompt``, ``get_available_tools``,
7
+ ``get_model_name``) and runs them through the pax runtime.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import uuid
13
+ from abc import ABC, abstractmethod
14
+
15
+ __all__ = ["BaseAgent"]
16
+
17
+
18
+ class BaseAgent(ABC):
19
+ """Minimal 0.0.x base class for plugin-defined agents."""
20
+
21
+ def __init__(self) -> None:
22
+ self.id: str = str(uuid.uuid4())
23
+
24
+ @property
25
+ @abstractmethod
26
+ def name(self) -> str:
27
+ """Unique identifier for this agent."""
28
+
29
+ @property
30
+ @abstractmethod
31
+ def display_name(self) -> str:
32
+ """Human-readable display name for this agent."""
33
+
34
+ @property
35
+ @abstractmethod
36
+ def description(self) -> str:
37
+ """Short description of what this agent does."""
38
+
39
+ @abstractmethod
40
+ def get_system_prompt(self) -> str:
41
+ """Return the system prompt for this agent."""
42
+
43
+ @abstractmethod
44
+ def get_available_tools(self) -> list[str]:
45
+ """Return the list of tool names this agent can use."""
46
+
47
+ def get_user_prompt(self) -> str | None:
48
+ """Optional opening prompt appended after the system prompt."""
49
+ return None
50
+
51
+ def get_model_name(self) -> str | None:
52
+ """Optional preferred model name for this agent."""
53
+ return None
@@ -0,0 +1,67 @@
1
+ """The agents Code Puppy used to ship, as JSON-agent definitions.
2
+
3
+ 0.0.x built these in Python. The definitions are kept here, in the shape of a
4
+ JSON agent, so one code path builds a built-in, a user's file and a
5
+ repository's file alike. ``tools=("*",)`` keeps the runtime's own defaults:
6
+ 1.0's tool names are not 0.0.x's, and a built-in that pinned the old list
7
+ would lose tools the runtime has since added.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from code_puppy.agents.spec import AgentSpec
13
+
14
+ GENERAL = AgentSpec(
15
+ name="code-puppy",
16
+ display_name="Code Puppy",
17
+ description="General-purpose coding agent; the default.",
18
+ system_prompt="You are Code Puppy, a general-purpose coding agent.",
19
+ )
20
+
21
+ _BUILTINS = (
22
+ GENERAL,
23
+ AgentSpec(
24
+ name="planning",
25
+ display_name="Planning Agent",
26
+ description="Reads the code and writes an implementation plan; does not edit.",
27
+ system_prompt=(
28
+ "You are a planning agent. Read the code, weigh the options, and "
29
+ "write a concrete, ordered plan with the files it touches and the "
30
+ "checks that prove it works. Do not edit files: hand the plan to "
31
+ "the main agent."
32
+ ),
33
+ ),
34
+ AgentSpec(
35
+ name="qa-kitten",
36
+ display_name="QA Kitten",
37
+ description="Reviews a change for bugs, edge cases and missing tests.",
38
+ system_prompt=(
39
+ "You are a QA agent. Review the change for bugs, edge cases, and "
40
+ "missing tests. Report what is wrong and where, with evidence; do "
41
+ "not rewrite the code yourself."
42
+ ),
43
+ ),
44
+ AgentSpec(
45
+ name="code-reviewer",
46
+ display_name="Code Reviewer",
47
+ description="Reviews code for style, structure and maintainability.",
48
+ system_prompt=(
49
+ "You are a code reviewer. Judge the change against the project's "
50
+ "own conventions and the code principles it follows. Be specific: "
51
+ "point at the line and say what to change."
52
+ ),
53
+ ),
54
+ AgentSpec(
55
+ name="security-auditor",
56
+ display_name="Security Auditor",
57
+ description="Looks for injection, secrets, unsafe input and unsafe defaults.",
58
+ system_prompt=(
59
+ "You are a security auditor. Look for injection, leaked secrets, "
60
+ "unsafe input handling, and unsafe defaults. Report each finding "
61
+ "with severity and a concrete fix."
62
+ ),
63
+ ),
64
+ )
65
+
66
+ BUILTIN_AGENTS: tuple[AgentSpec, ...] = _BUILTINS
67
+ """The roster Code Puppy ships; 0.0.x's built-in agents, minus the retired core plugins."""
@@ -0,0 +1,138 @@
1
+ """Agent definitions, built with the harness's coding tools and per-agent filters.
2
+
3
+ A delegated sub-agent is a real ``pydantic_ai`` agent: it runs in the parent's
4
+ workspace with its own instructions, optional model, and ``Coder`` tools
5
+ narrowed by ``AllowedTools`` to the tools the agent lists.
6
+
7
+ For the main agent, ``ActiveAgent`` resolves the currently selected agent on
8
+ each turn so ``/agent NAME`` takes effect immediately without reloading the
9
+ plugin.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from pydantic_ai import Agent, RunContext
19
+ from pydantic_ai.capabilities import AbstractCapability, Capability, Toolset
20
+ from pydantic_ai.tools import ToolDefinition
21
+ from pydantic_ai.toolsets import AbstractToolset
22
+ from pydantic_ai_harness.coder import Coder
23
+
24
+ from code_puppy.agents.spec import AgentSpec
25
+
26
+
27
+ _RUNTIME_META_TOOLS: frozenset[str] = frozenset(
28
+ {"load_capability", "search_tools", "run_code"}
29
+ )
30
+ """Runtime meta-tools that stay available so deferred capabilities and code mode still work."""
31
+
32
+
33
+ def _keeps(
34
+ ctx: RunContext[Any], definition: ToolDefinition, allowed: frozenset[str]
35
+ ) -> bool:
36
+ return definition.name in allowed or definition.name in _RUNTIME_META_TOOLS
37
+
38
+
39
+ def prompt_for(spec: AgentSpec) -> str:
40
+ """The agent's system prompt, with its 0.0.x first message after it."""
41
+ if not spec.user_prompt:
42
+ return spec.system_prompt
43
+ return f"{spec.system_prompt}\n\n{spec.user_prompt}"
44
+
45
+
46
+ @dataclass
47
+ class AllowedTools(AbstractCapability[Any]):
48
+ """Keep only the named tools from whatever toolset the agent ends up with.
49
+
50
+ ``names`` is ``None`` for an agent that lists ``*``: it gets every tool the
51
+ runtime offers, including ones added after the agent was written.
52
+ """
53
+
54
+ names: frozenset[str] | None = None
55
+
56
+ def get_wrapper_toolset(
57
+ self, toolset: AbstractToolset[Any]
58
+ ) -> AbstractToolset[Any] | None:
59
+ allowed = self.names
60
+ if allowed is None:
61
+ return None
62
+ return toolset.filtered(
63
+ lambda ctx, definition: _keeps(ctx, definition, allowed)
64
+ )
65
+
66
+
67
+ @dataclass
68
+ class ActiveAgent(AbstractCapability[Any]):
69
+ """Apply the currently selected agent's prompt and tool filter on every turn.
70
+
71
+ Pax calls ``Plugin.get_capabilities()`` once at plugin load time, so reading
72
+ the active agent dynamically here lets ``/agent NAME`` take effect on the
73
+ very next turn without reloading the plugin.
74
+ """
75
+
76
+ current: Callable[[], AgentSpec]
77
+
78
+ def get_instructions(self) -> Callable[[RunContext[Any]], str]:
79
+ return lambda _ctx: prompt_for(self.current())
80
+
81
+ def get_wrapper_toolset(
82
+ self, toolset: AbstractToolset[Any]
83
+ ) -> AbstractToolset[Any]:
84
+ def allows(ctx: RunContext[Any], tool_def: ToolDefinition) -> bool:
85
+ tools = self.current().runtime_tools()
86
+ return (
87
+ tools is None
88
+ or tool_def.name in tools
89
+ or tool_def.name in _RUNTIME_META_TOOLS
90
+ )
91
+
92
+ return toolset.filtered(allows)
93
+
94
+
95
+ def definition(
96
+ spec: AgentSpec,
97
+ *,
98
+ persona: Callable[[AgentSpec], AbstractCapability[Any] | None] | None = None,
99
+ coder: bool = True,
100
+ unrestricted_filesystem: bool = False,
101
+ repo_context: bool = True,
102
+ uc_toolset: Toolset[Any] | None = None,
103
+ ) -> Agent[Any, str]:
104
+ """A ``pydantic_ai`` agent for one built-in, JSON, or plugin agent.
105
+
106
+ ``coder=True`` (the default for delegated sub-agents) attaches ``Coder``
107
+ without nested sub-agents so the delegate has the workspace's file, grep,
108
+ and shell tools, narrowed by ``AllowedTools`` to ``spec.runtime_tools()``.
109
+ ``persona`` gives a top-level agent its persona; a delegated one omits it
110
+ so it reports back instead of acting like the main agent.
111
+ """
112
+ tools = spec.runtime_tools()
113
+ capabilities: list[AbstractCapability[Any]] = []
114
+ if coder:
115
+ capabilities.append(
116
+ Coder(
117
+ unrestricted_filesystem=unrestricted_filesystem,
118
+ repo_context=repo_context,
119
+ sub_agents=False,
120
+ )
121
+ )
122
+ if uc_toolset is not None:
123
+ capabilities.append(uc_toolset)
124
+ capabilities.append(Capability(instructions=prompt_for(spec)))
125
+ capabilities.append(
126
+ AllowedTools(names=frozenset(tools) if tools is not None else None)
127
+ )
128
+ if persona is not None:
129
+ own = persona(spec)
130
+ if own is not None:
131
+ capabilities.append(own)
132
+ return Agent(
133
+ spec.model,
134
+ name=spec.name,
135
+ description=spec.description,
136
+ capabilities=capabilities,
137
+ defer_model_check=True,
138
+ )
@@ -0,0 +1,89 @@
1
+ """Interactive Termflow TUI picker for ``/agent``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from pydantic_ai_pax.ui.menus.field_menu import TERMINAL, Runners
8
+ from pydantic_ai_pax.ui.menus.menu_worker import menu_key, run_worker
9
+ from pydantic_ai_pax.ui.menus.slash_search import slash_search
10
+ from pydantic_ai_pax.ui.rendering.rendering import markdown_style
11
+ from pydantic_ai_pax.ui.rendering.tool_output import terminal_text
12
+ from termflow.tui import MenuBuilder, MenuItem
13
+ from termflow.tui.menu import Menu
14
+
15
+ from code_puppy.agents.spec import AgentSpec
16
+
17
+ _PROMPT_PREVIEW_CHARS = 400
18
+
19
+
20
+ def agent_preview(spec: AgentSpec) -> str:
21
+ """Right-hand preview for one agent in the ``/agent`` picker."""
22
+ tools = spec.runtime_tools()
23
+ tools_text = "all (*)" if tools is None else ", ".join(tools)
24
+ lines = [
25
+ terminal_text(f"{spec.display_name} ({spec.name})"),
26
+ "",
27
+ terminal_text(spec.description),
28
+ "",
29
+ f"Tools: {terminal_text(tools_text)}",
30
+ ]
31
+ if spec.model:
32
+ lines.append(f"Model: {terminal_text(spec.model)}")
33
+ if spec.source is not None:
34
+ lines.append(f"Source: {terminal_text(str(spec.source))}")
35
+ snippet = spec.system_prompt.strip()
36
+ if len(snippet) > _PROMPT_PREVIEW_CHARS:
37
+ snippet = snippet[:_PROMPT_PREVIEW_CHARS].rstrip() + "..."
38
+ lines.extend(["", "Prompt:", terminal_text(snippet)])
39
+ return "\n".join(lines)
40
+
41
+
42
+ def build_agent_picker(agents: Sequence[AgentSpec], current: AgentSpec) -> Menu:
43
+ """Searchable Termflow menu listing every agent with a live preview pane."""
44
+ by_name = {agent.name: agent for agent in agents}
45
+ names = [agent.name for agent in agents]
46
+ initial = names.index(current.name) if current.name in names else 0
47
+ items = [
48
+ MenuItem(
49
+ terminal_text(
50
+ f"{agent.display_name} ({agent.name})"
51
+ f"{' (current)' if agent.name == current.name else ''}"
52
+ ),
53
+ value=agent.name,
54
+ )
55
+ for agent in agents
56
+ ]
57
+ builder = (
58
+ MenuBuilder("Select agent")
59
+ .style(markdown_style())
60
+ .items(items)
61
+ .initial_index(initial)
62
+ .list_width(36)
63
+ .preview(
64
+ lambda item: (
65
+ agent_preview(by_name[item.value])
66
+ if isinstance(item.value, str) and item.value in by_name
67
+ else ""
68
+ )
69
+ )
70
+ )
71
+ return slash_search(builder, footer="Enter switch - Esc close", key_source=menu_key)
72
+
73
+
74
+ async def pick_agent(
75
+ agents: Sequence[AgentSpec],
76
+ current: AgentSpec,
77
+ *,
78
+ runners: Runners = TERMINAL,
79
+ ) -> str | None:
80
+ """Show the ``/agent`` TUI picker and return the chosen name, or ``None`` if cancelled."""
81
+ menu = build_agent_picker(agents, current)
82
+ result = await run_worker(lambda: runners.run_list(menu))
83
+ if (
84
+ result.cancelled
85
+ or result.item is None
86
+ or not isinstance(result.item.value, str)
87
+ ):
88
+ return None
89
+ return result.item.value
@@ -0,0 +1,284 @@
1
+ """The agents plugin: the roster, ``/agent``, and the main agent's definition.
2
+
3
+ One plugin owns both sides of the old ``/agent`` feature, so the agents the
4
+ command lists are exactly the agents the model can delegate to:
5
+
6
+ * **The roster.** Code Puppy's built-ins, 0.0.x plugin agents (``register_agents``),
7
+ the user's ``~/.code_puppy/agents/`` and the repository's ``.code_puppy/agents/``,
8
+ in that order, a later agent of the same name replacing an earlier one.
9
+ * **``/agent``.** With no argument, the roster; with a name, that agent takes
10
+ over the conversation. The switch is a switch of instructions and tools, not
11
+ a second conversation: the history stays, so the new agent answers what was
12
+ just asked. The next turn runs with the new agent's prompt and tools.
13
+ * **``delegate_task``.** The same definitions are handed to the harness's
14
+ ``SubAgents`` capability, so the model can delegate to any of them.
15
+
16
+ The chosen agent's prompt is added beside the runtime's coding instructions;
17
+ its tools are the runtime's, narrowed to the tools it lists.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from pydantic import BaseModel, ConfigDict
28
+ from pydantic_ai.capabilities import AgentCapability
29
+ from pydantic_ai_harness.sub_agents import SubAgent, SubAgents, TaskControl
30
+ from pydantic_ai_pax.builtin_plugins.coder import CoderSettings
31
+ from pydantic_ai_pax.config.builtins import STOCK_PLUGINS
32
+ from pydantic_ai_pax.config.settings_store import SettingsStore
33
+ from pydantic_ai_pax.plugins import Command, Plugin, PluginHost, SessionStart
34
+
35
+ from code_puppy import messaging, universal_constructor
36
+ from code_puppy.agents import builtins, picker, plugin_agents, spec as specs
37
+ from code_puppy.agents.definition import ActiveAgent, definition
38
+ from code_puppy.agents.spec import AgentSpec
39
+
40
+ PLUGIN_ID = "agents"
41
+ FACTORY = "code_puppy.agents.plugin:Agents"
42
+
43
+ LIST_WORDS = frozenset({"list", "ls", "agents"})
44
+ """Arguments that ask for the roster rather than for a switch."""
45
+
46
+ SUB_AGENTS_ID = "sub_agents"
47
+ """The harness's own ``SubAgents`` id, so our roster composes with ``coder``'s."""
48
+
49
+ SEPARATE_SUB_AGENTS_ID = "code_puppy_agents"
50
+ """Fallback id when ``coder`` uses custom delegation settings we cannot mirror."""
51
+
52
+ SEPARATE_DELEGATE_TOOL = "delegate_puppy_agent"
53
+ """Tool name paired with ``SEPARATE_SUB_AGENTS_ID`` so it never collides with ``delegate_task``."""
54
+
55
+
56
+ class AgentSettings(BaseModel):
57
+ """The agent a conversation starts with."""
58
+
59
+ model_config = ConfigDict(extra="forbid", frozen=True)
60
+
61
+ agent: str | None = None
62
+ """The name chosen with ``/agent``; ``None`` means Code Puppy's own."""
63
+
64
+
65
+ def roster(
66
+ workspace: Path,
67
+ *,
68
+ report_errors: bool = False,
69
+ ) -> tuple[AgentSpec, ...]:
70
+ """Every agent available here: built-ins, plugin agents, user files, project files."""
71
+ warn = messaging.emit_warning if report_errors else None
72
+ file_error = (
73
+ (
74
+ lambda path, exc: messaging.emit_warning(
75
+ f"Skipping broken agent {path}: {exc}"
76
+ )
77
+ )
78
+ if report_errors
79
+ else None
80
+ )
81
+ return specs.merge(
82
+ builtins.BUILTIN_AGENTS,
83
+ plugin_agents.discover(on_error=warn),
84
+ specs.discover(
85
+ [specs.agents_dir(), specs.project_agents_dir(workspace)],
86
+ on_error=file_error,
87
+ ),
88
+ )
89
+
90
+
91
+ def find(agents: Sequence[AgentSpec], name: str) -> AgentSpec | None:
92
+ """The agent called ``name``, by name or by display name, case-insensitively."""
93
+ wanted = name.strip().casefold()
94
+ if not wanted:
95
+ return None
96
+ for agent in agents:
97
+ if wanted in (agent.name.casefold(), agent.display_name.casefold()):
98
+ return agent
99
+ return None
100
+
101
+
102
+ def listing(agents: Sequence[AgentSpec], current: AgentSpec) -> str:
103
+ """The roster as ``/agent`` shows it, the current agent marked."""
104
+ width = max(len(agent.name) for agent in agents)
105
+ lines = [
106
+ f"{'*' if agent.name == current.name else ' '} {agent.name:<{width}} "
107
+ f"{agent.display_name} - {agent.description}"
108
+ for agent in agents
109
+ ]
110
+ return "Agents (switch with /agent NAME):\n" + "\n".join(lines)
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Delegation:
115
+ """How the loaded ``coder`` plugin delegates, which our roster has to match.
116
+
117
+ ``CoderPlugin`` contributes a ``SubAgents`` of its own. Two ``SubAgents``
118
+ with the same id compose only when they agree on every field except the
119
+ roster, so we read ``coder``'s live ``CoderSettings`` from ``host.plugins``.
120
+ """
121
+
122
+ agent_folders: tuple[str, ...]
123
+ sub_agents: bool
124
+ task_control: bool
125
+ custom_delegation: bool
126
+ unrestricted_filesystem: bool
127
+ repo_context: bool
128
+
129
+ @classmethod
130
+ def of(cls, host: PluginHost[Any]) -> Delegation:
131
+ """Read ``coder``'s active settings from the loaded plugin catalog."""
132
+ settings = _coder_settings(host)
133
+ folders = settings.folders(home=Path.home())
134
+ return cls(
135
+ agent_folders=tuple(str(folder) for folder in folders),
136
+ sub_agents=settings.sub_agents,
137
+ task_control=settings.task_control,
138
+ custom_delegation=bool(settings.delegate_models) or settings.review_agent,
139
+ unrestricted_filesystem=settings.unrestricted_filesystem,
140
+ repo_context=settings.repo_context,
141
+ )
142
+
143
+
144
+ def _coder_settings(host: PluginHost[Any]) -> CoderSettings:
145
+ """``coder``'s effective settings, safe to read during plugin load in any order.
146
+
147
+ Reads the persisted ``coder`` declaration from ``host.settings_database``
148
+ when present (avoiding re-entrant ``host.plugins.listing()`` during load),
149
+ otherwise falls back to ``STOCK_PLUGINS``'s ``coder`` declaration.
150
+ """
151
+ raw: dict[str, Any] | None = None
152
+ if host.settings_database is not None:
153
+ stored = next(
154
+ (
155
+ p
156
+ for p in SettingsStore(host.settings_database).plugins()
157
+ if p.id == "coder"
158
+ ),
159
+ None,
160
+ )
161
+ if stored is not None:
162
+ raw = dict(stored.settings)
163
+ if raw is None:
164
+ stock = next((p for p in STOCK_PLUGINS if p.id == "coder"), None)
165
+ if stock is not None:
166
+ raw = dict(stock.settings)
167
+ if raw is None:
168
+ return CoderSettings()
169
+ return CoderSettings.model_validate(raw)
170
+
171
+
172
+ class Agents(Plugin[AgentSettings, Any]):
173
+ """Ships Code Puppy's agents, loads JSON & plugin agents, and switches between them."""
174
+
175
+ def __init__(self, host: PluginHost[Any], settings: AgentSettings) -> None:
176
+ super().__init__(host, settings)
177
+ self._active: str | None = settings.agent
178
+ self._startup_warnings_shown = False
179
+
180
+ def _current_agent(self) -> AgentSpec:
181
+ agents = roster(self.host.workspace)
182
+ return find(agents, self._active or "") or agents[0]
183
+
184
+ async def on_session_start(self, event: SessionStart) -> None:
185
+ if not self._startup_warnings_shown:
186
+ self._startup_warnings_shown = True
187
+ roster(self.host.workspace, report_errors=True)
188
+
189
+ def get_capabilities(self) -> Sequence[AgentCapability[Any]]:
190
+ capabilities: list[AgentCapability[Any]] = [
191
+ ActiveAgent(current=self._current_agent),
192
+ ]
193
+ delegation = self._delegation(roster(self.host.workspace))
194
+ if delegation is not None:
195
+ capabilities.append(delegation)
196
+ return tuple(capabilities)
197
+
198
+ def _delegation(self, agents: Sequence[AgentSpec]) -> SubAgents[Any] | None:
199
+ """``delegate_task`` over every agent, matching ``coder``'s own settings."""
200
+ delegation = Delegation.of(self.host)
201
+ if not delegation.sub_agents:
202
+ return None
203
+ delegates = self._delegates(agents, delegation)
204
+ if delegation.custom_delegation:
205
+ # ``CoderPlugin`` attaches bound per-instance resolvers when
206
+ # ``delegate_models`` or ``review_agent`` is enabled, which cannot
207
+ # compare equal across two ``SubAgents`` instances. Keep our roster
208
+ # under its own id/tool name instead of crashing ``SubAgents.combine``.
209
+ return SubAgents(
210
+ agents=delegates,
211
+ id=SEPARATE_SUB_AGENTS_ID,
212
+ tool_name=SEPARATE_DELEGATE_TOOL,
213
+ )
214
+ return SubAgents(
215
+ agents=delegates,
216
+ agent_folders=list(delegation.agent_folders) or None,
217
+ id=SUB_AGENTS_ID,
218
+ task_control=TaskControl() if delegation.task_control else None,
219
+ )
220
+
221
+ def _delegates(
222
+ self, agents: Sequence[AgentSpec], delegation: Delegation
223
+ ) -> tuple[SubAgent[Any], ...]:
224
+ """Every agent as a ``delegate_task`` target, with coding tools and no persona."""
225
+ uc_toolset = universal_constructor.build_toolset()
226
+ return tuple(
227
+ SubAgent(
228
+ definition(
229
+ agent,
230
+ unrestricted_filesystem=delegation.unrestricted_filesystem,
231
+ repo_context=delegation.repo_context,
232
+ uc_toolset=uc_toolset,
233
+ ),
234
+ name=agent.name,
235
+ description=agent.description,
236
+ )
237
+ for agent in agents
238
+ )
239
+
240
+ def get_commands(self) -> Sequence[Command]:
241
+ return (
242
+ Command(
243
+ name="agent",
244
+ description="Pick an agent from the menu, list them, or switch: /agent [NAME]",
245
+ handler=self._agent_command,
246
+ during_turn=True,
247
+ complete=lambda args: (
248
+ agent.name
249
+ for agent in roster(self.host.workspace)
250
+ if not args or agent.name.startswith(args[0])
251
+ ),
252
+ ),
253
+ )
254
+
255
+ def _switch_to(self, agent: AgentSpec) -> str:
256
+ self._active = agent.name
257
+ self._settings = AgentSettings(agent=agent.name)
258
+ self.host.save_settings(self._settings)
259
+ return (
260
+ f"Switched to {agent.display_name} ({agent.name}). "
261
+ f"The next turn runs with its prompt and tools."
262
+ )
263
+
264
+ async def _agent_command(self, args: list[str]) -> str:
265
+ agents = roster(self.host.workspace)
266
+ current = self._current_agent()
267
+ if args and args[0].casefold() in LIST_WORDS:
268
+ return listing(agents, current)
269
+ if not args:
270
+ if not self.host.console.is_terminal:
271
+ return listing(agents, current)
272
+ chosen_name = await picker.pick_agent(agents, current)
273
+ if chosen_name is None:
274
+ return ""
275
+ picked = find(agents, chosen_name)
276
+ if picked is None:
277
+ return ""
278
+ if picked.name == current.name:
279
+ return ""
280
+ return self._switch_to(picked)
281
+ agent = find(agents, " ".join(args))
282
+ if agent is None:
283
+ return f"No agent called {' '.join(args)!r}.\n\n" + listing(agents, current)
284
+ return self._switch_to(agent)