mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
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.
273 lines
7.4 KiB
Go
273 lines
7.4 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/audit"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
dbpubsub "github.com/coder/coder/v2/coderd/database/pubsub"
|
|
"github.com/coder/coder/v2/coderd/notifications"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/messagepartbuffer"
|
|
"github.com/coder/quartz"
|
|
)
|
|
|
|
const (
|
|
defaultAcquisitionInterval = 30 * time.Second
|
|
defaultAcquisitionBatchSize = int32(10)
|
|
defaultRunnerSyncInterval = 15 * time.Second
|
|
defaultHeartbeatInterval = 9 * time.Second
|
|
defaultHeartbeatCleanupEvery = 30 * time.Second
|
|
defaultHeartbeatStaleSeconds = int32(30)
|
|
// The archive cutoff is based on UTC start-of-day and only moves
|
|
// once per day, so hourly runs are more than enough to keep up
|
|
// while still catching chats that cross the threshold shortly
|
|
// after midnight.
|
|
defaultArchiveInterval = time.Hour
|
|
defaultArchiveBatchSize = int32(1000)
|
|
defaultStateChannelSize = 64
|
|
defaultTaskRetryInitialBackoff = 100 * time.Millisecond
|
|
defaultTaskRetryMaxBackoff = 5 * time.Second
|
|
)
|
|
|
|
// chatWorkerPubsub is the chat worker pubsub dependency.
|
|
type chatWorkerPubsub interface {
|
|
Publish(event string, message []byte) error
|
|
SubscribeWithErr(event string, listener dbpubsub.ListenerWithErr) (func(), error)
|
|
}
|
|
|
|
// chatWorkerTaskStarter starts runner-owned side-effect tasks.
|
|
type chatWorkerTaskStarter interface {
|
|
StartGeneration(context.Context, chatWorkerTaskStartInput) error
|
|
StartInterrupt(context.Context, chatWorkerTaskStartInput) error
|
|
StartRequiresActionTimeout(context.Context, chatWorkerTaskStartInput) error
|
|
StartAbandon(context.Context, chatWorkerTaskStartInput) error
|
|
}
|
|
|
|
// chatWorkerTaskStartInput describes one runner task invocation.
|
|
type chatWorkerTaskStartInput struct {
|
|
TaskID uuid.UUID
|
|
ChatID uuid.UUID
|
|
// TurnID is a process-local correlation ID minted per generation
|
|
// task run. It groups the run's hook events; it is best-effort only
|
|
// and never persisted.
|
|
TurnID uuid.UUID
|
|
WorkerID uuid.UUID
|
|
RunnerID uuid.UUID
|
|
HistoryVersion int64
|
|
GenerationAttempt int64
|
|
Status database.ChatStatus
|
|
RequiresActionDeadlineAt sql.NullTime
|
|
DebugTurn *runnerDebugTurn
|
|
SessionStart *sessionStartTracker
|
|
StopNudges *stopNudgeTracker
|
|
}
|
|
|
|
func (i chatWorkerTaskStartInput) hookTurnID() *uuid.UUID {
|
|
if i.TurnID == uuid.Nil {
|
|
return nil
|
|
}
|
|
turnID := i.TurnID
|
|
return &turnID
|
|
}
|
|
|
|
// stopNudgeTracker allows at most one stop-hook nudge continuation per
|
|
// turn. Turns are keyed by the last user prompt's message ID so the
|
|
// claim survives task restarts, which mint fresh process-local turn
|
|
// IDs.
|
|
type stopNudgeTracker struct {
|
|
mu sync.Mutex
|
|
turnKey int64
|
|
claimed bool
|
|
pending bool
|
|
}
|
|
|
|
// stopNudgeKey identifies the current turn by its prompt row. Model
|
|
// visibility user rows are hook context, not prompts.
|
|
func stopNudgeKey(messages []database.ChatMessage) int64 {
|
|
index := lastUserPromptIndex(messages)
|
|
if index == -1 {
|
|
return 0
|
|
}
|
|
return messages[index].ID
|
|
}
|
|
|
|
func (t *stopNudgeTracker) claim(turnKey int64) bool {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if t.turnKey != turnKey {
|
|
t.turnKey = turnKey
|
|
t.claimed = false
|
|
}
|
|
if t.claimed {
|
|
return false
|
|
}
|
|
t.claimed = true
|
|
t.pending = true
|
|
return true
|
|
}
|
|
|
|
func (t *stopNudgeTracker) consume(turnKey int64) bool {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if t.turnKey != turnKey || !t.pending {
|
|
return false
|
|
}
|
|
t.pending = false
|
|
return true
|
|
}
|
|
|
|
func (t *stopNudgeTracker) cancel(turnKey int64) {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if t.turnKey != turnKey || !t.pending {
|
|
return
|
|
}
|
|
t.pending = false
|
|
t.claimed = false
|
|
}
|
|
|
|
func (t *stopNudgeTracker) reset() {
|
|
t.mu.Lock()
|
|
t.turnKey = 0
|
|
t.claimed = false
|
|
t.pending = false
|
|
t.mu.Unlock()
|
|
}
|
|
|
|
type sessionStartTracker struct {
|
|
mu sync.Mutex
|
|
completed bool
|
|
inFlight chan struct{}
|
|
}
|
|
|
|
func (t *sessionStartTracker) claim(ctx context.Context) (bool, func(bool), error) {
|
|
for {
|
|
t.mu.Lock()
|
|
if t.completed {
|
|
t.mu.Unlock()
|
|
return false, nil, nil
|
|
}
|
|
if t.inFlight == nil {
|
|
t.inFlight = make(chan struct{})
|
|
t.mu.Unlock()
|
|
return true, func(completed bool) {
|
|
t.mu.Lock()
|
|
t.completed = completed
|
|
close(t.inFlight)
|
|
t.inFlight = nil
|
|
t.mu.Unlock()
|
|
}, nil
|
|
}
|
|
inFlight := t.inFlight
|
|
t.mu.Unlock()
|
|
select {
|
|
case <-inFlight:
|
|
case <-ctx.Done():
|
|
return false, nil, ctx.Err()
|
|
}
|
|
}
|
|
}
|
|
|
|
// chatWorkerOptions configures a chatWorker.
|
|
type chatWorkerOptions struct {
|
|
WorkerID uuid.UUID
|
|
|
|
Store database.Store
|
|
Pubsub chatWorkerPubsub
|
|
Logger slog.Logger
|
|
Clock quartz.Clock
|
|
TaskStarter chatWorkerTaskStarter
|
|
MessagePartBuffer *messagepartbuffer.Buffer
|
|
|
|
NotificationsEnqueuer notifications.Enqueuer
|
|
Auditor *atomic.Pointer[audit.Auditor]
|
|
AutoArchiveRecords prometheus.Counter
|
|
|
|
AcquisitionInterval time.Duration
|
|
AcquisitionBatchSize int32
|
|
ArchiveInterval time.Duration
|
|
ArchiveBatchSize int32
|
|
RunnerSyncInterval time.Duration
|
|
HeartbeatInterval time.Duration
|
|
HeartbeatCleanupInterval time.Duration
|
|
HeartbeatStaleSeconds int32
|
|
StateChannelSize int
|
|
RunnerManagerChannelSize int
|
|
AcquisitionWakeChannelSize int
|
|
TaskRetryInitialBackoff time.Duration
|
|
TaskRetryMaxBackoff time.Duration
|
|
}
|
|
|
|
func (o chatWorkerOptions) withDefaults() (chatWorkerOptions, error) {
|
|
if o.Store == nil {
|
|
return chatWorkerOptions{}, xerrors.New("chatworker: store is required")
|
|
}
|
|
if o.Pubsub == nil {
|
|
return chatWorkerOptions{}, xerrors.New("chatworker: pubsub is required")
|
|
}
|
|
if o.TaskStarter == nil && o.MessagePartBuffer == nil {
|
|
return chatWorkerOptions{}, xerrors.New("chatworker: task starter or message part buffer is required")
|
|
}
|
|
if o.WorkerID == uuid.Nil {
|
|
return chatWorkerOptions{}, xerrors.New("chatworker: worker ID is required")
|
|
}
|
|
if o.Clock == nil {
|
|
o.Clock = quartz.NewReal()
|
|
}
|
|
if o.AcquisitionInterval <= 0 {
|
|
o.AcquisitionInterval = defaultAcquisitionInterval
|
|
}
|
|
if o.AcquisitionBatchSize <= 0 {
|
|
o.AcquisitionBatchSize = defaultAcquisitionBatchSize
|
|
}
|
|
if o.ArchiveInterval <= 0 {
|
|
o.ArchiveInterval = defaultArchiveInterval
|
|
}
|
|
if o.ArchiveBatchSize <= 0 {
|
|
o.ArchiveBatchSize = defaultArchiveBatchSize
|
|
}
|
|
if o.NotificationsEnqueuer == nil {
|
|
o.NotificationsEnqueuer = notifications.NewNoopEnqueuer()
|
|
}
|
|
if o.RunnerSyncInterval <= 0 {
|
|
o.RunnerSyncInterval = defaultRunnerSyncInterval
|
|
}
|
|
if o.HeartbeatInterval <= 0 {
|
|
o.HeartbeatInterval = defaultHeartbeatInterval
|
|
}
|
|
if o.HeartbeatCleanupInterval <= 0 {
|
|
o.HeartbeatCleanupInterval = defaultHeartbeatCleanupEvery
|
|
}
|
|
if o.HeartbeatStaleSeconds <= 0 {
|
|
o.HeartbeatStaleSeconds = defaultHeartbeatStaleSeconds
|
|
}
|
|
if o.StateChannelSize <= 0 {
|
|
o.StateChannelSize = defaultStateChannelSize
|
|
}
|
|
if o.RunnerManagerChannelSize <= 0 {
|
|
o.RunnerManagerChannelSize = defaultStateChannelSize
|
|
}
|
|
if o.AcquisitionWakeChannelSize <= 0 {
|
|
o.AcquisitionWakeChannelSize = 1
|
|
}
|
|
if o.TaskRetryInitialBackoff <= 0 {
|
|
o.TaskRetryInitialBackoff = defaultTaskRetryInitialBackoff
|
|
}
|
|
if o.TaskRetryMaxBackoff <= 0 {
|
|
o.TaskRetryMaxBackoff = defaultTaskRetryMaxBackoff
|
|
}
|
|
if o.TaskRetryMaxBackoff < o.TaskRetryInitialBackoff {
|
|
o.TaskRetryMaxBackoff = o.TaskRetryInitialBackoff
|
|
}
|
|
return o, nil
|
|
}
|