Files
coder/coderd/x/chatd/subagent_catalog.go
T
Michael Suchacz ac824cd235 chore(coderd): remove dead code from chatd (#29008)
Removes production code in `coderd/x/chatd` that nothing reaches, the
tests that only existed to exercise it, and option/config fields that
callers filled in but chatd never read. No runtime behaviour changes;
the only edits outside `coderd/x/chatd` drop the now-nonexistent fields
at their three call sites (`coderd/coderd.go`, `coderd/exp_chats.go`,
`coderd/coderdtest`).

Net: 42 files, +147 / -1065.

Verification method for every item: `golang.org/x/tools/cmd/deadcode`
(with and without `-test`) rooted at `cmd/coder`, `enterprise/cmd/coder`
and every package that imports chatd; a `go/packages` pass counting
`TypesInfo.Uses` per declared type, const, var, field and method across
the same roots, split into test and non-test use sites, plus a
read-vs-write split for struct fields; `rg` over the whole repo
including `site/src` for json tag names; then `go build ./...`, `go vet
./coderd/x/chatd/...`, `golangci-lint run ./coderd/x/chatd/... ./coderd/
./coderd/coderdtest/`, and `go test ./coderd/x/chatd/...` (all 20
packages) locally.

<details>
<summary>Evidence per deletion</summary>

| Removed | What it was | Why unused |
|---|---|---|
| `subagent.go` `resolveConfiguredModelOverride`, `parseModelOverride`,
`parsedModelOverride` (~135 lines) +
`TestResolveConfiguredModelOverride_*`, `TestParseModelOverride` |
raw-string model override resolver | Only callers were its two tests;
production resolves overrides through `resolveOrganizationModelOverride`
(`title_override.go`, `compaction_override.go`, `subagent.go`). |
| `chatd.go` `removeSkillIndexMessages`, `isSkillIndexMessage` +
`TestSkillIndexRefreshReplacesStaleAliases` | skill-index refresh
helpers | Zero production references; the test simulated a refresh path
no production code performs. |
| `chatd.go` `chatMessage`, `newChatMessage`, `withCreatedBy`,
`appendMessageFields`, `BuildSingleChatMessageInsertParams` (~90 lines)
| insert-params builder | Exported, but every caller was a `chatd_test`
file (6 sites). Replaced by a 25-line `singleChatMessageInsertParams`
helper in `chatd_helpers_test.go`. |
| `chatd.go` `Server.closeInflightAdmission` | one-line wrapper around
`inflightClosed.Store(true)` | Single call site (`Close`); inlined. |
| `chatd.go` `Server.workerID`, `instructionLookupTimeout`,
`pendingChatAcquireInterval`, `maxChatsPerAcquire`,
`chatHeartbeatInterval` | Server struct fields | Assigned in `New` and
never read anywhere (the values reach the worker through
`chatWorkerOptions`, not these fields). |
| `Config.InstructionLookupTimeout`, `homeInstructionLookupTimeout`,
`coderd.Options.ChatdInstructionLookupTimeout`,
`coderdtest.Options.ChatdInstructionLookupTimeout` | timeout plumbing |
The value only landed in the dead `Server.instructionLookupTimeout`; no
CLI flag sets it and nothing reads it. |
| `PromoteQueuedOptions.CreatedBy` | option field | Set by
`coderd/exp_chats.go` and three tests, never read in chatd (promotion
keeps the queued row's `created_by`). |
| `SubmitToolResultsOptions.DynamicTools` | option field | Set by
`coderd/exp_chats.go` (which re-read `chat.DynamicTools` just to pass
it) and three tests, never read in chatd. |
| `attachments.go` `buildAssistantPartsForPersist` (whole file) |
assistant part builder | Stale copy left by #26270; production uses
`buildAssistantParts` in `message_conversion.go`. Its six tests were
retargeted to the live function (now
`message_conversion_internal_test.go`) and a dead-copy assertion in
`subagent_internal_test.go` was dropped. |
| `chatloop.RunOptions` (94 lines) | old loop options struct | Only two
of 23 fields were ever populated, for one internal call to
`prepareMessagesForRequest`, which now takes `model, logger` directly
and no longer returns the ignored canonical slice.
`GenerateAssistantOptions` / `ExecuteLocalToolsOptions` are the live
types. |
| `chatloop.ErrDynamicToolCall`, `ErrStopAfterTool`, `PendingToolCall`,
`PersistedStep.PendingDynamicToolCalls` | dynamic-tool exit protocol |
Zero references outside their declarations (one stale comment in
`chatdebug/service.go` updated). |
| `chatloop.CompactionOptions.Persist`, `.OnError` | callbacks |
`Persist` had zero references; `OnError` was set only by two tests that
asserted it was never invoked. |
| `chatloop` `stepResult.shouldContinue` + its computation | flag |
Written once, never read. |
| `chatloop.StateWaiting` | metric label const | Zero references. |
| `generation.go` `generationOutcome.InsertedMessages`,
`runnerActionMessage` | outcome field | Built on every commit, never
read. |
| `chatstate` `ExecutionState.IsArchived`, `AllOwnershipStates`,
`OwnershipState`/`StateU`/`StateO`, `TransitionAcquire` | state-machine
leftovers | Zero references (the ownership consts became dead once
`AllOwnershipStates` went). |
| `chatstate` `ExecutionState.QueueNonEmpty` | predicate | Only
referenced by the test asserting its own table; the sibling `IsRunnable`
check in that test is kept. |
| `chatdebug.Attempt.RetryClassification`, `.RetryDelayMs` | json fields
| Never assigned anywhere, `omitempty`, and
`retry_classification`/`retry_delay_ms` do not appear in `site/src` or
`typesGenerated.ts`. |
| `chatdebug.RunContext.Kind`, `StepContext.HistoryTipMessageID`,
`RecorderOptions.Provider`/`.Model`, `stepHandle.opts`/`.usage`/`.err` |
context/handle fields | Written (from `chatd.go`,
`chatloop/compaction.go`, `modelcall.go`, `recorder.go`) and never read.
The DB run row keeps its own `kind` column. |
| `chatprovider.MergeProviderAPIKeys` +
`TestMergeProviderAPIKeys_PreservesProviderRegions` | key merge |
Superseded by `ResolveUserProviderKeys`, whose region test already
covers the same behaviour. |
| `chatprovider` `providerCreationError` | one-line `xerrors.Errorf`
wrapper | Single call site; inlined with identical message. |
| `chatretry.IsRetryable` | classifier wrapper | Zero references. |
| `computeruse.IsTool` + `TestComputerUseTool` | one-line forwarder to
`fantasyopenai.IsComputerUseTool` | No production caller; two test
assertions now call the fantasy function directly, and the dropped test
only asserted the library's own constructor. |
| `chatprompt.ToolResultToPart` | one-line forwarder to
`codersdk.ChatMessageToolResult` | Single call site; inlined. |
| `subagent_catalog.go` `formatSubagentDefinitions` | forwarder with
`nil` overrides | Single call site; inlined. |
| `worker.go` `chatWorker.chatWorkerID` | getter | Only tests called it;
they read `opts.WorkerID` directly now. |
| `chattest.AnthropicErrorResponse`, `OpenAIServerErrorResponse`,
`ChatMessageWithParts` (`messages.go` removed) | test fixtures | Zero
references. |
| `chattest` `AnthropicRequest.Options`, `OpenAIRequest.Options` |
`json:",inline"` map fields | `encoding/json` has no inline tag (the
TODO on each said so); never populated, never read. |

</details>

<details>
<summary>Considered and kept</summary>

- `chatstate.CreateChat` (test-only thin wrapper over `insertChat`,
production uses `CreateChatWithID`): documented package API with 25 test
call sites; not worth the churn.
- `chatprompt.MarshalContent` / `MarshalToolResult`: test-only, but they
deliberately produce legacy-format DB rows so the read path's legacy
handling stays covered.
- `chatstate.AllowedExecutionTransitionsFrom` / `AllowedInputStates` /
`AllowedExecutionTransitionOutputs`, `chatdebug.StepFromContext`,
`WithClock`, `WithStaleThreshold`, `WaitUntilIdleForTest`,
`PublishBuffer.BufferedChannels`, `chattool.NewWorkspaceMCPTool`: test
seams that tests actively use to reach otherwise unexported state.
- `AgentCapacityLimiter` interface (one production implementation):
tests inject fakes.
- `applyHookResultMessages` / `appendHookResultMessages`: a named pair
over one placement enum, both used.
- Nil-receiver guards on `*Metrics`, `*Result`, `*streamSyncPoller`,
`*runnerDebugTurn`: nil is a supported "disabled" value on those paths.
- Tests flagged by heuristics as assertion-light
(`TestNopMetrics_DoesNotPanic`, `TestStepHandleFinish_NilHandle`,
`TestRetry_OnRetryNilDoesNotPanic`, the `chatstate`
synthetic-cancellation tests that assert through helpers): they cover
real nil-safety or delegate assertions to helpers; kept.

</details>

<details>
<summary>Out-of-scope findings (not changed here)</summary>

- `chatdebug.Service.FinalizeStale` has had no production caller since
#26270 removed the background sweep loop; only its tests call it, and
comments in `chatd_debug.go` and `database/querier.go` still describe
the loop. Deleting it would erase the implementation a fix needs, so it
is left for a decision.
- `coderd_chatd_chats` (gauge) and
`coderd_chatd_stream_buffer_dropped_total` (counter) are registered and
documented in `docs/admin/integrations/prometheus.md` but never set or
incremented in production; `Metrics.RecordStreamBufferDropped` is
test-only. Removing them changes the exported metric set and the docs,
so they are left alone.

</details>

## Declined review findings

None yet.

> Xum (AI agent) opened this PR on behalf of @ibetitsmike.
2026-09-05 11:39:10 +02:00

393 lines
15 KiB
Go

package chatd
import (
"context"
"strings"
"charm.land/fantasy"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"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. Use " + spawnAgentToolName +
" and wait_agent when delegation helps gather context. Prefer type=\"" +
subagentTypeGeneral +
"\" for substantial delegated research, analysis, reasoning, review, " +
"planning support, or implementation. Use type=\"" + subagentTypeGeneral +
"\" even for read-only work when the task is open-ended, multi-step, " +
"parallel, requires synthesis, or may later need edits. When planning, " +
"type=\"" + subagentTypeGeneral +
"\" remains non-mutating until implementation is approved. 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."
)
// unbilledSubagentToolNames excludes parent-side orchestration because
// child chats bill their own runtime. Include deprecated aliases.
var unbilledSubagentToolNames = map[string]bool{
spawnAgentToolName: true,
"wait_agent": true,
"message_agent": true,
"interrupt_agent": true,
"close_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
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 {
if currentChat.PlanMode.Valid && currentChat.PlanMode.ChatPlanMode == database.ChatPlanModePlan {
return `type "computer_use" is unavailable in plan mode`
}
if !p.experiments.Enabled(codersdk.ExperimentChatVirtualDesktop) {
return `type "computer_use" is unavailable because the chat-virtual-desktop experiment is not enabled`
}
_, _, _, err := p.computerUseProviderAndModelFromConfig(ctx)
if err != nil {
p.logger.Warn(ctx, "computer-use provider config is unavailable",
slog.F("chat_id", currentChat.ID),
slog.Error(err),
)
return `type "computer_use" is unavailable because its provider configuration could not be loaded`
}
return ""
},
buildOptions: func(ctx context.Context, p *Server, currentChat database.Chat, _ database.Chat, _ uuid.UUID, _ *uuid.UUID, prompt string) (childSubagentChatOptions, error) {
provider, _, _, err := p.computerUseProviderAndModelFromConfig(ctx)
if err != nil {
return childSubagentChatOptions{}, err
}
providerKeys, err := p.resolveUserProviderAPIKeysForProviderType(ctx, currentChat.OwnerID, string(provider))
if err != nil {
return childSubagentChatOptions{}, err
}
if !userCanUseProviderKeys(providerKeys, string(provider)) {
return childSubagentChatOptions{}, xerrors.Errorf(
`API key for computer-use provider %q is not configured`,
provider,
)
}
return childSubagentChatOptions{
chatMode: database.NullChatMode{
ChatMode: database.ChatModeComputerUse,
Valid: true,
},
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 {
defs := allSubagentDefinitions()
available := make([]subagentDefinition, 0, len(defs))
for _, def := range defs {
if def.unavailableReasonText(ctx, p, currentChat) == "" {
available = append(available, def)
}
}
return available
}
func availableSubagentTypeIDs(
ctx context.Context,
p *Server,
currentChat database.Chat,
) []string {
defs := availableSubagentDefinitions(ctx, p, currentChat)
ids := make([]string, 0, len(defs))
for _, def := range defs {
ids = append(ids, def.id)
}
return ids
}
func (d subagentDefinition) unavailableReasonText(
ctx context.Context,
p *Server,
currentChat database.Chat,
) string {
if d.unavailableReason == nil {
return ""
}
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 {
return subagentDefinition{}, xerrors.Errorf(
"type must be one of: %s",
strings.Join(availableSubagentTypeIDs(ctx, p, currentChat), ", "),
)
}
if reason := def.unavailableReasonText(ctx, p, currentChat); 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 withSubagentType(result map[string]any, chat database.Chat) map[string]any {
if result == nil {
result = map[string]any{}
}
result["type"] = subagentTypeFromChat(chat)
return result
}
func subagentErrorResponse(err error, chat *database.Chat) fantasy.ToolResponse {
if chat == nil {
return fantasy.NewTextErrorResponse(err.Error())
}
return toolJSONErrorResponse(withSubagentType(map[string]any{
"error": err.Error(),
}, *chat))
}
func buildSpawnAgentDescription(
ctx context.Context,
p *Server,
currentChat database.Chat,
) string {
availableDefs := availableSubagentDefinitions(ctx, p, currentChat)
description := "Spawn a delegated child subagent to work on a clearly scoped, " +
"independent task in parallel. 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. Be careful when running parallel subagents: if two " +
"subagents modify the same files they will conflict with each other, " +
"so ensure parallel subagent tasks are independent. The child agent " +
"receives the same workspace tools but cannot spawn its own subagents. " +
"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 + "\". " +
"After spawning, use wait_agent to retrieve the result. 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
}
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,
) + "."
}