Documentation
¶
Overview ¶
Package agentcontext consolidates the agent-side plumbing that resolves, watches, and pushes workspace context (instruction files, skills, and MCP configuration) to coderd.
This is the agent half of the design described in "RFC: Workspace Context Sources for Coder Agents". It owns:
- User-declared scan roots (Sources) layered on top of built-in defaults and the working directory.
- A resolver that classifies files at fixed locations under each scan root into typed Resources (instruction files, skills, MCP configs, MCP servers). Discovery is shallow: instruction files (AGENTS.md, CLAUDE.md, .cursorrules) and .mcp.json are read only at a scan root's top level, skills only from fixed container directories (skills, .agents/skills, .claude/skills, .codex/skills), and the resolver never walks the tree downward or up to a parent directory.
- A fixed-location fsnotify watcher that signals a re-resolve when any recognized file changes.
- A readiness gate (Manager.SetReady). The Manager starts gated, publishing only an empty version-0 snapshot until the agent calls SetReady from the workspace lifecycle transition once startup scripts finish. This keeps pre-startup partial state out of coderd and chats.
- An HTTP API at /api/v0/context/sources for source CRUD and /api/v0/context/resync for synchronous push barriers.
- A Pusher abstraction so the latest Snapshot can be shipped to coderd without coupling this package to any particular drpc client version.
Live MCP server tool lists come from the shared MCP engine in agent/x/agentmcp, which owns the single set of MCP server connections used for both tool discovery and tool-call execution. This package reads that engine's catalog through the injected MCPCatalog option and surfaces the servers and their tools as KindMCPServer resources, so MCP servers are pushed to coderd alongside instruction files and skills. The engine notifies this package through the Manager's Trigger when its catalog changes, driving a re-resolve and re-push.
Index ¶
- Constants
- Variables
- func CanonicalizePath(raw string) (string, error)
- func CanonicalizePathIn(home string, raw string) (string, error)
- func ComputeAggregateHash(resources []Resource) [32]byte
- func ValidateSourcePath(canonical string, allowedRoots []string) error
- type API
- type DRPCPusher
- type MCPServerStatus
- type MCPTool
- type Manager
- func (m *Manager) AddSource(s Source) (Source, error)
- func (m *Manager) Close() error
- func (m *Manager) HasSource(path string) (canonical string, ok bool)
- func (m *Manager) RemoveSource(path string) error
- func (m *Manager) Resync(ctx context.Context) (Snapshot, error)
- func (m *Manager) Run(ctx context.Context) error
- func (m *Manager) RunPush(ctx context.Context, p Pusher, opts PushOptions) error
- func (m *Manager) SeedSources(sources []Source)
- func (m *Manager) SetReady()
- func (m *Manager) Snapshot() Snapshot
- func (m *Manager) Sources() []Source
- func (m *Manager) SubscribeChanges() (<-chan struct{}, func())
- func (m *Manager) Trigger()
- type ManagerOptions
- type PushOptions
- type PushRequest
- type PushResponse
- type Pusher
- type Resolver
- type Resource
- type ResourceKind
- type ResourceStatus
- type ScanRoot
- type Snapshot
- type SnapshotResource
- type SnapshotResponse
- type Source
- type SourceRequest
- type SourceResponse
- type Watcher
- type WatcherOptions
Constants ¶
const ( DefaultPushInitialBackoff = 250 * time.Millisecond DefaultPushMaxBackoff = 30 * time.Second )
Default backoff timings for pushWithRetry. Exposed as named constants (rather than inline literals) so godoc shows them and a second push loop, if it ever appears, can reuse them.
const ( // DefaultMaxResourceBytes is the per-resource payload cap. // Resources whose payload exceeds this size are emitted // with Status == StatusOversize and an empty Payload. DefaultMaxResourceBytes = 64 * 1024 // DefaultMaxSnapshotBytes is the aggregate payload cap. // Resources past this cap are emitted with Status == // StatusExcluded. DefaultMaxSnapshotBytes = 2 * 1024 * 1024 // DefaultMaxResources is the resource count cap. Resources // past this cap are emitted with Status == StatusExcluded. DefaultMaxResources = 500 )
Default caps. Copied from the RFC. The Manager exposes overrides via Options.
const DefaultWatchDebounce = 250 * time.Millisecond
DefaultWatchDebounce coalesces editor-style multi-event writes (truncate plus rename plus chmod) into a single re-resolve. Mirrors the debounce window the existing MCP config watcher uses so behavior is consistent across the agent.
Variables ¶
var ErrManagerClosed = xerrors.New("agentcontext: manager closed")
ErrManagerClosed is returned by methods called after Close.
var ErrPushUnimplemented = xerrors.New("agentcontext: PushContextState unimplemented")
ErrPushUnimplemented signals that the coderd peer does not implement PushContextState. RunPush stops pushing for the remainder of the connection.
var ErrSourceNotFound = xerrors.New("source not found")
ErrSourceNotFound is returned by RemoveSource when the requested path is not in the source list.
Functions ¶
func CanonicalizePath ¶
CanonicalizePath returns lexicalPath with symlinks resolved when the target exists.
func CanonicalizePathIn ¶ added in v2.36.0
CanonicalizePathIn is CanonicalizePath with ~ expanded against the given home directory instead of the current user's.
func ComputeAggregateHash ¶
ComputeAggregateHash produces the deterministic snapshot aggregate hash for the supplied resources. The caller does not need to pre-sort; the function sorts a copy of the slice to keep its inputs side-effect free.
The encoding is a Netstring-style stream. Each string field is written as the decimal-ASCII length, the literal ':', and the raw UTF-8 bytes. ContentHash is written as 32 raw bytes without a length prefix because it is a fixed-size SHA-256 digest. Resources are separated by a single NUL byte. The scheme is internal to the agent and coderd, but it is stable across platforms because every field has an unambiguous length.
func ValidateSourcePath ¶
ValidateSourcePath enforces the path-validation rules from the RFC's Authorization section. It rejects:
- Paths containing ".." segments after expansion.
- Paths resolving outside the supplied allowedRoots, unless allowedRoots is empty (which disables the check).
allowedRoots are canonicalized lazily; missing roots are silently skipped so a workspace with no $HOME does not break validation for project-relative roots.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API exposes the Manager over HTTP. The routes match the RFC:
GET /api/v0/context/sources
POST /api/v0/context/sources { path }
GET /api/v0/context/sources/{path}
DELETE /api/v0/context/sources/{path}
POST /api/v0/context/resync
{path} is URL-encoded canonical path. Callers pass either the canonical or original path; the handler canonicalizes before matching.
type DRPCPusher ¶
type DRPCPusher struct {
// contains filtered or unexported fields
}
DRPCPusher adapts a generated DRPCAgentClient to the agentcontext.Pusher interface. The adapter is the only place that knows about the wire protobuf types; the rest of the package operates on the Go Snapshot/Resource value types.
Use NewDRPCPusher to construct an instance. The pusher's behavior is identical to invoking PushContextState directly: per-request retries are handled by Manager.RunPush.
func NewDRPCPusher ¶
func NewDRPCPusher(client agentproto.DRPCAgentClient210) *DRPCPusher
NewDRPCPusher wraps the supplied drpc client. The client must implement the v2.10 Agent API.
func (*DRPCPusher) PushContextState ¶
func (p *DRPCPusher) PushContextState(ctx context.Context, req *PushRequest) (*PushResponse, error)
PushContextState satisfies the Pusher interface.
drpc returns an Unimplemented error when the peer's service definition does not include the RPC. The adapter translates that into ErrPushUnimplemented so RunPush stops gracefully when an old coderd is on the other end.
type MCPServerStatus ¶
type MCPServerStatus struct {
// Name is the server name declared in .mcp.json.
Name string
// Connected reports whether the runner reached the server and
// listed its tools during the most recent reload.
Connected bool
// Err carries the connect/list failure when Connected is false.
Err string
// Tools is the server's tool list, with the tool names exactly
// as the server reported them (no server prefix), when
// Connected; empty otherwise.
Tools []MCPTool
}
MCPServerStatus is a non-blocking, point-in-time view of a single MCP server the runner has attempted to connect to. It is the data buildMCPServerResources turns into a KindMCPServer resource. The runner owns the connection lifecycle; this type carries only the resolved result.
type MCPTool ¶
MCPTool mirrors the wire MCPTool message. InputSchema is the JSON-Schema-shaped object the MCP server reported for the tool's arguments.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager orchestrates source CRUD, resolution, watching, and Pusher fan-out. Construct with NewManager; start its lifecycle goroutines with Run; tear down with Close.
func NewManager ¶
func NewManager(opts ManagerOptions) *Manager
NewManager validates options and canonicalizes initial sources. The returned Manager is gated, so its first snapshot is the empty version-0 placeholder and the first real resolve runs on SetReady. Call Run to start the watcher and re-resolve goroutine.
func (*Manager) AddSource ¶
AddSource validates a new source against the AllowedRoots set and registers it by its lexical identity. AddSource is idempotent.
func (*Manager) Close ¶
Close stops the Manager. Close is idempotent; subsequent calls block until Run exits.
func (*Manager) HasSource ¶
HasSource reports whether path matches a registered source, returning its lexical identity.
func (*Manager) RemoveSource ¶
RemoveSource removes the source matching path by its lexical identity, returning ErrSourceNotFound if none matches.
func (*Manager) Resync ¶
Resync forces an immediate re-resolve and returns the new Snapshot. Resync is safe to call regardless of whether Run is active. Like resolveAndBroadcast, Resync drops the Manager's mutex around the resolver pass so concurrent Sources, AddSource, RemoveSource, and Snapshot calls do not block on filesystem I/O. When the watcher is active, Resync also re-arms it so newly added scan roots are observed for subsequent edits.
func (*Manager) Run ¶
Run starts the watcher and the re-resolve goroutine. Run blocks until ctx is canceled or Close is called. It is safe to call Run at most once per Manager.
func (*Manager) RunPush ¶
RunPush ships the current snapshot to the Pusher, then ships every subsequent snapshot whenever the Manager broadcasts a change. RunPush returns when ctx is canceled, when the Manager is closed, or when the Pusher signals ErrPushUnimplemented.
The first push is always sent with Initial=true so coderd can distinguish a fresh boot from a drift event.
func (*Manager) SeedSources ¶
SeedSources registers a batch of trusted sources without AllowedRoots validation, the late-binding equivalent of ManagerOptions.InitialSources for when the working directory is only known after Run starts. Invalid paths are skipped and duplicates are ignored.
Untrusted callers must use AddSource; SeedSources exists only for manifest-triggered seeding from CODER_AGENT_EXP_*_DIRS.
func (*Manager) SetReady ¶
func (m *Manager) SetReady()
SetReady starts context collection: the agent calls it once startup scripts finish (or terminally fail) so context is never collected from a half-built workspace. Idempotent; the first call triggers the first resolve and push.
func (*Manager) Snapshot ¶
Snapshot returns the latest Snapshot. The returned value is safe to share but shares the same Resources slice as the internal state; callers must not mutate it.
func (*Manager) Sources ¶
Sources returns a defensive copy of the current source list. The returned slice is safe to mutate.
func (*Manager) SubscribeChanges ¶
func (m *Manager) SubscribeChanges() (<-chan struct{}, func())
SubscribeChanges returns a buffered channel that receives a signal whenever the snapshot changes. The unsubscribe callback is safe to call from any goroutine and is idempotent.
func (*Manager) Trigger ¶
func (m *Manager) Trigger()
Trigger queues an asynchronous re-resolve. Trigger returns immediately; the Run goroutine performs the filesystem walk in the background and broadcasts when it finishes. Use Trigger when the caller wants the watcher to pick up an updated working directory or scan-root set but does not need the new Snapshot synchronously. Trigger is a no-op when Run has not started or the Manager is closed.
type ManagerOptions ¶
type ManagerOptions struct {
// Logger receives diagnostic messages. Required.
Logger slog.Logger
// Clock is the time source used for the watcher's
// debounce timer. Optional; defaults to quartz.NewReal().
Clock quartz.Clock
// WorkingDir is evaluated on every resolve, mirroring the
// existing agent convention. The result is used as a
// scan root.
WorkingDir func() string
// InitialSources seeds the Manager's source list at boot
// time. Sources from CODER_AGENT_EXP_*_DIRS env vars or
// startup scripts are layered here.
InitialSources []Source
// AllowedRoots restricts which paths may be added as
// sources at runtime. When empty the package falls back
// to [~, ~/.coder, ~/.claude] plus the working directory.
// Tests override this to exercise the validation logic
// directly; production callers leave it unset.
AllowedRoots []string
// Resolver, when non-nil, replaces the default resolver.
// Tests use this to inject MCP resources (via
// Resolver.MCPResources) and tighten caps.
Resolver *Resolver
// MCPCatalog, when non-nil, supplies the per-server MCP snapshot
// the Manager surfaces as KindMCPServer resources on every
// resolve. The agent injects the shared MCP engine's catalog here
// so discovery and execution use one set of server connections.
// It is ignored when the resolver already has an MCP provider
// (e.g. a test injecting one via Resolver).
MCPCatalog func() []MCPServerStatus
// Debounce overrides the watcher's debounce window.
Debounce time.Duration
}
ManagerOptions configures a Manager. Zero values get sensible defaults.
type PushOptions ¶
type PushOptions struct {
// Logger receives push success/failure diagnostics.
Logger slog.Logger
// InitialBackoff is the wait before the first retry.
// Default 250ms.
InitialBackoff time.Duration
// MaxBackoff caps the retry wait. Default 30s.
MaxBackoff time.Duration
// Clock is the time source for retry backoffs. Optional;
// defaults to the Manager's clock so tests can trap waits
// with quartz instead of real sleeps.
Clock quartz.Clock
}
PushOptions parameterizes RunPush.
type PushRequest ¶
type PushRequest struct {
Version uint64
AggregateHash [32]byte
Resources []Resource
Initial bool
SnapshotError string
}
PushRequest is the wire-format-independent payload the Manager hands to a Pusher. It mirrors the protobuf PushContextStateRequest message reserved in the RFC.
Keeping the shape in plain Go lets this package compile without bumping the drpc proto version. The follow-up integration change can add a thin adapter that converts PushRequest to proto and back.
type PushResponse ¶
type PushResponse struct {
Accepted bool
}
PushResponse is the wire-format-independent return value of a push.
type Pusher ¶
type Pusher interface {
PushContextState(ctx context.Context, req *PushRequest) (*PushResponse, error)
}
Pusher delivers snapshots to coderd. Concrete implementations wrap a drpc client (Agent API v2.10 and later) or, in tests, a recording in-memory fake.
PushContextState must respect ctx cancellation; the Manager retries on transient errors with backoff but stops on ErrPushUnimplemented.
type Resolver ¶
type Resolver struct {
// MaxResourceBytes caps the per-resource payload size. Use
// DefaultMaxResourceBytes if zero.
MaxResourceBytes uint64
// MaxSnapshotBytes caps the aggregate payload size. Use
// DefaultMaxSnapshotBytes if zero.
MaxSnapshotBytes uint64
// MaxResources caps the resource count. Use
// DefaultMaxResources if zero.
MaxResources int
// MCPResources, when non-nil, is consulted after the
// filesystem pass and returns the KindMCPServer resources
// for live MCP servers. It must not block: the resolver
// calls it on every re-resolve. In production the manager
// wires this to its MCP runner's snapshot; tests inject a
// closure directly.
MCPResources func() []Resource
}
Resolver walks one or more scan roots and produces a snapshot of every recognized resource it finds. The Resolver is stateless; the Manager owns the scan-root list and orchestrates successive resolves.
func (*Resolver) Resolve ¶
Resolve walks the supplied scan roots and returns a Snapshot. The version and schemaVersion fields are stamped by the caller; Resolve fills everything else. Resolve is the non-cancellable convenience wrapper around ResolveContext using context.Background.
func (*Resolver) ResolveContext ¶
ResolveContext is the cancellable variant of Resolve. The context is checked between scan roots so callers can bail out of a long pass without waiting for the current root's walk to finish. Cancellation never partially populates the returned Snapshot: a canceled context returns an empty Snapshot with SnapshotError set to the context error.
type Resource ¶
type Resource struct {
// ID is stable across pushes for the same logical
// resource. The current scheme is "<kind>:<source>". It is
// used for in-snapshot dedup and as part of the aggregate
// hash; it is not transmitted on the wire.
ID string
// Kind classifies the resource. Drives which proto oneof
// variant the DRPC adapter sets.
Kind ResourceKind
// Source is the file path or MCP server name.
Source string
// ContentHash is sha256 over the resource's original
// bytes (or transport-encoded server tool list).
ContentHash [32]byte
// Payload is the full bytes when Status == StatusOK; the
// per-resource and aggregate caps may leave it empty.
// Unused for KindMCPServer (Tools is used instead).
Payload []byte
// SizeBytes is the original payload size, populated
// regardless of Status.
SizeBytes uint64
// Status records OK or a reason the payload is absent.
Status ResourceStatus
// Error is populated whenever Status != StatusOK; may
// also carry a non-fatal warning when Status == StatusOK.
Error string
// Name is the resource's own short identifier. Currently
// populated for KindSkill (from front-matter) and
// KindMCPServer (server name); empty for other kinds.
Name string
// Description is a short human-readable summary (skill
// front-matter description, MCP server description,
// instruction-file first line). Shipped on the wire only
// for kinds whose body type carries a description field.
Description string
// SourcePath is the user-declared source that contributed
// the resource; empty for built-in scan roots.
SourcePath string
// Tools is populated for KindMCPServer with the live
// server's tool list; empty otherwise.
Tools []MCPTool
}
Resource is what the resolver emits for each recognized file or live server it discovers under a scan root. The struct is intentionally flat; the typed wire mapping happens in drpc.go where Kind selects the proto oneof variant.
type ResourceKind ¶
type ResourceKind int
ResourceKind describes the category of a resolved context resource. The values mirror the proto ContextResource.Kind enum reserved in the RFC; future kinds (PLUGIN, HOOK, SUBAGENT, COMMAND) are defined here so callers can switch exhaustively, but no v1 resolver emits them.
const ( KindUnspecified ResourceKind = iota // KindInstructionFile covers AGENTS.md, CLAUDE.md, // .cursorrules, and similar plain-text rule files that // inject content into the model prompt. KindInstructionFile // KindSkill is a directory containing SKILL.md and any // supporting files. Only the meta file is read at // resolve time; bodies are fetched on demand. KindSkill // KindMCPConfig is a .mcp.json fragment declaring one or // more MCP servers. KindMCPConfig // KindMCPServer is a live MCP server's resolved tool list, // populated from the MCP runner's snapshot after the server // has been connected. KindMCPServer // KindPlugin is reserved for Claude Code plugin manifests. // Not emitted by v1. KindPlugin // KindHook is reserved for plugin hooks. Not emitted by v1. KindHook // KindSubagent is reserved for plugin-declared subagents. // Not emitted by v1. KindSubagent // KindCommand is reserved for plugin slash commands. // Not emitted by v1. KindCommand )
func (ResourceKind) String ¶
func (k ResourceKind) String() string
String returns the lower-snake-case name used in IDs and metrics. Unknown values stringify to "unknown".
type ResourceStatus ¶
type ResourceStatus int
ResourceStatus describes whether a resource was successfully read and whether its payload survived the per-resource and aggregate caps.
Note: these iota ordinals do NOT match the proto ContextResource.Status ordinals one-to-one. The proto enum reserves 0 for STATUS_UNSPECIFIED and shifts every value by one, so the conversion in resourceStatusToProto cannot be replaced with a direct int cast. ResourceKind, by contrast, does align with its proto counterpart.
const ( // StatusOK indicates the payload was populated. StatusOK ResourceStatus = iota // StatusOversize indicates the resource exceeded the // per-resource size cap; payload is omitted. StatusOversize // StatusUnreadable indicates an IO error reading the // resource (permission denied, broken symlink, etc.). StatusUnreadable // StatusInvalid indicates the resource was structurally // malformed (bad JSON, missing front-matter, etc.). StatusInvalid // StatusExcluded indicates the resource was dropped to fit // the aggregate snapshot or count cap. StatusExcluded )
func (ResourceStatus) String ¶
func (s ResourceStatus) String() string
String returns the lower-snake-case name used in IDs and metrics. Unknown values stringify to "unknown".
type ScanRoot ¶
type ScanRoot struct {
// Path is the absolute path. Symlinks should already be
// resolved.
Path string
// UserSource is the canonical source path the user
// declared, when this root came from a user-added Source.
// Empty for built-in roots.
UserSource string
}
ScanRoot describes a single directory or file the resolver should examine.
type Snapshot ¶
type Snapshot struct {
// Version is monotonically increasing per Manager instance; resets
// when the agent process restarts. Version 0 is the gated pre-ready
// placeholder (the first real resolve is version 1), which the push
// loop withholds.
Version uint64
// AggregateHash is sha256 over a canonical encoding of
// (ID, Kind, Source, ContentHash, Status) for every
// drift-relevant resource. MCP resources (KindMCPConfig and
// KindMCPServer) are excluded because they describe live,
// agent-global runtime capabilities discovered at turn time,
// not pinned prompt content; see driftResources. Identical
// inputs always produce identical hashes; see
// ComputeAggregateHash.
AggregateHash [32]byte
// Resources is sorted by ID for deterministic encoding.
Resources []Resource
// PayloadBytes is the sum of len(Resource.Payload) across
// emitted resources after caps were applied.
PayloadBytes uint64
// SnapshotError carries a single snapshot-level error
// string when present (count cap exceeded, watcher
// degraded, ENOSPC, etc.). Empty when healthy.
SnapshotError string
}
Snapshot is the immutable bundle of resources produced by a single resolver pass.
type SnapshotResource ¶
type SnapshotResource struct {
ID string `json:"id"`
Kind string `json:"kind"`
Source string `json:"source"`
SourcePath string `json:"source_path,omitempty"`
ContentHash string `json:"content_hash"`
SizeBytes uint64 `json:"size_bytes"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
}
SnapshotResource is the on-wire representation of a Resource. Payloads are omitted; clients that need the bytes go through the drpc PushContextState path.
type SnapshotResponse ¶
type SnapshotResponse struct {
Version uint64 `json:"version"`
AggregateHash string `json:"aggregate_hash"`
Resources []SnapshotResource `json:"resources"`
PayloadBytes uint64 `json:"payload_bytes"`
SnapshotError string `json:"snapshot_error,omitempty"`
}
SnapshotResponse is the on-wire representation of a Snapshot returned by the resync endpoint.
type Source ¶
type Source struct {
// Path is the canonical absolute path (symlinks resolved,
// ~ expanded). Empty means the zero value.
Path string
}
Source is a user-declared scan root added to the agent's in-memory list via the HTTP API or boot-time env seeding. Identity is the canonical absolute path.
type SourceRequest ¶
type SourceRequest struct {
Path string `json:"path"`
}
SourceRequest is the request body for POST /sources.
type SourceResponse ¶
type SourceResponse struct {
Path string `json:"path"`
}
SourceResponse is the on-wire representation of a Source. Matches the path-only RFC schema; future additions (tags, labels) can land additively without breaking clients.
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher is a fixed-location fsnotify wrapper. It watches only the directories that can hold recognized resources (each scan root plus its skill containers and immediate skill dirs) rather than walking the tree, mirroring the resolver's fixed-location discovery. Inotify ENOSPC degrades the watcher into a poll-only mode that still re-resolves on Sync calls.
func NewWatcher ¶
func NewWatcher(opts WatcherOptions) (*Watcher, error)
NewWatcher constructs a recursive watcher. The watcher does nothing until Sync is called.
func (*Watcher) Close ¶
Close stops the watcher and releases all kernel watch slots. Close is idempotent.
func (*Watcher) Degraded ¶
Degraded returns a non-empty string when the watcher is running with reduced functionality (typically inotify ENOSPC). The string is suitable for use as a snapshot-level error message.
func (*Watcher) Sync ¶
Sync replaces the set of watched directories with the fixed locations that can hold recognized resources: each scan root, its skill containers, and the immediate skill subdirectories. Files are not watched directly; watching the parent directory catches creates, renames, removes, and writes that touch any recognized basename. Files that are themselves scan roots are handled by watching their parent.
Sync is idempotent and safe to call repeatedly. The lock is released around the directory scan so concurrent Close, schedule, and the run goroutine are not blocked by a slow filesystem.
type WatcherOptions ¶
type WatcherOptions struct {
Logger slog.Logger
Clock quartz.Clock
Debounce time.Duration
// OnChange runs at most once per debounce window. The
// caller must not block; the recommended pattern is a
// non-blocking send on a re-resolve trigger channel.
OnChange func()
}
WatcherOptions parameterizes the watcher.