Files
coder/coderd/x/chatd/subagent.go
T
Ethan a0be9d0e1d feat: make message_agent always steer (#31175)
`message_agent` no longer takes an `interrupt` flag, and always steers.
If the child is busy, it gets the message before its next model call and
keeps working. To correct or redirect a busy child, the parent just
calls `message_agent`, and `interrupt_agent` only stops it, which is the
same split the API has after #31174. The tool result also drops
`interrupted`, as it was just whether the child was running before the
send.

That was the last caller of the interrupt busy behaviour, so chatd and
chatstate drop it too. `SendMessage` never interrupts now. On a busy
chat it only ever adds the message to a lane, so the sends that moved a
running chat to interrupting, or a `requires_action` chat back to
running, are gone, along with the send's inline interruption finish for
chats with no worker. Most of the diff is deleted tests.

A steer send to a paused chat, or to an errored chat whose next message
is being edited, no longer fails with a 429 at the queue limit when it's
delivered straight away, which is whenever the message being edited is a
queue message.

Part of CODAGT-1140
2026-11-09 15:55:17 +11:00

790 lines
28 KiB
Go

package chatd
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strings"
"time"
"charm.land/fantasy"
"github.com/google/uuid"
"github.com/sqlc-dev/pqtype"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/util/ptr"
"github.com/coder/coder/v2/coderd/x/agenthooks/dispatch"
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
"github.com/coder/coder/v2/codersdk"
)
var ErrSubagentNotDescendant = xerrors.New("target chat is not a descendant of current chat")
// ErrSubagentWaitTimeout is returned by awaitSubagentCompletion when the
// wait deadline elapses before the subagent reaches a terminal status. The
// agent is still working and the wait can be retried.
var ErrSubagentWaitTimeout = xerrors.New("timed out waiting for delegated subagent completion")
// subagentStatusError wraps a subagent that reached error status. It
// carries the chat and report so callers can surface a structured,
// recoverable-aware payload instead of a bare tool error.
type subagentStatusError struct {
chat database.Chat
report string
reason string
}
func (e *subagentStatusError) Error() string { return e.reason }
const (
subagentAwaitPollInterval = 200 * time.Millisecond
subagentAwaitFallbackPoll = 5 * time.Second
defaultSubagentWaitTimeout = 5 * time.Minute
defaultListAgentsLimit = 10
maxListAgentsLimit = 50
subagentRecordingStopTimeout = 90 * time.Second
)
// computerUseSubagentSystemPrompt is the system prompt prepended to
// every computer use subagent chat. It instructs the model on how to
// interact with the desktop environment via the computer tool.
const computerUseSubagentSystemPrompt = `You are a computer use agent with access to a desktop environment. You can see the screen, move the mouse, click, type, scroll, and drag.
Your primary tool is the "computer" tool which lets you interact with the desktop. After every action you take, you will receive a screenshot showing the current state of the screen. Use these screenshots to verify your actions and plan next steps.
Guidelines:
- Always start by taking a screenshot to see the current state of the desktop.
- Use wait or ordinary actions when you only need a screenshot for your own reasoning.
- Use an explicit screenshot action when you want to share a durable screenshot with the user; those screenshots are attached to the chat automatically.
- Be precise with coordinates when clicking or typing.
- Wait for UI elements to load before interacting with them.
- If an action doesn't produce the expected result, try alternative approaches.
- Report what you accomplished when done.`
type waitAgentArgs struct {
ChatID string `json:"chat_id"`
TimeoutSeconds *int `json:"timeout_seconds,omitempty" description:"Defaults to 5 minutes."`
}
type messageAgentArgs struct {
ChatID string `json:"chat_id"`
Message string `json:"message"`
}
type interruptAgentArgs struct {
ChatID string `json:"chat_id"`
}
type listAgentsArgs struct {
Limit *int `json:"limit,omitempty"`
Offset *int `json:"offset,omitempty"`
}
type listSubagentModelsArgs struct{}
func subagentModelOverrideLogLabel(
overrideContext codersdk.ChatModelOverrideContext,
) string {
switch overrideContext {
case codersdk.ChatModelOverrideContextGeneral:
return "general delegated child"
case codersdk.ChatModelOverrideContextExplore:
return "explore"
default:
return string(overrideContext)
}
}
func personalModelOverrideContextForSubagent(
overrideContext codersdk.ChatModelOverrideContext,
) (codersdk.ChatPersonalModelOverrideContext, error) {
switch overrideContext {
case codersdk.ChatModelOverrideContextGeneral:
return codersdk.ChatPersonalModelOverrideContextGeneral, nil
case codersdk.ChatModelOverrideContextExplore:
return codersdk.ChatPersonalModelOverrideContextExplore, nil
default:
return "", xerrors.Errorf(
"unknown subagent model override context %q",
overrideContext,
)
}
}
func (p *Server) resolvePersonalSubagentModelConfigID(
ctx context.Context,
ownerID uuid.UUID,
organizationID uuid.UUID,
overrideContext codersdk.ChatModelOverrideContext,
) (uuid.UUID, *string, bool, error) {
personalContext, err := personalModelOverrideContextForSubagent(overrideContext)
if err != nil {
return uuid.Nil, nil, false, err
}
override, err := p.db.GetChatUserModelOverride(ctx, database.GetChatUserModelOverrideParams{
UserID: ownerID,
OrganizationID: organizationID,
Context: string(personalContext),
})
if err != nil {
if !xerrors.Is(err, sql.ErrNoRows) {
return uuid.Nil, nil, false, xerrors.Errorf(
"get %s personal model override: %w",
subagentModelOverrideLogLabel(overrideContext),
err,
)
}
return uuid.Nil, nil, false, nil
}
switch codersdk.ChatPersonalModelOverrideMode(override.Mode) {
case codersdk.ChatPersonalModelOverrideModeChatDefault:
return uuid.Nil, nil, true, nil
case codersdk.ChatPersonalModelOverrideModeDeploymentDefault:
case codersdk.ChatPersonalModelOverrideModeModel:
if !override.ModelConfigID.Valid {
p.logger.Warn(ctx,
"personal model override has no model config, using deployment default",
slog.F("override_context", overrideContext),
slog.F("owner_id", ownerID),
)
break
}
modelConfig, ok, err := p.resolvePersonalModelOverride(
ctx,
overrideContext,
ownerID,
override.ModelConfigID.UUID,
)
if err != nil {
return uuid.Nil, nil, false, err
}
if ok {
return modelConfig.ID, ptr.FromNullString(override.ReasoningEffort), true, nil
}
default:
p.logger.Warn(ctx,
"unsupported personal model override mode, using deployment default",
slog.F("override_context", overrideContext),
slog.F("owner_id", ownerID),
slog.F("mode", override.Mode),
)
}
return uuid.Nil, nil, false, nil
}
func (p *Server) resolvePersonalModelOverride(
ctx context.Context,
overrideContext codersdk.ChatModelOverrideContext,
ownerID uuid.UUID,
modelConfigID uuid.UUID,
) (database.ChatModelConfig, bool, error) {
modelConfig, providerName, err := p.resolveModelConfigAndNormalizedProvider(ctx, ownerID, modelConfigID)
if err != nil {
if !modelConfigUnavailable(err) {
return database.ChatModelConfig{}, false, xerrors.Errorf(
"resolve %s personal model override %s: %w",
subagentModelOverrideLogLabel(overrideContext),
modelConfigID,
err,
)
}
p.logger.Debug(ctx,
"personal model override is unavailable, using deployment default",
slog.F("override_context", overrideContext),
slog.F("owner_id", ownerID),
slog.F("model_config_id", modelConfigID),
slog.Error(err),
)
return database.ChatModelConfig{}, false, nil
}
providerKeys, err := p.resolveUserProviderAPIKeys(ctx, ownerID, modelConfigAIProviderID(modelConfig))
if err != nil {
return database.ChatModelConfig{}, false, xerrors.Errorf("resolve provider API keys: %w", err)
}
if !userCanUseProviderKeys(providerKeys, providerName) {
p.logger.Debug(ctx,
"personal model override credentials are unavailable, using deployment default",
slog.F("override_context", overrideContext),
slog.F("owner_id", ownerID),
slog.F("model_config_id", modelConfigID),
slog.F("provider", providerName),
)
return database.ChatModelConfig{}, false, nil
}
return modelConfig, true, nil
}
func (p *Server) resolveSubagentModelConfigID(
ctx context.Context,
ownerID uuid.UUID,
organizationID uuid.UUID,
overrideContext codersdk.ChatModelOverrideContext,
) (uuid.UUID, *string, error) {
//nolint:gocritic // Chatd needs its scoped config and user-data access here.
chatdCtx := dbauthz.AsChatd(ctx)
personalOverridesEnabled, err := p.db.GetChatPersonalModelOverridesEnabled(chatdCtx)
if err != nil {
return uuid.Nil, nil, xerrors.Errorf("get chat personal model overrides enabled: %w", err)
}
if personalOverridesEnabled {
modelConfigID, reasoningEffort, resolved, err := p.resolvePersonalSubagentModelConfigID(
chatdCtx,
ownerID,
organizationID,
overrideContext,
)
if err != nil {
return uuid.Nil, nil, err
}
if resolved {
return modelConfigID, reasoningEffort, nil
}
}
switch overrideContext {
case codersdk.ChatModelOverrideContextGeneral,
codersdk.ChatModelOverrideContextExplore:
default:
return uuid.Nil, nil, xerrors.Errorf(
"unsupported subagent model override context %q",
overrideContext,
)
}
resolved, err := p.resolveModelOverride(chatdCtx, modelOverrideSpec{
context: string(overrideContext),
ownerID: ownerID,
organizationID: organizationID,
})
if err != nil {
return uuid.Nil, nil, err
}
if !resolved.Set {
return uuid.Nil, nil, nil
}
return resolved.Config.ID, resolved.ReasoningEffort, nil
}
func (p *Server) resolveExplicitSpawnOverrides(
ctx context.Context,
ownerID uuid.UUID,
organizationID uuid.UUID,
args spawnAgentArgs,
) (*uuid.UUID, *string, error) {
var explicitModelConfigID *uuid.UUID
if raw := strings.TrimSpace(args.ModelConfigID); raw != "" {
modelConfigID, err := uuid.Parse(raw)
if err != nil {
return nil, nil, xerrors.New(
"invalid model_config_id: must be a valid UUID; use " +
listSubagentModelsToolName + " to see available models",
)
}
modelConfig, providerName, err := p.resolveModelConfigForOrganization(
ctx,
ownerID,
organizationID,
modelConfigID,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, nil, xerrors.New(
"model_config_id not found or is disabled; use " +
listSubagentModelsToolName + " to see available models",
)
case errors.Is(err, errInvalidModelOverrideMetadata):
return nil, nil, xerrors.Errorf(
"model_config_id metadata is invalid: %w",
err,
)
default:
p.logger.Warn(ctx, "failed to resolve spawn_agent model_config_id",
slog.F("model_config_id", modelConfigID),
slog.Error(err),
)
return nil, nil, xerrors.New("internal error looking up model config")
}
}
//nolint:gocritic // Provider credentials remain privileged Chatd reads.
providerKeys, err := p.resolveUserProviderAPIKeys(
dbauthz.AsChatd(ctx),
ownerID,
modelConfigAIProviderID(modelConfig),
)
if err != nil {
p.logger.Warn(ctx, "failed to resolve provider API keys for spawn_agent model_config_id",
slog.F("model_config_id", modelConfigID),
slog.Error(err),
)
return nil, nil, xerrors.New("internal error looking up model config")
}
if !userCanUseProviderKeys(providerKeys, providerName) {
return nil, nil, xerrors.Errorf(
"model_config_id credentials are unavailable for provider %q",
providerName,
)
}
explicitModelConfigID = &modelConfig.ID
}
var explicitReasoningEffort *string
if raw := strings.TrimSpace(args.ReasoningEffort); raw != "" {
effort := strings.ToLower(raw)
if !chatprovider.IsValidReasoningEffort(effort) {
return nil, nil, xerrors.Errorf(
"invalid reasoning_effort: must be one of %s",
strings.Join(codersdk.ChatModelReasoningEffortValues(), ", "),
)
}
explicitReasoningEffort = &effort
}
return explicitModelConfigID, explicitReasoningEffort, nil
}
func (p *Server) listSpawnableModelConfigs(
ctx context.Context,
ownerID uuid.UUID,
organizationID uuid.UUID,
) ([]map[string]any, error) {
modelCtx, err := p.callerModelConfigContext(ctx, ownerID)
if err != nil {
return nil, err
}
rows, err := enabledChatModelConfigsForOrganization(modelCtx, p.db, organizationID)
if err != nil {
return nil, xerrors.Errorf("get enabled chat model configs: %w", err)
}
models := make([]map[string]any, 0, len(rows))
providerKeysByID := make(map[uuid.UUID]chatprovider.ProviderAPIKeys)
for _, row := range rows {
providerName := chatprovider.NormalizeProvider(row.Provider)
if providerName == "" {
continue
}
if _, _, err := chatprovider.ResolveModelWithProviderHint(
row.ChatModelConfig.Model,
providerName,
); err != nil {
continue
}
providerID := modelConfigAIProviderID(row.ChatModelConfig)
providerKeys, ok := providerKeysByID[providerID]
if !ok {
//nolint:gocritic // Provider credentials remain privileged Chatd reads.
providerKeys, err = p.resolveUserProviderAPIKeys(
dbauthz.AsChatd(ctx),
ownerID,
providerID,
)
if err != nil {
return nil, xerrors.Errorf("resolve provider API keys: %w", err)
}
providerKeysByID[providerID] = providerKeys
}
if !userCanUseProviderKeys(providerKeys, providerName) {
continue
}
entry := map[string]any{
"model_config_id": row.ChatModelConfig.ID.String(),
"display_name": row.ChatModelConfig.DisplayName,
"model": row.ChatModelConfig.Model,
"provider": providerName,
"context_limit": row.ChatModelConfig.ContextLimit,
"is_default": row.ChatModelConfig.IsDefault,
}
callConfig := codersdk.ChatModelCallConfig{}
if len(row.ChatModelConfig.Options) > 0 {
if err := json.Unmarshal(row.ChatModelConfig.Options, &callConfig); err == nil {
if efforts := chatprovider.SelectableReasoningEfforts(callConfig.ReasoningEffort); len(efforts) > 0 {
entry["reasoning_efforts"] = efforts
}
}
}
models = append(models, entry)
}
return models, nil
}
func (p *Server) subagentTools(
ctx context.Context,
currentChat func() database.Chat,
currentModelConfigID uuid.UUID,
) ([]fantasy.AgentTool, error) {
currentChatSnapshot := database.Chat{}
if currentChat != nil {
currentChatSnapshot = currentChat()
}
spawnAgentDescription, err := buildSpawnAgentDescription(ctx, p, currentChatSnapshot)
if err != nil {
return nil, xerrors.Errorf("build spawn agent description: %w", err)
}
return []fantasy.AgentTool{
fantasy.NewAgentTool(
spawnAgentToolName,
spawnAgentDescription,
func(ctx context.Context, args spawnAgentArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
chat, err := p.spawnAgent(ctx, currentChat, currentChatSnapshot, currentModelConfigID, args)
// A failed hook dispatch must fail closed instead of
// degrading into a tool error the model can ignore.
if errors.As(err, new(*dispatch.Error)) {
return fantasy.ToolResponse{}, err
}
if err != nil {
// chathooks.UserPromptDeniedError.Error() carries the
// user-facing denial message, so the model can adjust its
// prompt.
return fantasy.NewTextErrorResponse(err.Error()), nil
}
return toolJSONResponse(subagentChatResult(chat)), nil
},
),
fantasy.NewAgentTool(
listSubagentModelsToolName,
"List the enabled model configurations available for "+
spawnAgentToolName+"'s model_config_id argument. Only models "+
"usable with the chat owner's credentials are returned. Each "+
"entry includes model_config_id, display_name, model, "+
"provider, context_limit, is_default, and reasoning_efforts "+
"(the values accepted by "+spawnAgentToolName+"'s "+
"reasoning_effort for that model).",
func(ctx context.Context, _ listSubagentModelsArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
parent, err := p.loadSubagentSpawnParentChat(ctx, currentChat)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
models, err := p.listSpawnableModelConfigs(ctx, parent.OwnerID, parent.OrganizationID)
if err != nil {
p.logger.Warn(ctx, "failed to list spawnable model configs", slog.F("chat_id", parent.ID), slog.Error(err))
return fantasy.NewTextErrorResponse("internal error listing model configs"), nil
}
return toolJSONResponse(map[string]any{"models": models}), nil
},
),
fantasy.NewAgentTool(
"wait_agent",
"Wait for a spawned child agent to finish and return its response "+
"and status. Returns immediately when the agent finishes, even if "+
"a longer timeout is set. A timeout does not stop the child; it "+
"still owns its task. Wait again or check its status with "+
"list_agents; do not take over its work without an acknowledged "+
"handoff. A timeout with status paused means the child's owner is "+
"editing one of its queued messages; the child continues when the "+
"edit ends, so keep waiting unless the owner says otherwise.",
func(ctx context.Context, args waitAgentArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
targetChatID, err := parseSubagentToolChatID(args.ChatID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
timeout := defaultSubagentWaitTimeout
if args.TimeoutSeconds != nil {
timeout = time.Duration(*args.TimeoutSeconds) * time.Second
}
targetChatInfo := p.subagentTargetChatInfo(ctx, targetChatID, "wait")
outcome, err := p.awaitSubagent(ctx, currentChat(), targetChatID, timeout)
if statusErr, ok := errors.AsType[*subagentStatusError](err); ok {
return toolJSONResponse(subagentAwaitStatusErrorResult(statusErr)), nil
}
if err != nil {
return subagentErrorResponse(err, targetChatInfo), nil
}
return toolJSONResponse(waitAgentResult(outcome)), nil
},
),
fantasy.NewAgentTool(
"message_agent",
"Send a follow-up message to a previously spawned child "+
"agent. If the agent is idle, it starts a new turn. If it "+
"is busy, the message is delivered before its next model "+
"call, and its current work continues. Use wait_agent to "+
"collect the child's response. A handoff is "+
"acknowledged only when wait_agent returns the child's "+
"response to your handoff message; a message_agent result is "+
"not an acknowledgment.",
func(ctx context.Context, args messageAgentArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
targetChatID, err := parseSubagentToolChatID(args.ChatID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
targetChatInfo := p.subagentTargetChatInfo(ctx, targetChatID, "message")
chat, err := p.sendSubagentMessage(ctx, currentChat().ID, targetChatID, args.Message)
if err != nil {
return subagentErrorResponse(err, targetChatInfo), nil
}
return toolJSONResponse(subagentChatResult(chat)), nil
},
),
fantasy.NewAgentTool(
"interrupt_agent",
"Interrupt a spawned child agent's current work. The "+
"status may briefly read interrupting before transitioning "+
"to waiting, running if there are queued messages, or "+
"paused if its owner is editing its next queued message. "+
"Use it only to stop the child. To send a message to a "+
"busy child, call message_agent; do not interrupt the "+
"child first.",
func(ctx context.Context, args interruptAgentArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
targetChatID, err := parseSubagentToolChatID(args.ChatID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
targetChatInfo := p.subagentTargetChatInfo(ctx, targetChatID, "interrupt")
chat, interrupted, err := p.interruptSubagent(ctx, currentChat().ID, targetChatID)
if err != nil {
return subagentErrorResponse(err, targetChatInfo), nil
}
return toolJSONResponse(subagentActionResult(chat, interrupted)), nil
},
),
fantasy.NewAgentTool(
"list_agents",
"List the child agents spawned by this chat, most recently "+
"active first. Returns up to `limit` agents (default 10) "+
"with `total` and `has_more`; use `offset` to page. The "+
"sort order is best-effort: an agent's position may shift "+
"if its updated_at changes between calls. Each "+
"agent has chat_id, title, type, status, created_at, "+
"updated_at. Status: running = working, "+
"interrupting = transient, waiting = idle, "+
"error = stopped on error, paused = waiting for its owner "+
"to finish editing a queued message.",
func(ctx context.Context, args listAgentsArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if currentChat == nil {
return fantasy.NewTextErrorResponse("subagent callbacks are not configured"), nil
}
limit := defaultListAgentsLimit
if args.Limit != nil {
limit = min(max(*args.Limit, 1), maxListAgentsLimit)
}
offset := 0
if args.Offset != nil && *args.Offset > 0 {
offset = *args.Offset
}
parent := currentChat()
if parent.ParentChatID.Valid {
return fantasy.NewTextErrorResponse("list_agents is only available on root chats"), nil
}
children, err := p.listSubagents(ctx, parent.ID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
return toolJSONResponse(listAgentsResult(children, offset, limit)), nil
},
),
}, nil
}
// turnParent preserves the parent turn's MCP tool snapshot for Explore children.
func (p *Server) spawnAgent(
ctx context.Context,
currentChat func() database.Chat,
turnParent database.Chat,
currentModelConfigID uuid.UUID,
args spawnAgentArgs,
) (database.Chat, error) {
parent, err := p.loadSubagentSpawnParentChat(ctx, currentChat)
if err != nil {
return database.Chat{}, err
}
definition, err := resolveSubagentDefinition(ctx, p, parent, args.Type)
if err != nil {
return database.Chat{}, err
}
if definition.id == subagentTypeComputerUse && (strings.TrimSpace(args.ModelConfigID) != "" || strings.TrimSpace(args.ReasoningEffort) != "") {
return database.Chat{}, xerrors.New("model_config_id and reasoning_effort are not supported for type \"" + subagentTypeComputerUse + "\"")
}
explicitModelConfigID, explicitReasoningEffort, err := p.resolveExplicitSpawnOverrides(ctx, parent.OwnerID, parent.OrganizationID, args)
if err != nil {
return database.Chat{}, err
}
if turnParent.ID == uuid.Nil {
turnParent = parent
}
options, err := definition.buildOptions(ctx, p, parent, turnParent, currentModelConfigID, explicitModelConfigID, args.Prompt)
if err != nil {
return database.Chat{}, err
}
if explicitReasoningEffort != nil {
options.reasoningEffortOverride = explicitReasoningEffort
}
return p.createChildSubagentChatWithOptions(ctx, parent, args.Prompt, args.Title, options)
}
func parseSubagentToolChatID(raw string) (uuid.UUID, error) {
chatID, err := uuid.Parse(strings.TrimSpace(raw))
if err != nil {
return uuid.Nil, xerrors.New("chat_id must be a valid UUID")
}
return chatID, nil
}
// Tool outputs keep fields in sorted JSON key order so the payload text
// the model sees stays stable.
type subagentAwaitResult struct {
ChatID string `json:"chat_id"`
LastError string `json:"last_error,omitempty"`
LastErrorDetail string `json:"last_error_detail,omitempty"`
LastErrorKind string `json:"last_error_kind,omitempty"`
LastErrorRetryable *bool `json:"last_error_retryable,omitempty"`
RecordingFileID string `json:"recording_file_id,omitempty"`
Report *string `json:"report,omitempty"`
Status string `json:"status"`
ThumbnailFileID string `json:"thumbnail_file_id,omitempty"`
TimedOut bool `json:"timed_out,omitempty"`
Title string `json:"title"`
Type string `json:"type"`
}
type subagentListEntry struct {
ChatID string `json:"chat_id"`
CreatedAt string `json:"created_at"`
Status string `json:"status"`
Title string `json:"title"`
Type string `json:"type"`
UpdatedAt string `json:"updated_at"`
}
type subagentListResult struct {
Agents []subagentListEntry `json:"agents"`
HasMore bool `json:"has_more"`
Offset int `json:"offset"`
Returned int `json:"returned"`
Total int `json:"total"`
}
func subagentChatResult(chat database.Chat) any {
return struct {
ChatID string `json:"chat_id"`
Status string `json:"status"`
Title string `json:"title"`
Type string `json:"type"`
}{
ChatID: chat.ID.String(), Status: string(chat.Status),
Title: chat.Title, Type: subagentTypeFromChat(chat),
}
}
func subagentActionResult(chat database.Chat, interrupted bool) any {
return struct {
ChatID string `json:"chat_id"`
Interrupted bool `json:"interrupted"`
Status string `json:"status"`
Title string `json:"title"`
Type string `json:"type"`
}{
ChatID: chat.ID.String(), Interrupted: interrupted, Status: string(chat.Status),
Title: chat.Title, Type: subagentTypeFromChat(chat),
}
}
func waitAgentResult(outcome subagentAwaitOutcome) subagentAwaitResult {
chat := outcome.chat
result := subagentAwaitResult{ChatID: chat.ID.String(), Status: string(chat.Status), Title: chat.Title, Type: subagentTypeFromChat(chat)}
if outcome.timedOut {
result.TimedOut = true
return result
}
result.RecordingFileID = outcome.recording.recordingFileID
result.Report = &outcome.report
result.ThumbnailFileID = outcome.recording.thumbnailFileID
return result
}
func subagentAwaitStatusErrorResult(statusErr *subagentStatusError) subagentAwaitResult {
chat := statusErr.chat
decoded, lastError := subagentLastError(chat.LastError)
if lastError == "" {
lastError = statusErr.reason
}
result := subagentAwaitResult{ChatID: chat.ID.String(), LastError: lastError, Report: &statusErr.report, Status: string(chat.Status), Title: chat.Title, Type: subagentTypeFromChat(chat)}
if decoded != nil {
kind := decoded.Kind
if kind == "" {
kind = codersdk.ChatErrorKindGeneric
}
retryable := decoded.Retryable
result.LastErrorKind = string(kind)
result.LastErrorRetryable = &retryable
result.LastErrorDetail = decoded.Detail
}
return result
}
// subagentGenericErrorMessage matches the normalized fallback that
// chaterror and db2sdk emit for unclassifiable failures. It carries no
// actionable information, so a provider detail replaces it entirely.
const subagentGenericErrorMessage = "The chat request failed unexpectedly."
// subagentLastError decodes a chat's last_error payload and builds the
// message surfaced to the parent model, preferring the actionable
// provider detail. The content mirrors what the chat UI renders from
// the same payload. An unrecognized payload yields an empty message so
// the caller falls back to its own status reason instead of exposing
// raw stored bytes.
func subagentLastError(raw pqtype.NullRawMessage) (*codersdk.ChatError, string) {
if !raw.Valid {
return nil, ""
}
var payload codersdk.ChatError
if err := json.Unmarshal(raw.RawMessage, &payload); err != nil {
return nil, ""
}
switch {
case payload.Message == "" && payload.Detail == "":
return nil, ""
case payload.Detail == "":
return &payload, payload.Message
case payload.Message == "" || payload.Message == subagentGenericErrorMessage:
return &payload, payload.Detail
default:
return &payload, payload.Message + " (" + payload.Detail + ")"
}
}
func listAgentsResult(children []database.Chat, offset, limit int) subagentListResult {
total := len(children)
start := min(offset, total)
end := min(start+limit, total)
agents := make([]subagentListEntry, 0, end-start)
for _, chat := range children[start:end] {
agents = append(agents, subagentListEntry{ChatID: chat.ID.String(), CreatedAt: chat.CreatedAt.Format(time.RFC3339), Status: string(chat.Status), Title: chat.Title, Type: subagentTypeFromChat(chat), UpdatedAt: chat.UpdatedAt.Format(time.RFC3339)})
}
return subagentListResult{Agents: agents, HasMore: end < total, Offset: offset, Returned: len(agents), Total: total}
}
func toolJSONResponse(result any) fantasy.ToolResponse {
data, err := json.Marshal(result)
if err != nil {
return fantasy.NewTextResponse("{}")
}
return fantasy.NewTextResponse(string(data))
}
func toolJSONErrorResponse(result map[string]any) fantasy.ToolResponse {
resp := toolJSONResponse(result)
resp.IsError = true
return resp
}