Files
coder/coderd/x/chatd/subagent_catalog.go
T
Michael SuchaczandEthan Dickson 97b68e37f9 refactor(coderd/x/chatd): move subagent operations out of tool closures (#28758)
Moves the subagent tools' logic (`spawn_agent`, `wait_agent`,
`message_agent`, `interrupt_agent`, `list_agents`,
`list_subagent_models`) out of large inline closures in `subagent.go`.
Child chat operations become typed `*Server` functions in
`subagent_operations.go` that other code can call, such as the workflow
prototype in #31189. The tools become adapters that parse arguments,
apply defaults and build the JSON.

## Changes

- `subagent_operations.go`: operations take chat IDs, a timeout or a
busy behavior and return plain values. `awaitSubagent` wraps
`awaitSubagentCompletion` with the computer_use desktop recording and a
last status check, and returns the chat, report and recording, a
timeout, or a `*subagentStatusError`. `sendSubagentMessage` and
`interruptSubagent` are main's, unchanged. `listSubagents` returns
unarchived children, most recently updated first. The helpers they call
move from main unchanged.
- `subagent.go`: keeps main's model override resolution. Each tool
parses `chat_id`, applies the wait timeout or list paging defaults,
reads the target chat so errors carry its `type`, and builds the JSON.
`spawnAgent` validates the `spawn_agent` arguments.
- Tool outputs are typed structs whose fields follow sorted key order,
so the JSON the model sees is byte-identical to main's map output.

## Behavior

No intended behavior change. Error strings, tool names, descriptions and
schemas, hook fail-closed handling, the wait loop and recording lifetime
match main. `wait_agent` reads the target chat once more, for the
recording decision.

> Xum (an AI coding agent) rebuilt this PR on behalf of @ibetitsmike.

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-02 16:25:40 +11:00

388 lines
14 KiB
Go

package chatd
import (
"context"
"strings"
"charm.land/fantasy"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/codersdk"
)
const (
spawnAgentToolName = "spawn_agent"
listSubagentModelsToolName = "list_subagent_models"
subagentTypeGeneral = "general"
subagentTypeExplore = "explore"
subagentTypeComputerUse = "computer_use"
defaultSystemPromptPlanningGuidance = "1. Delegate context gathering with " +
spawnAgentToolName + " when it helps, only after defining the question or " +
"deliverable, scope, available inputs, and completion criteria. Follow the " +
spawnAgentToolName + " description for agent selection and ownership."
)
// unbilledSubagentToolNames excludes parent-side orchestration because
// child chats bill their own runtime.
var unbilledSubagentToolNames = map[string]bool{
spawnAgentToolName: true,
"wait_agent": true,
"message_agent": true,
"interrupt_agent": true,
"list_agents": true,
listSubagentModelsToolName: true,
}
type spawnAgentArgs struct {
Type string `json:"type"`
Prompt string `json:"prompt"`
Title string `json:"title,omitempty"`
ModelConfigID string `json:"model_config_id,omitempty" description:"Optional model config UUID from list_subagent_models. Runs the child on that model instead of the configured default. Not supported for type 'computer_use'."`
ReasoningEffort string `json:"reasoning_effort,omitempty" description:"Optional reasoning effort for the child: none, minimal, low, medium, high, xhigh, or max. Clamped to the selected model's supported range. Not supported for type 'computer_use'."`
}
type subagentDefinition struct {
id string
description string
unavailableReason func(context.Context, *Server, database.Chat) (string, error)
buildOptions func(context.Context, *Server, database.Chat, database.Chat, uuid.UUID, *uuid.UUID, string) (childSubagentChatOptions, error)
}
func allSubagentDefinitions() []subagentDefinition {
return []subagentDefinition{
{
id: subagentTypeGeneral,
description: "substantial delegated research, analysis, reasoning, review, planning support, and implementation",
buildOptions: func(ctx context.Context, p *Server, parent database.Chat, _ database.Chat, _ uuid.UUID, explicitModelConfigID *uuid.UUID, _ string) (childSubagentChatOptions, error) {
if explicitModelConfigID != nil {
return childSubagentChatOptions{modelConfigIDOverride: explicitModelConfigID}, nil
}
modelConfigID, reasoningEffort, err := p.resolveSubagentModelConfigID(
ctx,
parent.OwnerID,
parent.OrganizationID,
codersdk.ChatModelOverrideContextGeneral,
)
if err != nil {
return childSubagentChatOptions{}, err
}
options := childSubagentChatOptions{}
if modelConfigID != uuid.Nil {
options.modelConfigIDOverride = &modelConfigID
options.reasoningEffortOverride = reasoningEffort
}
return options, nil
},
},
{
id: subagentTypeExplore,
description: "narrow repository-local read-only code discovery and code tracing",
buildOptions: func(ctx context.Context, p *Server, _ database.Chat, turnParent database.Chat, currentModelConfigID uuid.UUID, explicitModelConfigID *uuid.UUID, _ string) (childSubagentChatOptions, error) {
modelConfigID := currentModelConfigID
var reasoningEffort *string
if explicitModelConfigID != nil {
modelConfigID = *explicitModelConfigID
} else {
resolvedModelConfigID, resolvedReasoningEffort, err := p.resolveSubagentModelConfigID(
ctx,
turnParent.OwnerID,
turnParent.OrganizationID,
codersdk.ChatModelOverrideContextExplore,
)
if err != nil {
return childSubagentChatOptions{}, err
}
if resolvedModelConfigID != uuid.Nil {
modelConfigID = resolvedModelConfigID
}
reasoningEffort = resolvedReasoningEffort
}
inheritedMCPServerIDs, err := p.resolveExploreToolSnapshot(
ctx,
turnParent,
)
if err != nil {
return childSubagentChatOptions{}, err
}
// Clearing plan mode changes only the Explore model behavior.
// The inherited tool snapshot still comes from the parent turn.
clearPlanMode := database.NullChatPlanMode{}
return childSubagentChatOptions{
chatMode: database.NullChatMode{
ChatMode: database.ChatModeExplore,
Valid: true,
},
modelConfigIDOverride: &modelConfigID,
reasoningEffortOverride: reasoningEffort,
planModeOverride: &clearPlanMode,
inheritedMCPServerIDs: inheritedMCPServerIDs,
}, nil
},
},
{
id: subagentTypeComputerUse,
description: "desktop GUI interaction, screenshots, and browser or app automation",
unavailableReason: func(ctx context.Context, p *Server, currentChat database.Chat) (string, error) {
if currentChat.PlanMode.Valid && currentChat.PlanMode.ChatPlanMode == database.ChatPlanModePlan {
return `type "computer_use" is unavailable in plan mode`, nil
}
if !p.experiments.Enabled(codersdk.ExperimentChatVirtualDesktop) {
return `type "computer_use" is unavailable because the chat-virtual-desktop experiment is not enabled`, nil
}
_, reason, err := p.resolveComputerUseModel(ctx, currentChat.OwnerID, currentChat.OrganizationID)
return reason, err
},
buildOptions: func(ctx context.Context, p *Server, currentChat database.Chat, _ database.Chat, _ uuid.UUID, _ *uuid.UUID, prompt string) (childSubagentChatOptions, error) {
model, reason, err := p.resolveComputerUseModel(ctx, currentChat.OwnerID, currentChat.OrganizationID)
if err != nil {
return childSubagentChatOptions{}, err
}
if reason != "" {
return childSubagentChatOptions{}, xerrors.New(reason)
}
return childSubagentChatOptions{
chatMode: database.NullChatMode{
ChatMode: database.ChatModeComputerUse,
Valid: true,
},
modelConfigIDOverride: &model.config.ID,
reasoningEffortOverride: model.reasoningEffort,
systemPrompt: computerUseSubagentSystemPrompt + "\n\n" + strings.TrimSpace(prompt),
}, nil
},
},
}
}
func subagentDefinitionsByID(ids ...string) []subagentDefinition {
defs := make([]subagentDefinition, 0, len(ids))
for _, id := range ids {
if def, ok := lookupSubagentDefinition(id); ok {
defs = append(defs, def)
}
}
return defs
}
func lookupSubagentDefinition(id string) (subagentDefinition, bool) {
for _, def := range allSubagentDefinitions() {
if def.id == id {
return def, true
}
}
return subagentDefinition{}, false
}
func availableSubagentDefinitions(
ctx context.Context,
p *Server,
currentChat database.Chat,
) ([]subagentDefinition, error) {
defs := allSubagentDefinitions()
available := make([]subagentDefinition, 0, len(defs))
for _, def := range defs {
reason, err := def.unavailableReasonText(ctx, p, currentChat)
if err != nil {
return nil, err
}
if reason == "" {
available = append(available, def)
}
}
return available, nil
}
func availableSubagentTypeIDs(
ctx context.Context,
p *Server,
currentChat database.Chat,
) ([]string, error) {
defs, err := availableSubagentDefinitions(ctx, p, currentChat)
if err != nil {
return nil, err
}
ids := make([]string, 0, len(defs))
for _, def := range defs {
ids = append(ids, def.id)
}
return ids, nil
}
func (d subagentDefinition) unavailableReasonText(
ctx context.Context,
p *Server,
currentChat database.Chat,
) (string, error) {
if d.unavailableReason == nil {
return "", nil
}
return d.unavailableReason(ctx, p, currentChat)
}
func resolveSubagentDefinition(
ctx context.Context,
p *Server,
currentChat database.Chat,
rawSubagentType string,
) (subagentDefinition, error) {
subagentType := strings.TrimSpace(rawSubagentType)
def, ok := lookupSubagentDefinition(subagentType)
if !ok {
ids, err := availableSubagentTypeIDs(ctx, p, currentChat)
if err != nil {
return subagentDefinition{}, err
}
return subagentDefinition{}, xerrors.Errorf(
"type must be one of: %s",
strings.Join(ids, ", "),
)
}
reason, err := def.unavailableReasonText(ctx, p, currentChat)
if err != nil {
return subagentDefinition{}, err
}
if reason != "" {
return subagentDefinition{}, xerrors.New(reason)
}
return def, nil
}
func validateSubagentSpawnParent(currentChat database.Chat) error {
if currentChat.ParentChatID.Valid {
return xerrors.New("delegated chats cannot create child subagents")
}
if isExploreSubagentMode(currentChat.Mode) {
return xerrors.New("explore chats cannot create child subagents")
}
return nil
}
func subagentTypeFromChat(chat database.Chat) string {
if !chat.Mode.Valid {
return subagentTypeGeneral
}
switch chat.Mode.ChatMode {
case database.ChatModeExplore:
return subagentTypeExplore
case database.ChatModeComputerUse:
return subagentTypeComputerUse
default:
return subagentTypeGeneral
}
}
func subagentErrorResponse(err error, chat *database.Chat) fantasy.ToolResponse {
if chat == nil {
return fantasy.NewTextErrorResponse(err.Error())
}
return toolJSONErrorResponse(map[string]any{
"error": err.Error(),
"type": subagentTypeFromChat(*chat),
})
}
func buildSpawnAgentDescription(
ctx context.Context,
p *Server,
currentChat database.Chat,
) (string, error) {
availableDefs, err := availableSubagentDefinitions(ctx, p, currentChat)
if err != nil {
return "", err
}
description := "Assign a clearly scoped, independent task to a child agent, " +
"including the criteria that complete it. Spawn only once you can define " +
"the assignment; gather missing context first rather than investigating " +
"alongside the child. Use the type field to choose " +
"the right specialist. Available type values: " +
formatSubagentDefinitionsWithDescriptionOverrides(availableDefs, nil) + ". Do not use this for " +
"simple or quick operations you can handle directly with execute, " +
"read_file, or write_file. Prefer type=\"" + subagentTypeGeneral +
"\" for substantial delegated research, analysis, reasoning, review, " +
"planning support, or implementation, even when the child should only " +
"report findings. When using type=\"" + subagentTypeGeneral +
"\" for read-only work, explicitly instruct the child not to modify " +
"files and to return findings. Use type=\"" + subagentTypeExplore +
"\" only for narrow repository-local read-only code discovery or code " +
"tracing, such as locating files, callsites, or a bounded existing flow. " +
"Do not use type=\"" + subagentTypeExplore +
"\" for generic research, broad architecture analysis, planning " +
"synthesis, external or web research, parallel research, or tasks that " +
"may need edits. Each delegated task has one owner until its result " +
"is returned or a handoff is acknowledged. While a child owns a task, do " +
"only work independent of it; do not investigate, implement, or edit that " +
"task yourself. Separate files do not make tasks independent when they " +
"depend on an unresolved shared contract. Independent work that itself " +
"qualifies for delegation is another assignment, not your own. When your " +
"next step depends on a child's result, or its report will answer the " +
"question, use wait_agent rather than doing that work yourself. Treat a " +
"report's findings and cited locations as read context; re-check only a " +
"specific gap, contradiction, suspected change, or the exact content an " +
"edit needs. The child cannot spawn its own subagents; its tools depend " +
"on its type and mode. " +
"You may optionally set model_config_id (a model config UUID from " +
listSubagentModelsToolName + ") to run the child on a specific model " +
"instead of the configured default, and reasoning_effort to pin the " +
"child's reasoning effort; both apply only to type \"" +
subagentTypeGeneral + "\" and type \"" + subagentTypeExplore + "\". " +
"Agents persist after completion; reuse an agent via message_agent for " +
"follow-up work when it already has relevant context. Spawned agents are " +
"your responsibility: do not abandon one in a working state (running); " +
"retrieve its result, redirect it with message_agent, or stop " +
"it with interrupt_agent."
if currentChat.PlanMode.Valid && currentChat.PlanMode.ChatPlanMode == database.ChatPlanModePlan {
description += " During plan mode, type=\"" + subagentTypeGeneral +
"\" is for non-mutating substantial investigation and planning support, " +
"and type=\"" + subagentTypeExplore +
"\" is for narrow repository-local lookup or tracing. Both may use " +
"shell commands for exploration and inspection, but only type=\"" +
subagentTypeGeneral +
"\" should be used for cloning repositories or non-local investigation. " +
"They must not implement changes or intentionally modify workspace files."
}
return description, nil
}
func formatSubagentDefinitionsWithDescriptionOverrides(
defs []subagentDefinition,
descriptionOverrides map[string]string,
) string {
parts := make([]string, 0, len(defs))
for _, def := range defs {
description := def.description
if override, ok := descriptionOverrides[def.id]; ok {
description = override
}
parts = append(parts, def.id+" ("+description+")")
}
return strings.Join(parts, ", ")
}
func planningOverlaySubagentGuidance() string {
planModeDescriptions := map[string]string{
subagentTypeGeneral: "non-mutating substantial investigation, analysis, and planning support",
subagentTypeExplore: "narrow repository-local codebase lookup and code tracing",
}
return "Use read_file, execute, process_output, list_templates, read_template, " +
spawnAgentToolName + ", and approved external MCP tools when available to gather context. " +
"Workspace MCP tools are not available in root plan mode, and side-effecting built-in tools such as process_list, process_signal, message_agent, interrupt_agent, and computer-use actions remain unavailable. In Plan Mode, " +
spawnAgentToolName + " delegation is for investigation and planning " +
"support, not code writing or implementation. Use type=\"" + subagentTypeGeneral +
"\" for substantial investigation, reasoning, and planning support. " +
"Use type=\"" + subagentTypeExplore +
"\" only for narrow repository-local lookup or tracing. Allowed type " +
"values in Plan Mode: " +
formatSubagentDefinitionsWithDescriptionOverrides(
subagentDefinitionsByID(
subagentTypeGeneral,
subagentTypeExplore,
),
planModeDescriptions,
) + "."
}