mirror of
https://github.com/coder/coder.git
synced 2026-09-23 14:03:57 +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.
361 lines
9.4 KiB
Go
361 lines
9.4 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
coderdpubsub "github.com/coder/coder/v2/coderd/pubsub"
|
|
)
|
|
|
|
type taskKind string
|
|
|
|
const (
|
|
taskKindGeneration taskKind = "generation"
|
|
taskKindInterrupt taskKind = "interrupt"
|
|
taskKindRequiresActionTimeout taskKind = "requires_action_timeout"
|
|
taskKindAbandon taskKind = "abandon"
|
|
)
|
|
|
|
type taskInstanceID uuid.UUID
|
|
|
|
type localWorkKey struct {
|
|
historyVersion int64
|
|
status database.ChatStatus
|
|
}
|
|
|
|
type taskIndexKey struct {
|
|
kind taskKind
|
|
key localWorkKey
|
|
}
|
|
|
|
type taskRecord struct {
|
|
id taskInstanceID
|
|
kind taskKind
|
|
localKey localWorkKey
|
|
cancel context.CancelFunc
|
|
done <-chan struct{}
|
|
}
|
|
|
|
type runner struct {
|
|
ctx context.Context
|
|
mgr *runnerManager
|
|
rec *runnerRecord
|
|
opts chatWorkerOptions
|
|
|
|
lastSnapshotVersion int64
|
|
hasAcceptedState bool
|
|
latestState runnerStateUpdate
|
|
|
|
activeTaskID taskInstanceID
|
|
activeTaskSet bool
|
|
tasks map[taskInstanceID]*taskRecord
|
|
tasksByIndex map[taskIndexKey]taskInstanceID
|
|
localLocks *localLockSet
|
|
debugTurn *runnerDebugTurn
|
|
sessionStart sessionStartTracker
|
|
stopNudges stopNudgeTracker
|
|
}
|
|
|
|
func newRunner(ctx context.Context, mgr *runnerManager, rec *runnerRecord, opts chatWorkerOptions) *runner {
|
|
return &runner{
|
|
ctx: ctx,
|
|
mgr: mgr,
|
|
rec: rec,
|
|
opts: opts,
|
|
tasks: make(map[taskInstanceID]*taskRecord),
|
|
tasksByIndex: make(map[taskIndexKey]taskInstanceID),
|
|
localLocks: newLocalLockSet(),
|
|
debugTurn: newRunnerDebugTurn(ctx, opts.Logger),
|
|
}
|
|
}
|
|
|
|
func (r *runner) run() {
|
|
if !r.bootstrap() {
|
|
return
|
|
}
|
|
for {
|
|
select {
|
|
case state := <-r.rec.stateCh:
|
|
r.processState(state)
|
|
case <-r.ctx.Done():
|
|
r.cancelActiveTask()
|
|
r.waitForTasks()
|
|
r.closeDebugTurn()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (r *runner) bootstrap() bool {
|
|
channel := coderdpubsub.ChatStateUpdateChannel(r.rec.key.ChatID)
|
|
unsubscribe, err := r.opts.Pubsub.SubscribeWithErr(channel, coderdpubsub.HandleChatStateUpdate(
|
|
func(ctx context.Context, payload coderdpubsub.ChatStateUpdateMessage, err error) {
|
|
if err != nil {
|
|
r.opts.Logger.Warn(ctx, "chatworker state update decode failed", slogError(err))
|
|
return
|
|
}
|
|
r.mgr.RouteStateHint(ctx, stateUpdateFromPubsub(r.rec.key.ChatID, payload))
|
|
},
|
|
))
|
|
if err != nil {
|
|
r.mgr.requestCleanup(r.ctx, r.rec.key)
|
|
return false
|
|
}
|
|
if !r.rec.setUnsubscribe(unsubscribe) {
|
|
return false
|
|
}
|
|
chat, err := r.opts.Store.GetChatByID(r.ctx, r.rec.key.ChatID)
|
|
if err != nil {
|
|
r.opts.Logger.Warn(r.ctx, "chatworker runner bootstrap failed", slogError(err))
|
|
r.mgr.requestCleanup(r.ctx, r.rec.key)
|
|
return false
|
|
}
|
|
// Apply the database snapshot directly instead of routing it through
|
|
// the manager. Routing fans out through stateCh, where a stale hint
|
|
// (for example the pre-acquisition chat:update relayed by another
|
|
// runner's subscription) could be processed first while
|
|
// lastSnapshotVersion is still zero. A stale unowned hint would make
|
|
// the runner clean itself up without abandoning the chat, leaving the
|
|
// chat owned by a dead runner until its heartbeat goes stale.
|
|
// Processing the snapshot here seeds lastSnapshotVersion before the
|
|
// run loop drains stateCh, so the dedup in processState drops every
|
|
// hint at or below this version regardless of delivery path.
|
|
r.processState(stateUpdateFromChat(chat))
|
|
return true
|
|
}
|
|
|
|
func stateUpdateFromPubsub(chatID uuid.UUID, payload coderdpubsub.ChatStateUpdateMessage) runnerStateUpdate {
|
|
return runnerStateUpdate{
|
|
ChatID: chatID,
|
|
WorkerID: payload.WorkerID,
|
|
RunnerID: payload.RunnerID,
|
|
SnapshotVersion: payload.SnapshotVersion,
|
|
HistoryVersion: payload.HistoryVersion,
|
|
QueueVersion: payload.QueueVersion,
|
|
GenerationAttempt: payload.GenerationAttempt,
|
|
Status: database.ChatStatus(payload.Status),
|
|
Archived: payload.Archived,
|
|
}
|
|
}
|
|
|
|
func (r *runner) processState(state runnerStateUpdate) {
|
|
if state.SnapshotVersion <= r.lastSnapshotVersion {
|
|
return
|
|
}
|
|
|
|
r.removeFinishedTasks()
|
|
|
|
if !uuidPtrEqual(state.WorkerID, r.rec.workerID) || !uuidPtrEqual(state.RunnerID, r.rec.key.RunnerID) {
|
|
r.acceptState(state)
|
|
r.mgr.requestCleanup(r.ctx, r.rec.key)
|
|
return
|
|
}
|
|
|
|
changed := !r.hasAcceptedState ||
|
|
r.latestState.HistoryVersion != state.HistoryVersion ||
|
|
r.latestState.Status != state.Status ||
|
|
r.latestState.Archived != state.Archived
|
|
if !changed {
|
|
r.acceptState(state)
|
|
return
|
|
}
|
|
if r.hasAcceptedState && r.activeTaskSet {
|
|
r.cancelActiveTask()
|
|
}
|
|
|
|
r.spawnForState(state)
|
|
r.acceptState(state)
|
|
}
|
|
|
|
func (r *runner) acceptState(state runnerStateUpdate) {
|
|
r.hasAcceptedState = true
|
|
r.latestState = state
|
|
r.lastSnapshotVersion = state.SnapshotVersion
|
|
}
|
|
|
|
func (r *runner) spawnForState(state runnerStateUpdate) {
|
|
if state.Archived {
|
|
r.spawnTaskIfNeeded(taskKindAbandon, state)
|
|
return
|
|
}
|
|
switch state.Status {
|
|
case database.ChatStatusRunning:
|
|
r.spawnTaskIfNeeded(taskKindGeneration, state)
|
|
case database.ChatStatusInterrupting:
|
|
r.spawnTaskIfNeeded(taskKindInterrupt, state)
|
|
case database.ChatStatusRequiresAction:
|
|
r.spawnTaskIfNeeded(taskKindRequiresActionTimeout, state)
|
|
case database.ChatStatusWaiting, database.ChatStatusError:
|
|
r.spawnTaskIfNeeded(taskKindAbandon, state)
|
|
default:
|
|
r.spawnTaskIfNeeded(taskKindAbandon, state)
|
|
}
|
|
}
|
|
|
|
func (r *runner) spawnTaskIfNeeded(kind taskKind, state runnerStateUpdate) {
|
|
key := localWorkKey{historyVersion: state.HistoryVersion, status: state.Status}
|
|
idx := taskIndexKey{kind: kind, key: key}
|
|
if r.activeTaskSet && r.tasksByIndex[idx] == r.activeTaskID {
|
|
return
|
|
}
|
|
|
|
id := taskInstanceID(uuid.New())
|
|
taskCtx, cancel := context.WithCancel(r.ctx)
|
|
done := make(chan struct{})
|
|
record := &taskRecord{
|
|
id: id,
|
|
kind: kind,
|
|
localKey: key,
|
|
cancel: cancel,
|
|
done: done,
|
|
}
|
|
r.tasks[id] = record
|
|
r.tasksByIndex[idx] = id
|
|
r.activeTaskID = id
|
|
r.activeTaskSet = true
|
|
|
|
input := chatWorkerTaskStartInput{
|
|
TaskID: uuid.UUID(id),
|
|
ChatID: r.rec.key.ChatID,
|
|
WorkerID: r.rec.workerID,
|
|
RunnerID: r.rec.key.RunnerID,
|
|
HistoryVersion: state.HistoryVersion,
|
|
GenerationAttempt: state.GenerationAttempt,
|
|
Status: state.Status,
|
|
RequiresActionDeadlineAt: state.RequiresActionDeadlineAt,
|
|
DebugTurn: r.debugTurn,
|
|
SessionStart: &r.sessionStart,
|
|
StopNudges: &r.stopNudges,
|
|
}
|
|
go r.runTask(taskCtx, kind, key, input, done)
|
|
}
|
|
|
|
func (r *runner) runTask(
|
|
ctx context.Context,
|
|
kind taskKind,
|
|
key localWorkKey,
|
|
input chatWorkerTaskStartInput,
|
|
done chan<- struct{},
|
|
) {
|
|
defer close(done)
|
|
taskInfo := retryWrapperTaskInfo{
|
|
ChatID: input.ChatID,
|
|
WorkerID: input.WorkerID,
|
|
RunnerID: input.RunnerID,
|
|
}
|
|
err := runTaskWithRetry(ctx, r.opts.retryOptions(), kind, taskInfo, func(ctx context.Context) error {
|
|
unlock, ok := r.localLocks.acquire(ctx, key)
|
|
if !ok {
|
|
return errors.Join(errTaskExpectedExit, xerrors.Errorf("runTask acquire local lock: %w", ctx.Err()))
|
|
}
|
|
defer unlock()
|
|
if ctx.Err() != nil {
|
|
return errors.Join(errTaskExpectedExit, xerrors.Errorf("runTask context canceled: %w", ctx.Err()))
|
|
}
|
|
|
|
switch kind {
|
|
case taskKindGeneration:
|
|
return r.opts.TaskStarter.StartGeneration(ctx, input)
|
|
case taskKindInterrupt:
|
|
return r.opts.TaskStarter.StartInterrupt(ctx, input)
|
|
case taskKindRequiresActionTimeout:
|
|
return r.opts.TaskStarter.StartRequiresActionTimeout(ctx, input)
|
|
case taskKindAbandon:
|
|
return r.opts.TaskStarter.StartAbandon(ctx, input)
|
|
default:
|
|
return errors.Join(errTaskExpectedExit, xerrors.Errorf("unknown task kind %q", kind))
|
|
}
|
|
})
|
|
if err != nil && ctx.Err() == nil {
|
|
r.opts.Logger.Warn(ctx, "chatworker task failed", slogError(err))
|
|
}
|
|
}
|
|
|
|
func (r *runner) cancelActiveTask() {
|
|
if !r.activeTaskSet {
|
|
return
|
|
}
|
|
id := r.activeTaskID
|
|
r.activeTaskSet = false
|
|
if record := r.tasks[id]; record != nil {
|
|
record.cancel()
|
|
}
|
|
}
|
|
|
|
func (r *runner) waitForTasks() {
|
|
for _, record := range r.tasks {
|
|
<-record.done
|
|
}
|
|
}
|
|
|
|
func (r *runner) closeDebugTurn() {
|
|
if r.debugTurn == nil {
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), debugFinalizeTimeout)
|
|
defer cancel()
|
|
r.debugTurn.Finalize(ctx)
|
|
}
|
|
|
|
func (r *runner) removeFinishedTasks() {
|
|
for id, record := range r.tasks {
|
|
select {
|
|
case <-record.done:
|
|
delete(r.tasks, id)
|
|
idx := taskIndexKey{kind: record.kind, key: record.localKey}
|
|
if r.tasksByIndex[idx] == id {
|
|
delete(r.tasksByIndex, idx)
|
|
}
|
|
if r.activeTaskSet && r.activeTaskID == id {
|
|
r.activeTaskSet = false
|
|
}
|
|
default:
|
|
}
|
|
}
|
|
}
|
|
|
|
func uuidPtrEqual(got *uuid.UUID, want uuid.UUID) bool {
|
|
return got != nil && *got == want
|
|
}
|
|
|
|
type localLockSet struct {
|
|
mu sync.Mutex
|
|
locked map[localWorkKey]chan struct{}
|
|
}
|
|
|
|
func newLocalLockSet() *localLockSet {
|
|
return &localLockSet{locked: make(map[localWorkKey]chan struct{})}
|
|
}
|
|
|
|
func (l *localLockSet) acquire(ctx context.Context, key localWorkKey) (func(), bool) {
|
|
for {
|
|
l.mu.Lock()
|
|
wait, ok := l.locked[key]
|
|
if !ok {
|
|
released := make(chan struct{})
|
|
l.locked[key] = released
|
|
l.mu.Unlock()
|
|
return func() {
|
|
l.mu.Lock()
|
|
if l.locked[key] == released {
|
|
delete(l.locked, key)
|
|
close(released)
|
|
}
|
|
l.mu.Unlock()
|
|
}, true
|
|
}
|
|
l.mu.Unlock()
|
|
|
|
select {
|
|
case <-wait:
|
|
case <-ctx.Done():
|
|
return nil, false
|
|
}
|
|
}
|
|
}
|