Extension points: the ports and adapters
The framework is built on a small set of ports (Go interfaces) with reference adapters (built-in implementations). You wire your own infrastructure in by implementing a port; the reference adapters exist for tests, local dev, and as a template for a real backend. Every built-in adapter asserts its contract with a var _ Port = (*Adapter)(nil) line, so a breaking change to a port fails to compile against the adapters.
This page documents each port: its method set, what an implementer provides, and the reference adapters that ship with it. The full exported API of each package, with its stability label, is in the generated SDK API reference.
| Port | Package | What it abstracts | Reference adapter(s) |
|---|---|---|---|
Model | root | the provider (LLM) primitive | model/anthropic, model/openai, model/gemini |
Store | root | the crash-safe journal substrate, under Journal | MemStore, store/sqlite, store/postgres |
Tool | root | an action the agent can take | Func, CompensatedFunc, mcptools tools |
Compensator | root | how a tool undoes its side effect (sagas) | CompensatedFunc |
Retriever | root | bring-your-own RAG | your store; wired via RetrievalTool / WithRetrieval |
Anchor | audit | out-of-band anchoring of a commitment | MemAnchorLog, anchor/awss3 (S3 Object Lock), anchor/gcs (Google Cloud Storage, locked retention policy) |
EventStore | audit | durable event-trail persistence | MemEventStore |
Waker | root | what re-invokes a run at a durable timer's wake time (WithWaker) | MemWaker; a cron, queue or in-process loop is your policy (signals) |
Signer | audit | one signing key under one scheme, for the log, grants and approvers | in-memory keys, signer/pkcs11, signer/awskms, signer/azurekv, signer/gcpkms (key custody) |
Notifier | root | telling a person a run needs them | your webhook, chat or pager adapter |
NotifyTrail | root | the audited delivery state behind Notifier | audit.NewNotifyTrail (over an EventStore), MemNotifyTrail |
Model: the provider primitive
type Model interface {
Stream(ctx context.Context, req Request) (*Stream, error)
}Streaming is first-class: Stream is the only method an adapter must implement. agent.Generate is a convenience drain built on top (stream and assemble in one call), the opposite of frameworks that make blocking generation primary and bolt streaming on later. An implementer maps a provider's wire format onto normalized Event values (TextDelta, ReasoningDelta, ToolCallDelta, Finish).
An adapter that reads a response as it arrives builds its stream with agent.NewStreamFunc:
return agent.NewStreamFunc(ctx, func(send func(agent.Emit) bool) {
defer resp.Body.Close()
for /* each event read from resp.Body */ {
if !send(agent.Emit{Event: ev}) {
return // the consumer stopped reading, or ctx was cancelled
}
}
}), nilsend returns false once the consumer breaks out of Stream.Events, calls Stream.Close, or cancels ctx, so the adapter stops and releases the response. After cancellation no further event is delivered and the stream ends with the context's error, so a response cut short is never read as a complete one. A turn ends with a Finish event, sent only once the provider has signalled the end of the turn: a stream that closes without one reads as agent.ErrIncompleteResponse (an ErrModel), so a response cut off partway fails the model call, which retry middleware can repeat, instead of being journaled as the model's answer. The Finish is the turn's last event: an event after it reads as agent.ErrStreamProtocol (an ErrModel and an ErrProtocol). An adapter sends it on the provider's end-of-turn signal only, never on usage alone, and fails with agent.ErrStreamProtocol on content the provider sends after that signal. A Finish whose usage has a negative count fails the call with agent.ErrNegativeUsage rather than lowering the run's totals; so does negative usage a middleware returns. The Finish names why the turn ended in the neutral agent.FinishReason vocabulary (FinishStop, FinishToolUse, FinishLength, FinishFiltered), with the provider's own value in Raw; a turn cut off at its token limit or stopped by a filter fails the call with agent.ErrOutputTruncated or agent.ErrOutputFiltered. agent.NewStream wraps a channel the caller fills itself, which suits a response buffered up front. model/modeltest.Run checks an HTTP adapter against this contract, including the truncation case, and modeltest.CheckFinish checks the Finish it sends. The HTTP kit the first-party adapters share (error classification, SSE framing, the response cap, Retry-After parsing, the tool-result codec) is the model/provider package, which a third-party adapter can use too.
Reference adapters. model/anthropic, model/openai, and model/gemini each provide New(apiKey, opts...) returning a *Model that satisfies the port, with options like WithModel, WithMaxTokens, and WithPromptCache (Anthropic).
Store: the crash-safe substrate
type Store interface {
// Insert stores data under (runID, name) if no entry has that name, and returns the stored
// entry (the caller's, or the one already there) and whether this call stored it.
Insert(ctx context.Context, runID, name string, data []byte) (Entry, bool, error)
// Get returns runID's entry named name, if there is one.
Get(ctx context.Context, runID, name string) (Entry, bool, error)
// Load yields runID's entries whose Seq is greater than after (-1 for all of them), in
// ascending Seq. It yields an error at most once, as its last element.
Load(ctx context.Context, runID string, after int64) iter.Seq2[Entry, error]
}
type Entry struct {
Seq int64 // opaque; strictly increasing in commit order within the run
Name string
Data []byte
}A Store is a dumb, append-only set of named entries per run. It stores bytes and knows nothing of what they mean. Everything with meaning lives in the agent.Journal above it (agent.NewJournal(store)): the record encoding and its salt, named-step memoization, the journal format header, the attempt claims that keep side effects at most once, and recording a step's outcome after its caller's context is cancelled. So a new backend implements three methods and gets every engine guarantee without reimplementing any of them.
Requirements. The Journal relies on these, and agent/storetest checks each one:
- A1, unique names, linearizable insert. At most one entry per
(runID, name). Concurrent Inserts of one name, from any number of processes, have exactly one winner, and every caller and every later reader sees the winner's bytes. Which entry(runID, name)names does not depend on the context: a tenant carried in the context and mixed into the keys breaks the journal, which remembers runs by run ID; put the tenant in the run ID instead (RunFilter.Prefix). - A2, commit-ordered, prefix-closed visibility.
Seqis strictly increasing in commit order within a run, and every read returns a prefix of the run's final order: no entry ever becomes visible with a lowerSeqthan one already visible. Gaps are allowed; nothing readsSeqas a count. - A3, durable before return. Insert reports
insertedonly after the commit. On an error the entry is either absent or complete, and the same bytes may be inserted again. - A4, read-your-writes, monotone visibility. Once visible, an entry stays visible with the same bytes and position.
- A5, byte fidelity. Data comes back exactly as inserted, every record's salt included: the engine tells its own model record from another driver's by the salt it drew, so a store that rewrites or drops salt bytes makes it take its own record for another's.
- A6, immutable. No update or delete; only a redaction may replace an entry's bytes with a tombstone, in a run that is over, through the optional
Redactorbelow, never throughStore. - A7, context. Every method honors
ctx. - A8, iterator hygiene. Breaking out of
Loadreleases everything it holds, and a store holds no connection, transaction or lock across ayield, so a caller may write inside its loop.
Optional capabilities. A store may also implement Holder (PlaceHold, LiftHold, Holds: legal holds kept beside the journal; the store's Redactor refuses a run a hold covers, or with a tree hold a sub-agent run below one, in the statement that would replace the record: ErrRedactHeld; storetest.Holder is the conformance suite) and Redactor (Redact(ctx, runID, name, current, tombstone): replace one entry's bytes with a tombstone that keeps its leaf hash, atomically, only if the entry still holds current, the run holds an end marker, no lease on it is live and every run above it (a sub-agent's parents) that holds records holds an end marker, and it is not a session's run; it calls agent.CheckRedaction first, so a caller cannot write a tombstone with the wrong hash or redact a protected record; storetest.Redactor is the conformance suite and Run calls it). A store may also implement Lister (Runs(ctx, RunFilter), which a recovery supervisor needs; a SQL store evaluates the filter in its query) and Leaser (run leases that coordinate drivers, and ReapLeases, which deletes lapsed leases no recovery pass takes over: a finished run's, one on a run the store does not hold, and one on a run whose ID contains >). A store that implements both must implement RunFilter.LeaseLapsed, which admits only the runs whose lease has lapsed by the comparison AcquireLease makes: RecoverLoop's lapsed loop lists with it on every pass, so a store that ignored it would hand that loop every unfinished run, doubling the cost of recovery and letting halted runs delay takeover again. storetest.Run checks both (Lister_LeaseLapsed, Leaser_ReapLeases). agent.Capability[T](store) finds them, looking through wrappers that implement Unwrap() Store. Only a wrapper that passes run IDs and names through unchanged may implement Unwrap; one that rewrites keys (a tenant prefix, say) implements each capability itself. storetest.CheckWrapper(t, wrap, ctxA, ctxB) checks this, and that the wrapper's keys do not depend on the context; give it at least two contexts that differ in the values your wrapper reads from a context. The engine also follows Unwrap() Store (as audit.AuditedStore implements it) to the store beneath for the identity under which the process keeps per-run state (claims it could not record as not started, spend it could not journal), shared by every Journal and wrapper over that store; this is a second reason a wrapper that rewrites keys must not implement Unwrap, or two tenants' runs of one name would share that state.
Reference adapters. agent.NewMemStore() is the in-memory implementation for tests and local dev. store/sqlite.Open(path) (one machine; three connection pools: a writer, readers, and a lease connection) and store/postgres.Open(ctx, dsn) (any number of nodes) are the persistent backends; each also has New(ctx, db) for a *sql.DB you opened, and WithTablePrefix (tables are bide_steps, bide_leases, bide_events (the durable event trail, see EventStore below) and bide_schema_version by default). All three implement Lister and Leaser. store/postgres sends every write (an insert, each lease call) as one statement that Postgres commits before it replies, so no transaction spans two round trips and a process stalled between them holds no lock another node waits on. A statement that a deployment whose default_transaction_isolation is repeatable read or serializable fails with a serialization failure changed nothing and is run again, so the level does not change how the store records steps or leases. Retries back off and continue until the context ends, so give each call a deadline if it must be bounded. Inserts into one run queue on the run's advisory lock, which the function bide_next_seq_v1 takes inside the insert's statement; it qualifies every name and runs with SET search_path = pg_catalog, pg_temp. Open and New create the function and refuse an existing table that lacks a uniqueness the statements depend on, or a function with another definition or owner, since they never alter either. Every name in every statement is qualified (the tables and the function with the store's schema, built-ins, types and operators with pg_catalog), so no statement looks a name up through the search path. Pin the schema with postgres.WithSchema: without it, every Open discovers the schema through the search path and logs a warning, and a role that can create a schema earlier on the path (any role with CREATE on the database can create the "$user" schema) can redirect a restarting node. The store trusts the owner of its schema and every role that can create objects in it, as it trusts the tables' owner. After renaming the schema, drop bide_next_seq_v1(text) and Open again.
Implement your own store
Here is a small in-memory implementation (the same shape as MemStore):
package mystore
import (
"bytes"
"context"
"iter"
"sync"
"github.com/bide-ai/bide/agent"
)
type Store struct {
mu sync.Mutex
runs map[string][]agent.Entry // runID -> entries in Seq order
}
func New() *Store { return &Store{runs: map[string][]agent.Entry{}} }
var _ agent.Store = (*Store)(nil) // port/adapter contract
func (s *Store) Insert(ctx context.Context, runID, name string, data []byte) (agent.Entry, bool, error) {
if err := ctx.Err(); err != nil {
return agent.Entry{}, false, err
}
s.mu.Lock()
defer s.mu.Unlock()
for _, e := range s.runs[runID] {
if e.Name == name { // A1: the first insert of a name wins
e.Data = bytes.Clone(e.Data)
return e, false, nil
}
}
e := agent.Entry{Seq: int64(len(s.runs[runID])), Name: name, Data: bytes.Clone(data)}
s.runs[runID] = append(s.runs[runID], e)
e.Data = bytes.Clone(e.Data)
return e, true, nil
}
func (s *Store) Get(ctx context.Context, runID, name string) (agent.Entry, bool, error) {
if err := ctx.Err(); err != nil {
return agent.Entry{}, false, err
}
s.mu.Lock()
defer s.mu.Unlock()
for _, e := range s.runs[runID] {
if e.Name == name {
e.Data = bytes.Clone(e.Data)
return e, true, nil
}
}
return agent.Entry{}, false, nil
}
func (s *Store) Load(ctx context.Context, runID string, after int64) iter.Seq2[agent.Entry, error] {
return func(yield func(agent.Entry, error) bool) {
if err := ctx.Err(); err != nil {
yield(agent.Entry{}, err)
return
}
s.mu.Lock()
snap := s.runs[runID] // entries are only appended, so the snapshot stays valid
s.mu.Unlock() // A8: no lock held across a yield
for _, e := range snap {
if e.Seq > after {
e.Data = bytes.Clone(e.Data)
if !yield(e, nil) {
return
}
}
}
}
}Use it through a Journal, which goes wherever a store goes (agent.New(model, j), j.Step(ctx, ...), agent.Recover(ctx, j, ...)):
j, err := agent.NewJournal(mystore.New())
if err != nil {
return err
}
_ = jFor a SQL backend, let a primary key on (run_id, name) enforce A1 (INSERT ... ON CONFLICT DO NOTHING, then read back the stored row), assign seq in the insert under a per-run lock so it follows commit order (A2), read Load in pages with no connection held between them (A8), and store data as bytes, never as JSON or text (A5).
Check it with the conformance suite. agent/storetest checks every requirement above (including 64 goroutines racing one name through three handles), the journal format header, and the record-fidelity cases (records whose encoding is easy to get wrong: HTML-significant characters, U+2028, NUL, invalid UTF-8, unusual number forms, key order). open may be called several times; every handle it returns must reach the same data:
package mystore_test
import (
"testing"
"github.com/bide-ai/bide/agent"
"github.com/bide-ai/bide/agent/storetest"
)
func TestMyStore(t *testing.T) {
s := New()
storetest.Run(t, func(*testing.T) agent.Store { return s })
}
func New() agent.Store { return agent.NewMemStore() } // your store hereMemStore, store/sqlite, and store/postgres all run it.
Tool: an action the agent can take
type Tool interface {
Spec() ToolSpec // name, description, schema, safety, approval gate, timeout
Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}The interface is untyped (json.RawMessage) so heterogeneous tools share one type, including runtime mcptools tools whose schema is only known at connect time. Most native tools never implement this by hand: agent.Func[In, Out](name, desc, fn, opts...) (or MustFunc) wraps a typed Go function and derives the spec's Input schema from In at construction, so changing In is a compile-time change. Safety (the WithSafety option) declares retry behavior on resume (ReadOnly, Idempotent) and maps directly onto MCP annotations (see the MCP guide). Trailing tool options set the rest of the tool's ToolSpec: WithApproval (a human gate: SingleApproval(), or a signed m-of-n ApprovalPolicy), WithTimeout, WithTitle, WithOutputSchema, and WithSafety. For the m-of-n policy, approver signatures are checked through the ApproverVerifier hook (Alg(), Verify and KeyIDs), which the audit package's Ed25519, ECDSA P-256, ML-DSA, and hybrid verifiers implement; a decision counts only under the scheme journaled with it (Decision.Alg, recorded as Record.ApproverAlg), which must be its approver key's. Its KeyIDs method names the keys behind a verifier, derived from the public key's bytes, and the gate refuses a policy two of whose approvers share one (see approval).
type ToolSpec struct {
Name string
Title string // display name; models are not shown it
Description string
Input json.RawMessage // argument schema, an object schema
Output json.RawMessage // result schema, when the tool declares one
Safety Safety // journaled with each result
Approval *ApprovalPolicy // journaled with each result
Timeout time.Duration // bounds each call, tool middleware included
}The agent reads each tool's spec once, when it is registered, and decides every call from that copy; model adapters receive the specs as Request.Tools, sorted by name. With a Timeout, a result the tool returns after the deadline is recorded, and an error it returns after the deadline has an unknown outcome: a side effect records nothing and halts on resume, a retry-safe tool records the error. A tool that wraps another (as audit.AttenuatingSubAgent wraps a SubAgent) says so with an Unwrap() Tool method, which the agent follows to find a wrapped sub-agent for saga rollback and budget accounting. The contract: a wrapper adds no side effect of its own (it may change the context the wrapped tool runs in), is not a Compensator, and does not give a wrapped sub-agent a timeout or another Safety; New refuses the last three with ErrConfig. A rollback through a wrapper runs the wrapped sub-agent's compensations, never the wrapper's. A decorator that embeds a tool (struct{ agent.Tool }) inherits its Spec, approval gate and timeout included; one that declares a Spec of its own that drops an embedded tool's approval gate or timeout would let the gated tool run ungated, and New refuses it with ErrConfig. The same holds for a tool on a wrapper's Unwrap chain, however the wrapper holds it (a named field included): when the wrapper's own spec is weaker than a wrapped tool's, New and the plan registry refuse it with ErrConfig, naming the field and both tools. Weaker means, for the approval gate: none; fewer decisions needed (Need; a SingleApproval needs one); a SingleApproval over an m-of-n gate; an approver the wrapped gate does not name; no ExcludePrincipal where the wrapped gate has it; no gate deadline, or a longer one, where the wrapped gate has one. For Timeout: none, or a longer one. For Caps: a rule line of the wrapped tool that the wrapper's Caps does not carry, word for word (a changed rule is a missing one; the wrapper may add rules). If the wrapper has another name, write one rule line naming both tools (refund|refund_logged.amount[...], the grammar of the amount-caps guide) and carry it on the wrapped tool and the wrapper: a line that names only the wrapped tool is refused on a differently named wrapper. Declare the same on the wrapper, or build its spec from the wrapped tool's. A wrapper with neither embedding nor Unwrap cannot be seen through. Safety is checked the same way, for a wrapper that unwraps a tool or embeds one, at any depth. The levels are ordered: a side effect (the zero value), then Idempotent, then ReadOnly (the safest, whether or not Idempotent is also set). A wrapper whose declared Safety is safer than the tool inside it (the least safe one, when it embeds several) is refused with ErrConfig, naming the wrapper, the tool and both levels. The wrapper's Safety is the one the agent acts on, so a wrapper that claims ReadOnly over a side-effecting tool would lose the taint gate, the attempt marker and the halt on an unknown outcome (the call would be re-run on resume), and one that claims Idempotent would have its call re-run. The same or a stricter level is accepted. A wrapper that really does make the call safer (it stops at a dry run, it adds an idempotency key) opts out with agent.RaisesSafety(reason) (experimental; ToolSpec.RaisesSafety is the same declaration for a spec built by hand). The reason is required, printable and at most 128 bytes, as for agent.Trusted; it is part of the declarations document and digest (only when set), bide doctor -declarations lists it, and bide doctor -diff reports adding it as WEAKENED. The wrapper is then treated by the level it declared. A wrapper is held to every tool inside it, not only the one it holds directly: a middle wrapper that raised the level with a reason does not let the outer one declare it without its own. Untrusted is checked through the chain as described above.
Compensator: how a tool undoes its side effect
type Compensator interface {
// Compensate undoes a completed call. args are the arguments the tool accepted (after tool
// middleware; see CompensatedFunc); result is what Call returned. Must be idempotent: on a
// crash mid-rollback it may re-run.
Compensate(ctx context.Context, args, result json.RawMessage) error
}An optional interface a Tool implements to declare how to roll back its write. In a saga run (WithSaga()), if a step fails after earlier writes succeeded, the completed compensatable writes are rolled back in reverse order, automatically and recursively through sub-agent trees (a wrapped sub-agent included, through Unwrap() Tool). agent.CompensatedFunc[In, Out](name, desc, do, undo, opts...) (or MustCompensatedFunc) builds a typed tool that declares both its forward action and its compensator.
Retriever: bring-your-own RAG
type Retriever interface {
Retrieve(ctx context.Context, query string, k int) ([]Doc, error)
}The bring-your-own-RAG port: given a query, return the top-k relevant Doc values from your store (pgvector, Pinecone, a file index, anything). Bide ships no vector store and no embedder; you implement Retrieve against infrastructure you already run and wire it in with agent.RetrievalTool(name, description, r, k) (agentic: the model searches on demand) or the agent.WithRetrieval(r, k) option (classic: the top-k for the run's user message, retrieved once per run as a journaled step and sent on every model call of the run as a user message just before that message; it runs before the model middleware chain, so wrap the Retriever to gate it, and retry it with WithRetrievalRetry). Both journal what was retrieved, so a resumed run sees the same documents, and both call Retrieve concurrently, so it must be safe for concurrent use. See RAG and memory.
Anchor: out-of-band anchoring (audit)
type Anchor interface {
Publish(ctx context.Context, runID string, sth SignedTreeHead) error
}The bring-your-own port for out-of-band anchoring: publish a SignedTreeHead to a trust domain separate from the app (a Certificate-Transparency-style log, a notary / timestamping service, another account's WORM store, a public ledger). Anchoring is what upgrades integrity to tamper-evidence: a Merkle root stored in the same database an attacker controls can be rewritten and rehashed, so the guarantee only bites once the signed head is committed to a domain the app tier does not fully control.
Reference adapter. audit.NewMemAnchorLog() is a reference external transparency log: an append-only, independently Merkle-committed record of published STHs. Because it keeps its own RFC 6962 tree over the entries, a third party can verify that the anchor log itself only grew (ProveConsistency) and that a specific STH was anchored (Prove). In a real deployment the anchor lives in a different trust domain than the journal; this in-memory version is for tests and local dev. See the audit guide.
Production adapter. anchor/awss3 (its own module, so the AWS SDK stays out of the core) writes each head as an object in an S3 bucket under Object Lock, reads it back, and ships bide-anchor to verify the set and audit the bucket. See anchoring. anchor/gcs is the same for a Google Cloud Storage bucket with a locked retention policy (anchoring in Google Cloud Storage), and bide-anchor -backend gcs reads it; both build on the SDK-free audit/anchorobj.
EventStore: durable event-trail persistence (audit)
type EventStore interface {
// Append durably records leaf at position seq (0-based, contiguous) for runID.
// Append-only and idempotent on (runID, seq): re-appending the same bytes is a no-op,
// a DIFFERENT leaf at an existing seq must fail with an error wrapping audit.ErrSeqTaken
// (fork/tamper, or a lost race of which exactly one writer wins), and a seq beyond the
// next position is a gap and must error without wrapping it.
Append(ctx context.Context, runID string, seq int, leaf []byte) error
// Load returns every leaf for runID in seq order (0..n-1), or nil if unknown.
Load(ctx context.Context, runID string) ([][]byte, error)
}The bring-your-own port for a compliance trail that has to outlive the journal (keep 7 years, on WORM storage, in a different trust domain). You implement Append / Load against an append-only backend you run (a Postgres table with UNIQUE(run_id, seq) and insert-only grants, object storage with object-lock/WORM, or a log). The trail is fed from the durable journal projection (agent.ReplayEvents, see debugging), not the live stream, so re-mirroring after a crash appends the same leaves at the same positions (idempotent). audit.PersistJournal drives that mirroring; audit.LoadEventLog rebuilds an EventLog from the store for Root / STH / proofs even after the journal is deleted. Each leaf holds its event's random salt, which a proof discloses from the stored bytes, so store leaves verbatim (see audit).
audit.ErrSeqTaken is how a store reports a position that holds a different leaf; a caller that inserts if absent tells a lost race from a real failure with errors.Is(err, audit.ErrSeqTaken).
Reference adapters. audit.NewMemEventStore() is the in-memory implementation; it enforces the same append-only, idempotent, contiguous contract a real backend would enforce with a unique constraint and insert-only permissions. store/sqlite and store/postgres ship durable ones: (*Store).EventStore() returns an audit.EventStore over the same database and connections as the journal, in a bide_events table (the table prefix applies) with primary key (run_id, seq). Append is one insert-if-absent statement, committed before it returns, so writers racing for a position, across connections or nodes, have exactly one winner and the rest get ErrSeqTaken (or a no-op for the same bytes). audit/eventstoretest.Run is the conformance suite every one of them passes; run it against your own backend.
Notifier: tell a person a run needs them
type Notifier interface {
Notify(ctx context.Context, n Notification) error
}The port behind agent.WithNotifier. Notify is called when a run halts on an unknown outcome, waits for approval, is aborted, or cannot be recovered (and, with agent.NotificationResolved, when an event it reported is over: Notification.Clears says which; with agent.NotificationEscalated, when an event nobody acknowledged or decided is escalated to it: Notification.Escalates says which), and again after an error, a crash or a lost reply: return nil only once the sink has accepted the notification, and use Notification.ID, which is the same on every attempt, to drop duplicates at the sink. A Notification holds structured fields only, and Err is for an in-process notifier: a notifier that sends elsewhere should not forward error text or tool arguments, which can hold card numbers or personal data. Notify may be called from several goroutines at once, for different events (an event and the steps of its escalation chain too), so an implementation must be safe for concurrent use: guard any counter, map or buffer it keeps. Wrap agent.ErrNotifyPermanent for a failure a retry in the same round cannot fix, and call agent.ReportNotifyAck to record how a delivery was authenticated. A plan flow takes the same notifier with plan.Builder.WithNotifier (or plan.WithLoadedNotifier for a loaded config), and code that drives its own runs binds it with agent.NewRunNotifier. The design is in docs/design/notifier.md; the webhook notifier that implements the port follows. On the receiving side, relay.Sink in package notify/relay (Name() string, Send(ctx, notify.Payload) error) is the port for forwarding a verified webhook somewhere else; relay.NewSlack and relay.NewPagerDuty implement it (see Notifications).
One WithNotifier can serve several receivers: agent.WithNotifyReceiver adds a named Notifier, WithNotifyRoute and WithNotifyApproverRoute choose where events go, and WithNotifyEscalation sets a bounded chain of receivers for an event not acknowledged (an approval: not decided) in time. Notification.Receiver says which receiver a call is for. Each receiver has its own records in the trail; see Routing and escalation.
NotifyTrail: delivery state, audited
type NotifyTrail interface {
Load(ctx context.Context, trail string) ([]NotifyRecord, error)
Append(ctx context.Context, trail string, seq int, rec NotifyRecord) error
}Where a notifier records that it observed an event, claimed it, and saw the sink acknowledge it, so a restart does not repeat an acknowledged event and two processes do not both deliver while a claim is live. Append is insert-if-absent at a position: a different record at a taken position is agent.ErrTrailConflict, and the same record again is a no-op. The state is never written to the run's journal. audit.NewNotifyTrail(store) stores a trail as salted, Merkle-committed event leaves on any audit.EventStore, so it is verifiable like any event trail; across processes it needs an EventStore that is durable and enforces UNIQUE(run_id, seq). agent.NewMemNotifyTrail is the in-process implementation, and agenttest.NotifyTrailContract is the contract test for your own.