Files
coder/coderd/x/chatd/hook_server.go
T
Michael Suchacz c17bed25e0 feat: wire chat lifecycle hooks into chatd (#27429)
Wires chat lifecycle hooks into chatd, gated by the
`agent-lifecycle-hooks` experiment. Part of the lifecycle hooks stack
(#27401, #27428, #27430). See `docs/admin/setup/chat-lifecycle-hooks.md`
for the consumer-facing contract.

## Summary

When a hook URL is configured, chatd dispatches `session_start`,
`user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_compact`,
`post_compact`, and `stop` events to the consumer and applies its
responses.

## Design

- **Stateless**: Coder stores no hook dispatch or decision state.
Delivery is at least once; consumers deduplicate on stable payload
identifiers (chat ID, event type, tool-use ID) and answer duplicates
with the same decision.
- **Admission-time prompt effects**: `user_prompt_submit` dispatches
exactly once per submission (create, send, queue, edit, subagent spawn)
and folds its effects into the stored prompt as typed message parts:
original-or-overridden user parts, then model-only `hook-context`, then
a user-visible `hook-notice`. Hook context is stripped from every
client-facing conversion; hook notices are excluded from model prompts.
The server rejects hook parts in client-submitted content.
- **Tool gating**: `pre_tool_use` allow can override tool input; deny
becomes a synthetic denied tool result, with any returned model context
persisted as a model-only transcript row so it never reaches clients.
The denial text identifies an external policy (the deployment's
lifecycle hook) as the source and marks the decision as persistent, so
the model explains the denial instead of retrying it or misreporting it
as an infrastructure failure.
- **Fail closed**: a dispatch failure rejects the triggering request or
moves the chat to the error state in the same transaction as the
affected step, so a runnable state is never published with unapproved
content.
- **Admission before persistence**: `pre_tool_use` is dispatched for the
calls the model produced, before the assistant message is stored. See
"Staged tool admission" below.
- **Fresh dispatch per tool call**: every non-provider-executed tool
call is decided by its own `pre_tool_use` dispatch; Coder never reuses
an earlier decision on the consumer's behalf. Retries re-dispatch the
same logical event.

## Structure

All hook dispatch flows through one seam: entry points build a
`chathooks.Chat` (chat identity) and a `chathooks.Message` (event
details) and call `Trigger.Trigger`, the only component that talks to
the dispatcher. The integration lives in the `coderd/x/chatd/chathooks`
subpackage, split by responsibility:

- `trigger.go`: the trigger seam; builds the wire envelope per event,
normalizes deny into a typed error, and holds the package's single
enabled-check.
- `effects.go`: pure conversion of hook results into transcript rows and
prompt parts.
- `errors.go`: failure classification (dispatch error messages, denial
mapping, tool-result dispatch-failure scanning).
- `tooluse.go`: the tool-call gate (`pre_tool_use` preflight,
`post_tool_use` payloads, applying admitted input to the step).

Server-bound glue stays in `coderd/x/chatd/hook_server.go`: the
chat-parking dispatch error handlers, the step-commit row insertion
wrappers, and the dynamic post-tool-use state loader, which depends on
chatd validation types.

This PR adopts the `codersdk/x/agenthooks` and
`coderd/x/agenthooks/dispatch` import paths introduced at the tip of
#27401; intermediate commits still reference the pre-move paths and are
not individually buildable.

## Staged tool admission

`pre_tool_use` originally ran at tool execution time, which is after the
assistant message carrying the tool call was already committed. An
`input_override` therefore had to rewrite stored message content in
place. @hugodutka pointed out that chatd treats message content as
immutable, and that the rewrite was a shortcut rather than a
requirement.

It was also a correctness problem in its own right: the rewrite only
updated the database, so the transcript could show one input while a
different one had executed.

The hook now runs before the step is persisted:

```text
provider stream ends (tool calls complete, in memory)
  -> pre_tool_use dispatch per call
  -> ONE transaction: assistant row with admitted inputs, synthetic denials, hook rows
  -> execute
```

The step is inserted once, carrying the input the tool runs with.
`UpdateChatMessageContentByID` and `Tx.UpdateMessageContent` are deleted
from #27428, so message content stays immutable.

Two consequences, both intentional:

- **Clients converge rather than wait.** Tool-call parts still stream
live, so a rewritten call briefly shows the model's proposed input
before the committed message replaces it. The chat store already clears
stream state when an assistant message arrives, so the stored input wins
with no frontend change and no added latency before tool cards appear.
- **A call already in history was already admitted.** Execution consumes
the stored input instead of dispatching a second decision, which keeps
one dispatch and one set of hook effects per call. A consumer policy
change between admission and execution applies to later calls, not to
calls already admitted.

The per-chat debug endpoint still records the provider's original tool
input. Its purpose is to report provider behavior, and it requires an
explicit per-chat debug flag; the invariant here covers the transcript.

## Configuration

Adds `chat-hook-url`, `chat-hook-secret`, `chat-hook-timeout`, and
`chat-hook-enabled` deployment options with startup validation. The
flags are hidden from `coder server --help` while the feature is
experimental; the setup guide documents them.

## Tool input validation

Built-in tool arguments reach a consumer as raw JSON with key spelling
preserved, but the tools decode those bytes with Go, which matches
struct fields case-insensitively and keeps the last match. A policy
reading `path` could therefore authorize one value while the tool
executed another, and a lone case variant such as `{"PATH":"/secret"}`
was invisible to a policy checking for `path`.

Coder now rejects a built-in tool call whose input repeats a key or
spells a schema property with different capitalization, before the
`pre_tool_use` dispatch, so a consumer is never asked to authorize bytes
whose meaning depends on the reader. Rejected calls produce an error
result the model can retry; unambiguous calls in the same batch still
run. A consumer-authored `input_override` is rechecked after the
dispatch and fails the turn closed, because the model cannot correct it.
Dynamic and MCP inputs are excluded because the client and the workspace
agent execute those calls rather than coderd.

Two paths needed more than a schema check. Execution resolves a
deprecated tool name to its canonical tool, so validation resolves
aliases first. The `edit_files` decoder also reads `search` and
`replace`, which its schema does not advertise, so those aliases are now
matched exactly and their case variants ignored.

A hook denial now returns a structured 403 carrying `kind:
"hook_denied"`, mirroring the dispatch-failure response that already
carries its own kind. Without it a client cannot tell a policy decision
apart from a generic failure, and the chat UI titled a denial "Request
failed". Adding a kind needs no migration: `ChatErrorKind` is persisted
only inside the JSONB `chats.last_error` column, whose decoder accepts
unknown kinds.

The hook docs also correct the tool-input convergence window. A batch
dispatches sequentially before the assistant row commits, so the
original input stays visible for a span that scales with the number of
tool calls in the step rather than a single hook timeout.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 11:39:12 +00:00

188 lines
5.8 KiB
Go

package chatd
import (
"context"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/sqlc-dev/pqtype"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/x/chatd/chathooks"
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/x/agenthooks"
)
// applyHookResultMessages inserts hook event rows before the step's
// own rows so injected model context precedes the assistant content it
// steers; providers require tool results to directly follow the
// assistant tool calls.
func applyHookResultMessages(
messages stepMessagesForCommit,
results []*chathooks.Result,
modelConfigID uuid.UUID,
) (stepMessagesForCommit, error) {
return insertHookResultMessages(messages, results, modelConfigID, hookRowsBeforeStep)
}
func appendHookResultMessages(
messages stepMessagesForCommit,
results []*chathooks.Result,
modelConfigID uuid.UUID,
) (stepMessagesForCommit, error) {
return insertHookResultMessages(messages, results, modelConfigID, hookRowsAfterStep)
}
type hookRowPlacement int
const (
hookRowsBeforeStep hookRowPlacement = iota
hookRowsAfterStep
)
func insertHookResultMessages(
messages stepMessagesForCommit,
results []*chathooks.Result,
modelConfigID uuid.UUID,
placement hookRowPlacement,
) (stepMessagesForCommit, error) {
rows, err := chathooks.EventMessagesForResults(results, modelConfigID)
if err != nil {
return stepMessagesForCommit{}, err
}
if len(rows) > 0 {
if placement == hookRowsBeforeStep {
messages.Messages = append(rows, messages.Messages...)
} else {
messages.Messages = append(messages.Messages, rows...)
}
messages.VisibleIndexes = visibleMessageIndexes(messages.Messages)
}
return messages, nil
}
func (p *Server) handleUserPromptDispatchError(ctx context.Context, chatID uuid.UUID, dispatchErr error) error {
return p.handleAPIDispatchError(ctx, chatID, agenthooks.EventUserPromptSubmit, dispatchErr)
}
func (p *Server) handleAPIDispatchError(ctx context.Context, chatID uuid.UUID, eventType agenthooks.EventType, dispatchErr error) error {
lastError, ok := chathooks.DispatchErrorMessage(eventType, dispatchErr)
if !ok {
return dispatchErr
}
encoded, marshalErr := json.Marshal(codersdk.ChatError{
Message: lastError,
Kind: codersdk.ChatErrorKindHookDispatchFailed,
})
if marshalErr != nil {
return errors.Join(dispatchErr, xerrors.Errorf("encode hook dispatch error: %w", marshalErr))
}
var failedChat database.Chat
machine := p.newChatMachine(chatID)
err := machine.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
current, err := store.GetChatByID(ctx, chatID)
if err != nil {
return xerrors.Errorf("load chat for hook failure: %w", err)
}
// Park only idle chats. FinishError is also allowed from running
// states, but a running chat keeps its active turn and the
// request error alone surfaces to the caller.
if current.Status != database.ChatStatusWaiting {
return chatstate.ErrTransitionNotAllowed
}
if _, err := tx.FinishError(chatstate.FinishErrorInput{
LastError: pqtype.NullRawMessage{RawMessage: encoded, Valid: true},
}); err != nil {
return err
}
chat, err := store.GetChatByID(ctx, chatID)
if err != nil {
return xerrors.Errorf("reload chat after hook failure: %w", err)
}
failedChat = chat
return nil
})
if errors.Is(err, chatstate.ErrTransitionNotAllowed) {
return dispatchErr
}
if err != nil {
return errors.Join(dispatchErr, xerrors.Errorf("fail idle chat after hook dispatch: %w", err))
}
p.publishChatPubsubEvent(failedChat, codersdk.ChatWatchEventKindStatusChange, nil)
return dispatchErr
}
type dynamicPostToolUseState struct {
chat database.Chat
modelConfigID uuid.UUID
toolNames map[string]string
}
func loadDynamicPostToolUseState(
ctx context.Context,
machine *chatstate.ChatMachine,
opts SubmitToolResultsOptions,
) (dynamicPostToolUseState, error) {
var state dynamicPostToolUseState
err := machine.ReadLock(ctx, func(store database.Store) error {
chat, err := store.GetChatByID(ctx, opts.ChatID)
if err != nil {
return xerrors.Errorf("load chat: %w", err)
}
if chat.Archived {
return ErrChatArchived
}
if chat.Status != database.ChatStatusRequiresAction {
return &ToolResultStatusConflictError{ActualStatus: chat.Status}
}
messages, err := store.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
ChatID: opts.ChatID,
AfterID: 0,
})
if err != nil {
return xerrors.Errorf("load chat messages: %w", err)
}
_, pending, err := unresolvedToolCallsFromHistory(messages, dynamicToolNamesFromChat(chat))
if err != nil {
return xerrors.Errorf("load pending dynamic tool calls: %w", err)
}
toolNames := make(map[string]string, len(pending))
for _, call := range pending {
toolNames[call.ToolCallID] = call.ToolName
}
if err := validateSubmittedToolResults(opts.Results, toolNames); err != nil {
return err
}
modelConfigID := opts.ModelConfigID
if modelConfigID == uuid.Nil {
modelConfigID = chat.LastModelConfigID
}
state = dynamicPostToolUseState{
chat: chat,
modelConfigID: modelConfigID,
toolNames: toolNames,
}
return nil
})
return state, err
}
// validateSubmittedToolResults rejects invalid results before hook dispatch,
// using the same rules as CompleteRequiresAction.
func validateSubmittedToolResults(results []codersdk.ToolResult, toolNames map[string]string) error {
inputs := make([]chatstate.ToolResultInput, 0, len(results))
for _, result := range results {
inputs = append(inputs, chatstate.ToolResultInput{
ToolCallID: result.ToolCallID,
Output: result.Output,
})
}
if invalid := chatstate.ValidateToolResults(inputs, toolNames); invalid != nil {
return translateToolResultValidationError(invalid)
}
return nil
}