driver
import "github.com/barevoidco/zelk/core/driver"Package driver runs the effects the reducer asks for and records them in the session log.
The reducer in package loop decides what happens next; the driver makes it happen. For every effect it renews the lease, appends EffectStarted, dispatches, and appends the terminal event with the result items and usage in one batch, then folds what it appended and carries on from the new state until the session is idle. The driver keeps no state of its own beyond the folded log, so whatever it does next follows from what the log records.
Recovery settles lost attempts before normal dispatch. CallProvider, RunTool, Append and Acquire are the public pieces for hosts with their own executor. Stops leave cut-short attempts open; accepted interrupts persist termination. Run returns the acknowledged fold even when failed storage refuses reads; WithCommands supplies live input and WithInitialCommands an initial batch. Absolute attempt deadlines and generation-numbered run timers survive recovery. WithProviderResolver selects the host’s provider for each session’s recorded family and model without changing the driver’s shared default. Appends include the atomic decision groups prepared by loop.Records.
Ensure owns supervised log adoption and lazy initialization; Begin remains the explicit low-level initialization primitive. Callers own authority lifetime. WithRoot binds execution to the exact recorded model-visible workspace path; mismatches return ErrIncompatible before commands or effects can run.
WithToolResolver pins implementations to the session’s recorded descriptors after idle migration, so live inventories cannot change in-flight contracts.
Source files separate construction, driving, loading, recording, dispatch and recovery while preserving a single execution owner.
Constants
Section titled “Constants”const DefaultHookTimeout = 30 * time.SecondDefaultHookTimeout bounds a gate hook whose session records none.
const MaxParallelTools = 10MaxParallelTools is the most calls of one wave that run at once; the others wait for one to end. A model may ask for any number of calls in a turn, and each holds its result until the wave ends.
const RecordTimeout = 30 * time.SecondRecordTimeout bounds each record the driver makes whatever happens to the run’s context: the end of an effect already dispatched, and the ending of an interrupted run. They are made once ctx is done too, so the log is left consistent, but a log that waits for cancellation, as a remote store may, fails them at this deadline instead of holding Run forever.
Variables
Section titled “Variables”var ( // ErrStopped reports an execution whose command admission has closed. ErrStopped = errors.New("execution stopped") // ErrOverloaded reports a full command queue; the command was not admitted. ErrOverloaded = errors.New("command queue full") // ErrCommandConflict reports a command ID reused with different content. ErrCommandConflict = loop.ErrCommandConflict)var ( // ErrIncompatible reports a session that cannot safely resume with this driver. ErrIncompatible = errors.New("session is incompatible with this driver") // ErrNoSession is returned by Run for a session whose log is empty: // it has no SessionStarted, so there is nothing to drive. ErrNoSession = errors.New("session has not started") // ErrMissingTool is returned by Run for a session whose configuration // records a tool the driver wasn't given. The model was told the tool // exists, so the driver refuses rather than fail its calls. ErrMissingTool = errors.New("session uses a tool the driver doesn't have") // ErrToolChanged is returned by Run for a session whose configuration // records a tool whose properties differ from the driver's tool of // that name. The reducer schedules calls from the recorded // properties, so running a tool that, say, now writes would run a // write alongside other calls. ErrToolChanged = errors.New("session's tool differs from the driver's") // ErrInvalidCommand is returned by Run for a command the reducer // couldn't fold. Commands are checked before any is appended, since a // logged command that doesn't fold would break the session for good. ErrInvalidCommand = errors.New("invalid command"))var ErrCleanupBusy = errors.New("session resources are still in use")ErrCleanupBusy reports cleanup refused while runs, processes or children still use the session, or non-cleanup work remains pending.
var ErrLeaseLost = errors.New("authority over the session ended")ErrLeaseLost is the cause an Authority gives once it has ended: the lease said the grant was lost, its deadline passed before a renewal returned, or its holder released it (docs/design/durability.md, L4). The errors that carry it also wrap lease.ErrLost.
var ErrMoved = errors.New("session moved to another workspace")ErrMoved is returned by Run for a session whose workspace moved to a root other than this driver’s. The error is a *MovedError naming it.
var ErrNotPersisted = errors.New("transition not persisted")ErrNotPersisted reports a transition the log did not acknowledge as durable.
var ErrSuspended = errors.New("session suspended for input")ErrSuspended is returned by Run when the session suspended to wait for answers (docs/design/durability.md, P1): the request is recorded, nothing is in flight, and a later Run with the answers takes it up again.
Append
Section titled “Append”func Append(ctx context.Context, auth *Authority, log Log, expectSeq uint64, evs ...event.Event) errorAppend records an already numbered batch under authority, resolving only errors explicitly marked store.ErrAmbiguous. It never folds or mutates evs.
CallProvider
Section titled “CallProvider”func CallProvider(ctx context.Context, auth *Authority, p Provider, st loop.State, pending loop.Pending, opts ...EffectOption) ([]event.Payload, error)CallProvider runs one recorded, open attempt and returns its complete record group. It checks authority immediately before dispatch and keeps identity and fencing in the driver. A provider failure returns both its record group and error; a driver may replace its terminal event with AttemptEnded when retrying. Cancellation that cuts the attempt short returns no group, leaving recovery to settle it. The caller owns appending and folding the returned records. Pass the state immediately after folding this attempt’s EffectStarted so the requests match the notices the fold records for the attempt. If the caller folds more records while CallProvider runs, pass an independent snapshot using State.Clone.
CheckTools
Section titled “CheckTools”func CheckTools(st loop.State, tools map[string]Tool) errorCheckTools verifies that tools preserve the schemas, scheduling, recovery and reservation properties recorded in st. Descriptions may differ; recorded descriptions remain authoritative. Output contracts also check validators. It performs no I/O and does not modify st or tools.
InterruptedRewind
Section titled “InterruptedRewind”func InterruptedRewind(st loop.State) (event.RewindFinished, bool)InterruptedRewind returns the record that closes a rewind an earlier process left under way, if there is one (docs/design/rewind.md). A rewind whose file restore finished done goes ahead, as the user asked: its files are already back. Any other finishes failed, and the conversation stays as it is. Nothing is repeated. Close the file restore first, so its outcome is known.
Margin
Section titled “Margin”func Margin(ttl time.Duration) time.DurationMargin is how much of a grant the holder gives up as a safety margin, so its authority ends before the lease’s own expiry even if the two clocks drift a little: a tenth of the TTL.
ReleaseMaterializations
Section titled “ReleaseMaterializations”func ReleaseMaterializations(ctx context.Context, auth *Authority, log Log, blobs BlobReader, cleanup env.BundleReleaser) (st loop.State, err error)ReleaseMaterializations durably releases complete and possibly interrupted artifacts while the session is idle. auth is the caller’s supervised session authority and remains owned by the caller. The session must have only one driver or cleanup operation at a time. No provider or tools are used. The same cleanup backend used for publication and the recorded blob reader are required. Cancellation joins work; failures preserve remaining ownership. Repeating after a crash resumes the original pending cleanup. The returned state is the last acknowledged fold, including on persistence failure.
Reservation
Section titled “Reservation”func Reservation(p Provider, st loop.State, pending loop.Pending) *event.ReservationReservation returns the next attempt’s reservation from the provider request. Adapters may supply wire-specific bounds; without a byte-bound capability, the whole context window bounds input. The driver records this bound on EffectStarted; replay uses it as recorded rather than deriving it again. Non-provider effects return nil.
RunTool
Section titled “RunTool”func RunTool(ctx context.Context, auth *Authority, tools map[string]Tool, st loop.State, pending loop.Pending, opts ...EffectOption) ([]event.Payload, error)RunTool runs one recorded, open tool attempt and returns its observations and terminal event together. tools is indexed by recorded tool name. It shares immutable state only while running and owns no goroutine after returning. A stop that cuts the attempt short returns no group; recovery closes it.
StartRecords
Section titled “StartRecords”func StartRecords(st loop.State, pending []loop.Pending, tools map[string]Tool, times ...time.Time) []event.PayloadStartRecords builds the records to append atomically before dispatching pending effects. Tools that stop processes withdraw each owed wake in the same batch, so recovery cannot deliver it even if dispatch never happens. Pass the writer’s record time to compute effect deadlines with its clock.
Example
st, err := loop.Step(loop.New("s"), event.Event{Seq: 1, Payload: event.SessionStarted{Config: event.Config{ ReducerVersion: loop.Version, Provider: history.FamilyOpenAICompat, Model: "m", ToolTimeout: 30 * time.Second,}}})if err != nil { panic(err)}pending := []loop.Pending{{ID: "s/2/0", Effect: event.Effect{Kind: event.EffectRunTool, RunTool: &event.RunTool{ CallID: "call", Tool: "Describe", Input: []byte(`{}`),}}}}at := time.Unix(0, 0)// Append the returned records as one batch, then dispatch the tool.records := driver.StartRecords(st, pending, nil, at)started := records[0].(event.EffectStarted)fmt.Println(started.Attempt, started.Deadline.Sub(at))// Output: 1 30sOutput:
1 30sfunc Times(j loop.ScheduledMessage) cron.ScheduleTimes is when the recurring schedule j fires.
Acceptance
Section titled “Acceptance”type Acceptance struct { Seq uint64 Duplicate bool}Acceptance describes the original durable acceptance of a command.
type Ack struct { // contains filtered or unexported fields}Ack resolves once with the sequence of the command’s original acceptance, or the error that prevented it. Cancelling Wait never cancels admission.
Ack.Accepted
Section titled “Ack.Accepted”func (a *Ack) Accepted(ctx context.Context) (Acceptance, error)Accepted waits for the full acceptance, including whether this was a resend. Like Wait, cancelling ctx stops only the wait.
Ack.Wait
Section titled “Ack.Wait”func (a *Ack) Wait(ctx context.Context) (uint64, error)Wait waits for durable acceptance. A suppressed wake without a prior acceptance resolves with sequence zero. ctx controls only this wait.
Authority
Section titled “Authority”type Authority struct { // contains filtered or unexported fields}Authority is a session’s lease, held and supervised: the right to write the session’s log and dispatch its effects, for as long as the grant lasts. It renews the grant in the background and times it on the holder’s own clocks, from just before each request, so the lease’s clock never matters (docs/design/durability.md, L3, L4): the monotonic clock, which no one sets, and the wall clock, which runs on while the machine sleeps and the monotonic clock stops. Authority ends when either passes the deadline. Once it has ended it never comes back. An Authority is safe for concurrent use; Release must be called to stop its supervision.
Acquire
Section titled “Acquire”func Acquire(ctx context.Context, l Lease, session string) (*Authority, error)Acquire takes the session’s lease and supervises it from then on. It reads the clock just before asking, so a grant that arrives late is timed from before it was asked for; a grant that arrives after the deadline it would set is released at once, and Acquire returns ErrLeaseLost. Any error from the lease, such as lease.ErrHeld, is returned as it is.
Authority.Bind
Section titled “Authority.Bind”func (a *Authority) Bind(ctx context.Context) (context.Context, context.CancelFunc)Bind returns a context derived from ctx that is also cancelled, with ErrLeaseLost as its cause, when authority ends. Calling the returned function releases its resources.
Authority.Check
Section titled “Authority.Check”func (a *Authority) Check() errorCheck returns nil while authority lasts, and ErrLeaseLost, or why it ended, once it hasn’t. A driver checks it before appending and right before every dispatch (docs/design/durability.md, C3, L5).
Authority.Release
Section titled “Authority.Release”func (a *Authority) Release(ctx context.Context) errorRelease ends authority at once, which cancels everything bound to it and any renewal in progress, waits for the supervisor to return, and gives the lease up, so the next holder needn’t wait for it to expire (docs/design/durability.md, L6). It tries to release even if authority had already ended, since the lease’s own grant may still be live; a lease that answers ErrLost has nothing to give up. If ctx ends while the supervisor is still in a renewal that ignores cancellation, Release returns ctx’s error and the renewal finishes on its own. Releasing again does nothing.
Authority.Token
Section titled “Authority.Token”func (a *Authority) Token() lease.TokenToken returns the lease’s token, the proof of authority stores check with every append.
BlobReader
Section titled “BlobReader”type BlobReader interface { Get(ctx context.Context, session string, ref blob.Ref) ([]byte, error)}BlobReader supplies a session’s recorded bundle contents. A store.BlobStore implements it.
Classification
Section titled “Classification”type Classification struct { // Verdict is event.ClassifyAllow, ClassifyDeny or ClassifyUncertain. Verdict event.ClassifyVerdict Reason string Usage *event.Usage}Classification is a classifier’s answer.
Classifier
Section titled “Classifier”type Classifier interface { Classify(ctx context.Context, r loop.Review) (Classification, error)}Classifier judges actions for auto mode. Classify must honour ctx, which ends at the classification’s deadline. Usage is what the classification spent, charged against the session’s budget.
Commands
Section titled “Commands”type Commands struct { // contains filtered or unexported fields}Commands is a bounded, nonblocking command source. Its driver owns closing admission and resolving each admitted acknowledgment. It is safe for concurrent use.
NewCommands
Section titled “NewCommands”func NewCommands(capacity int) (*Commands, error)NewCommands returns a queue of at most capacity commands; capacity must be positive.
Commands.Close
Section titled “Commands.Close”func (c *Commands) Close(err error)Close closes admission and resolves every pending acknowledgment and process command with err, or with ErrStopped if err is nil. Run does this itself when it returns; a host whose execution fails before Run starts must do it, or a request queued meanwhile waits for a driver that never runs. Closing a closed queue resolves nothing more.
Commands.DropSuppressed
Section titled “Commands.DropSuppressed”func (c *Commands) DropSuppressed(st loop.State) boolDropSuppressed removes a startup command whose wake the lease holder has suppressed. A prior acceptance retains its acknowledgment sequence.
Commands.Poke
Section titled “Commands.Poke”func (c *Commands) Poke() (*Ack, error)Poke asks the driver to inspect its inbox without recording a command. Its acknowledgment resolves after the scan, with the current log sequence. It returns ErrStopped when admission has closed; the host then starts another execution. Pokes coalesce and do not consume command queue capacity.
Commands.RecordWithdrawnExit
Section titled “Commands.RecordWithdrawnExit”func (c *Commands) RecordWithdrawnExit(ctx context.Context, end event.ProcessEnded) errorRecordWithdrawnExit records an observed exit if its process is still running and has withdrawn its wake. It admits no command and starts no run.
Commands.Send
Section titled “Commands.Send”func (c *Commands) Send(cmd event.Command) (*Ack, error)Send atomically admits a copy of c or reports overload or closure.
Commands.StopProcess
Section titled “Commands.StopProcess”func (c *Commands) StopProcess(ctx context.Context, handle string, stop func(context.Context, loop.Process) (event.ProcessEnded, error)) (event.ProcessEnded, error)StopProcess asks the execution holding the lease to withdraw a process’s wake and record any confirmed ending. Stop runs only for a recorded running process, under the writer’s authority, and must honor cancellation.
type Delta struct { Session string EffectID string // Attempt is the attempt that streamed the delta. A retried call // streams again from the start, so a host discards what earlier // attempts streamed. Attempt int // Model is set for a model call's delta. Model *provider.Event // Output is set for what a running tool printed. Output *ToolOutput}Delta is a live piece of an effect’s output, as it streams: a model call’s text, readable reasoning or tool input, or what a running tool prints. Deltas are never recorded: the effect’s ending is, with its whole response or result.
DeltaSink
Section titled “DeltaSink”type DeltaSink interface { Delta(Delta)}DeltaSink receives live deltas. They are never persisted, so a sink must treat them as lossy. The driver calls Delta from the goroutine streaming the call or running the tool, so Delta must not block: a slow consumer drops deltas rather than holding up the session.
Driver
Section titled “Driver”type Driver struct { // contains filtered or unexported fields}Driver runs the effects the reducer asks for and records them in the session log. It holds no per-session state, so one Driver can drive any number of sessions; it is safe for concurrent use as long as each session is driven by one Run at a time, which the lease ensures.
func New(log Log, p Provider, opts ...Option) (*Driver, error)New returns a driver that records sessions in log and calls the model through p. A nil p is allowed when WithProviderResolver supplies every recorded family and model.
Driver.Begin
Section titled “Driver.Begin”func (d *Driver) Begin(ctx context.Context, auth *Authority, cfg event.Config, warnings ...event.Warning) errorBegin starts the session auth holds: it records cfg, in SessionStarted, as the first event of the session’s empty log, with warnings about how cfg was resolved in the same batch, so a degradation is never silent. An append the store can’t vouch for is settled as Run settles one (docs/design/durability.md), and a log that already holds an event is a conflict (store.ErrConflict).
Driver.CheckRoot
Section titled “Driver.CheckRoot”func (d *Driver) CheckRoot(recorded string) errorCheckRoot reports ErrIncompatible, naming both roots, unless recorded matches the root supplied with WithRoot. It performs no I/O. Hosts preparing workspace operations outside Run must check this before acting on a recorded session.
Example
// A custom host checks before workspace operations outside Run, too.p, _ := replay.New(provider.Caps{})d, _ := driver.New(mem.New(), p, driver.WithRoot("/work"))fmt.Println(d.CheckRoot("/work"))fmt.Println(errors.Is(d.CheckRoot("/other"), driver.ErrIncompatible))// Output:// <nil>// trueOutput:
<nil>trueDriver.EndWithdrawnRun
Section titled “Driver.EndWithdrawnRun”func (d *Driver) EndWithdrawnRun(ctx context.Context, auth *Authority) (bool, error)EndWithdrawnRun ends, interrupted and with no model call, a run that only process wakes a stop has withdrawn started, under auth. It does nothing else: it admits no command, fires no timer and dispatches no effect, so a stop can settle what it withdrew without starting the session’s other work. It reads only the log, so it needs no provider and diffs no workspace: a workspace baseline the run recorded goes with it, undiffed. It reports whether it ended a run; with no such run open it records nothing.
Driver.Ensure
Section titled “Driver.Ensure”func (d *Driver) Ensure(ctx context.Context, auth *Authority, resolve func(context.Context) (event.Config, []event.Warning, error)) (err error)Ensure adopts the log held by auth and initializes it only if it is empty. resolve supplies a new session’s resolved configuration and warnings; it is required but never called for an existing log. Existing configuration is kept; its recorded root is checked before the caller prepares execution. No providers or workspaces are queried.
Authority supervises adoption, resolution and the initial atomic append. The resolver must honor its context, which ends on caller cancellation or authority loss. Ensure does not release auth or drive effects: the caller owns authority until it releases it, including after an error. Begin remains the low-level operation for callers that have already established an empty durable log.
Example
ctx := context.Background()logs := mem.New()auth, err := driver.Acquire(ctx, &lease.Local{}, "job")if err != nil { panic(err)}defer func() { _ = auth.Release(context.Background()) }()model, err := replay.New(provider.Caps{}, replay.Text("Hello."))if err != nil { panic(err)}d, err := driver.New(logs, model)if err != nil { panic(err)}resolved := 0configure := func(context.Context) (event.Config, []event.Warning, error) { resolved++ return event.Config{Provider: history.FamilyOpenAICompat, ReducerVersion: loop.Version, Model: "m1", Cwd: "."}, nil, nil}for range 2 { if err := d.Ensure(ctx, auth, configure); err != nil { panic(err) }}fmt.Println("configurations resolved:", resolved)// Output: configurations resolved: 1Output:
configurations resolved: 1Driver.Fork
Section titled “Driver.Fork”func (d *Driver) Fork(ctx context.Context, auth *Authority, cfg event.Config, forked event.SessionForked) errorFork starts the session auth holds as a fork (docs/design/rewind.md): SessionStarted with cfg and then forked, in one batch, so the fork is never seen without its conversation. The log must be empty: one that holds an event is a conflict (store.ErrConflict).
Driver.Run
Section titled “Driver.Run”func (d *Driver) Run(ctx context.Context, auth *Authority, opts ...RunOption) (st loop.State, runs []event.RunFinished, err error)Run adopts and folds the log, checks compatibility, accepts cmds, reconciles open attempts and drives effects until idle. Retried attempts are settled before their next intent. It returns the last acknowledged state and the runs completed by this execution, even when failed storage refuses later reads. WithCommands supplies optional live input; WithInitialCommands admits an initial batch. Admission closes atomically with idle exit and every admitted acknowledgment resolves before Run returns.
Cancelling ctx stops dispatch and joins work. Completed record groups are persisted under RecordTimeout; cut-short attempts stay open for recovery. An accepted interrupt instead records termination and closes every effect. Lease loss prevents all further appends and dispatches, and returns ErrLeaseLost. Every append failure stops execution before another dispatch.
Example
ctx := context.Background()logs := mem.New()auth, err := driver.Acquire(ctx, &lease.Local{}, "s1")if err != nil { panic(err)}defer func() { _ = auth.Release(context.Background()) }()tok := auth.Token()// Start the session with its resolved configuration.cfg := event.Config{Provider: history.FamilyOpenAICompat, ReducerVersion: loop.Version, Model: "m1", Cwd: "."}if err := logs.Append(ctx, "s1", 0, tok, event.Event{Seq: 1, Payload: event.SessionStarted{Config: cfg}}); err != nil { panic(err)}
model, err := replay.New(provider.Caps{}, replay.Text("Hello."))if err != nil { panic(err)}d, err := driver.New(logs, model)if err != nil { panic(err)}_, runs, err := d.Run(ctx, auth, driver.WithInitialCommands(event.CommandAccepted{ CommandID: "c1", Command: event.Command{Kind: event.CommandUserMessage, UserMessage: &event.UserMessage{Text: "Hi"}},}))if err != nil { panic(err)}fmt.Println(runs[0].Outcome, runs[0].Turns)for ev, err := range logs.Read(ctx, "s1", 1) { if err != nil { panic(err) } fmt.Println(ev.Seq, ev.Kind())}// Output:// success 1// 1 session_started// 2 command_accepted// 3 run_started// 4 effect_started// 5 effect_finished// 6 run_finishedOutput:
success 11 session_started2 command_accepted3 run_started4 effect_started5 effect_finished6 run_finishedEffectOption
Section titled “EffectOption”type EffectOption func(*effectConfig)EffectOption configures one effect CallProvider or RunTool executes.
WithEffectBackground
Section titled “WithEffectBackground”func WithEffectBackground(ch <-chan struct{}) EffectOptionWithEffectBackground gives a RunTool effect ch, which the caller closes when the user asks the call to move to the background, as a BackgroundCalls command does. A tool that can, a Bash command or a subagent, then moves its work to the background and ends with a result naming the job. A driver passes it to the calls it runs.
WithEffectDeltas
Section titled “WithEffectDeltas”func WithEffectDeltas(sink DeltaSink) EffectOptionWithEffectDeltas passes the effect’s live deltas to sink, as WithDeltas does for a Driver: a model call’s pieces, or what a tool prints.
WithEffectEnvironment
Section titled “WithEffectEnvironment”func WithEffectEnvironment(e env.Environment) EffectOptionWithEffectEnvironment supplies the host-owned environment for one tool effect.
FileHistory
Section titled “FileHistory”type FileHistory interface { PutVersion(ctx context.Context, session string, data []byte) (blob.Ref, error) PruneVersions(ctx context.Context, session string, keep func(digest string) bool) error}FileHistory is the part of a store’s checkpoint history the driver uses; store.FileHistory implements it.
HookRunner
Section titled “HookRunner”type HookRunner interface { RunHook(ctx context.Context, id, name string, in event.HookInput) (event.HookResult, error)}HookRunner runs gate hooks by the names sessions record. RunHook must honour ctx, which ends at the invocation’s deadline, and return by then; an error, including one for a name it doesn’t know, makes the gate fail closed. id is the invocation ID, stable across a crash and re-invocation, so a host can deduplicate side effects.
InputCallback
Section titled “InputCallback”type InputCallback func(ctx context.Context, requestID string, req event.AwaitInput) (event.AnswerInput, error)InputCallback answers a request for human input while the driver waits (event.InputCallback). It must honour ctx, which ends at the request’s expiry. An error, a panic or ctx ending fails the request closed: it is answered as if no human were available.
LandedObserver
Section titled “LandedObserver”type LandedObserver interface { Landed(session string, last uint64)}LandedObserver is implemented by a Log that wants to hear that an append it reported as store.ErrAmbiguous did land. The driver calls Landed once it has read the write back, with the seq of the batch’s last event, so a log that tells its readers about appends as they succeed can tell them about this one too: until then it could only have said the outcome was unknown.
type Lease interface { Acquire(ctx context.Context, session string) (lease.Grant, error) Renew(ctx context.Context, t lease.Token) (lease.Grant, error) Release(ctx context.Context, t lease.Token) error}Lease is the part of a lease an Authority uses; lease.Lease implements it.
type Log interface { Adopt(ctx context.Context, session string, token lease.Token) (uint64, error) Append(ctx context.Context, session string, expectSeq uint64, token lease.Token, evs ...event.Event) error Read(ctx context.Context, session string, fromSeq uint64) iter.Seq2[event.Event, error]}Log is the part of a log store the driver uses; store.LogStore implements it.
MovedError
Section titled “MovedError”type MovedError struct { Root string}MovedError names the root a session moved to. The host takes the session up again with an environment and a driver at Root (docs/design/transitions.md).
MovedError.Error
Section titled “MovedError.Error”func (e *MovedError) Error() stringMovedError.Unwrap
Section titled “MovedError.Unwrap”func (e *MovedError) Unwrap() errorUnwrap returns ErrMoved.
Option
Section titled “Option”type Option func(*Driver)Option configures a Driver.
WithBatchLimit
Section titled “WithBatchLimit”func WithBatchLimit(n int) OptionWithBatchLimit sets the most bytes of encoded events the driver puts in one append. The default is store.MaxBatchBytes, which every store accepts; a host whose store takes less sets its own.
WithBlobs
Section titled “WithBlobs”func WithBlobs(blobs BlobReader) OptionWithBlobs supplies recorded bytes for materialization. Source files are never consulted. Sessions recording Materializer require this and an Environment implementing env.Materializer on every resume.
WithCapture
Section titled “WithCapture”func WithCapture(c observe.Capture) OptionWithCapture records the content c opts in to on the driver’s spans. It does nothing without an observer.
WithClassifier
Section titled “WithClassifier”func WithClassifier(c Classifier) OptionWithClassifier sets the auto-mode classifier. A classification without one fails closed.
WithClock
Section titled “WithClock”func WithClock(now func() time.Time) OptionWithClock sets the clock that stamps appended events. The default is time.Now.
WithDeltas
Section titled “WithDeltas”func WithDeltas(sink DeltaSink) OptionWithDeltas passes live deltas to sink.
WithEnvironment
Section titled “WithEnvironment”func WithEnvironment(e env.Environment) OptionWithEnvironment supplies the host-owned environment custom tools use. Supply its model-visible workspace root separately with WithRoot.
WithExclusiveTools
Section titled “WithExclusiveTools”func WithExclusiveTools(names ...string) OptionWithExclusiveTools names the tools whose calls hold the mutation lock’s exclusive side, such as a check whose result is only evidence if nothing else changes the workspace while it runs. Without a mutation lock it does nothing.
WithFileHistory
Section titled “WithFileHistory”func WithFileHistory(h FileHistory) OptionWithFileHistory supplies the storage h in which the driver keeps checkpoints for sessions that record Config.Checkpoints; a session’s own setting, recorded as it starts, decides whether it has them, so a host that keeps checkpoints off for new sessions still keeps them for the sessions that recorded them. The driver saves each file a trusted tool that names its path changes before the call starts, and the changed tracked files at each point’s run start (docs/design/checkpoints.md). The environment must implement env.FileObserver.
WithHooks
Section titled “WithHooks”func WithHooks(r HookRunner) OptionWithHooks sets the runner of the gate hooks sessions record. A session that records hooks fails each invocation closed without one.
WithInbox
Section titled “WithInbox”func WithInbox(inbox store.Inbox) OptionWithInbox supplies observer occurrences to admit under the session’s lease. Run checks it after queued commands and between effect dispatches. Pending seals ranges before acceptance; Trim happens only after durable acceptance. The host retains ownership of inbox and must make it safe for concurrent use.
WithInputCallback
Section titled “WithInputCallback”func WithInputCallback(cb InputCallback) OptionWithInputCallback sets the callback that answers requests for sessions whose input policy is event.InputCallback.
WithInteractiveWakes
Section titled “WithInteractiveWakes”func WithInteractiveWakes(interactive bool) OptionWithInteractiveWakes declares that the host can route joining follow-up input to a person (including an external suspend/answer interface). A callback also implies presence. Admission records the choice; recovery never recomputes it.
WithMutationLock
Section titled “WithMutationLock”func WithMutationLock(l RWLocker, exempt ...string) OptionWithMutationLock makes every tool call that may change state hold l’s shared side while it runs, except the exempt tools, such as one that waits for a child session. Sessions driven by one driver, a parent and its children, then edit at once, while a tool WithExclusiveTools names never runs beside them.
WithObserver
Section titled “WithObserver”func WithObserver(o observe.Observer) OptionWithObserver reports the driver’s live work to o as spans and metrics: an execution span per Run after loading the log, with turn spans for the model calls, compactions and tool calls. Tool spans hold PreToolUse and PermissionRequest hooks, classification, approval waits and tool runs. Other hooks and compactions sit under the active turn or, if none is open, the execution. Counters cover tokens (the classifier’s included), tool calls, PermissionDecided records, compactions and retries. Replaying a log reports nothing. Each execution with valid span IDs records them as ExecutionTraced, so the next one, here or in another process, links to it. A tool’s context carries its run span, so a subagent started by a tool nests under it. Spans carry the attributes the Run’s context carries (observe.WithAttrs). Suspension, caller context cancellation and a recorded interruption set zelk.outcome on the execution span and leave its error status unset.
WithPowerShellAnalysis
Section titled “WithPowerShellAnalysis”func WithPowerShellAnalysis(analyzer permission.PowerShellAnalyzer) OptionWithPowerShellAnalysis supplies the parser used for live permission decisions. The caller owns its lifetime.
WithProcessEnd
Section titled “WithProcessEnd”func WithProcessEnd(release func(session, handle, procID string)) OptionWithProcessEnd sets a callback for releasing a process after a record that ends it commits: a withdrawn process’s end, or a watch’s final occurrence. It receives the recorded process ID so a reused handle cannot release another process. The callback must be idempotent and may run concurrently for different sessions.
WithProviderResolver
Section titled “WithProviderResolver”func WithProviderResolver(resolve func(context.Context, history.Family, string) (Provider, error)) OptionWithProviderResolver supplies the host’s provider wiring for each recorded family and model. The resolver must be safe for concurrent use and return a provider of the requested family. It is called before accepting model changes, on reopen, and before dispatch. Without it only p’s family is available. The host owns every returned provider and its lifetime. When supplied, New accepts a nil default provider.
WithReadOnlyCalls
Section titled “WithReadOnlyCalls”func WithReadOnlyCalls(readOnly func(tool string, input json.RawMessage) bool) OptionWithReadOnlyCalls tells the mutation lock which calls of a tool that may change state change nothing, such as a shell command the read-only allowlist accepts: they run without the lock, beside the work of the sessions that share it, as read-only tools do. It decides scheduling only; the permission decision is the reducer’s.
WithRetry
Section titled “WithRetry”func WithRetry(r Retry) OptionWithRetry sets how failed model calls are retried. The default is DefaultRetry.
WithReviewFacts
Section titled “WithReviewFacts”func WithReviewFacts(f ReviewFacts) OptionWithReviewFacts sets how the host measures those facts. Without it the reviewer judges such actions as it does any other.
WithRoot
Section titled “WithRoot”func WithRoot(root string) OptionWithRoot supplies the workspace’s model-visible root, matching the Environment and tools the host injects. It must be empty or a clean absolute path. Drive-absolute Windows roots accept either separator and are recorded with forward slashes. Ensure, Begin and Run refuse a different recorded root with ErrIncompatible. Comparison is exact: symlinks are not resolved, since the reducer uses lexical paths and the Environment need not be on the host filesystem. Omitting this option permits only rootless sessions; it never adopts a recorded root.
WithShells
Section titled “WithShells”func WithShells(names ...string) OptionWithShells declares the shell tools this driver runs commands with, primary first, such as “PowerShell” and “Bash”. A session must record the same shells to run its commands: what it decided about a command was decided in their dialects. A driver that declares none runs no shell commands, so it takes any session.
Example
logs := mem.New()model, err := replay.New(provider.Caps{}, replay.Text("Hello."))if err != nil { panic(err)}// The driver names the shell tools it runs commands with, primary// first. Its sessions record event.Config{Shells: ...} the same.d, err := driver.New(logs, model, driver.WithShells("PowerShell", "Bash"))fmt.Println(d != nil && err == nil)// Output: trueOutput:
trueWithToolMigration
Section titled “WithToolMigration”func WithToolMigration(migrate func(event.Config) (event.Config, error)) OptionWithToolMigration supplies the host’s explicit, pure upgrade of an idle session’s recorded tool set. migrate is given the session’s configuration and returns it with the tools changed: only its Tools, DeferredTools and MCP status are recorded, so a migration can add or drop tools, and defer them, but changes nothing else. It must copy slices/maps before changing them. The driver validates the candidate configuration and tools before recording ConfigChanged under the session lease. Busy sessions cannot migrate. Without this option unrelated tool changes are refused by CheckTools.
WithToolPreparation
Section titled “WithToolPreparation”func WithToolPreparation(prepare func(context.Context, event.Config) error) OptionWithToolPreparation waits for live discovery before migrating an idle session. prepare is called after root validation and before tool migration, never for active/suspended runs or cleanup. It must honor ctx and be concurrency-safe.
WithToolResolver
Section titled “WithToolResolver”func WithToolResolver(resolve func(context.Context, event.ToolSpec) (Tool, error)) OptionWithToolResolver supplies implementations for a session’s recorded descriptors after idle migration. A nil result uses the static tool. Each execution keeps its resolved map until it ends, so inventory changes cannot alter validation or dispatch of an already authorized call. resolve must be concurrency-safe. The driver checks each implementation against its recorded contract.
WithTools
Section titled “WithTools”func WithTools(ts ...Tool) OptionWithTools gives the driver the tools sessions may call, by their descriptors’ names. Every tool a session’s configuration records must be among them.
WithWorkspaceMoves
Section titled “WithWorkspaceMoves”func WithWorkspaceMoves(worktree bool) OptionWithWorkspaceMoves lets the driver move a session recorded at another root to its own, instead of refusing it: resuming from another directory, or after the worktree a session moved to is gone. The session must own nothing bound to its old workspace and have nothing running there. worktree says whether the driver’s root is a git worktree of the session’s own, which the move records as the session’s Config.Worktree.
OutputValidators
Section titled “OutputValidators”type OutputValidators interface { Validators() []string}OutputValidators is implemented by the StructuredOutput tool: it names the host validators it can run. A session whose contract names one it lacks can’t be driven, since skipping a validator would accept values the session promised to reject.
PersistenceError
Section titled “PersistenceError”type PersistenceError struct { Err error Usage event.Usage}PersistenceError preserves both the append error and measured usage that was not recorded. An ambiguous batch may have landed; recovery decides from the log.
PersistenceError.Error
Section titled “PersistenceError.Error”func (e *PersistenceError) Error() stringPersistenceError.Unwrap
Section titled “PersistenceError.Unwrap”func (e *PersistenceError) Unwrap() []errorUnwrap exposes the persistence sentinel and the underlying append error.
Preparer
Section titled “Preparer”type Preparer interface { Prepare()}Preparer is a classifier with work to do before it can answer, such as checking its model. The driver calls Prepare whenever a session it runs is in auto mode, from the start of a run or once a mode change takes effect, so that the work starts before the first review is due rather than at it. Prepare must return promptly and is called many times: the first call starts the work, and the rest do nothing.
Provider
Section titled “Provider”type Provider interface { Family() history.Family Stream(ctx context.Context, req *provider.Request) (provider.Stream, error)}Provider is the part of a model provider the driver uses; provider.Provider implements it.
RWLocker
Section titled “RWLocker”type RWLocker interface { sync.Locker RLock() RUnlock()}RWLocker is a lock with a shared and an exclusive side, as *sync.RWMutex is.
type Retry struct { // MaxAttempts is the most attempts a call gets, the first included; // 1 turns retrying off. MaxAttempts int // Malformed is the most attempts a call gets when the last one's // response was malformed, counting every attempt before it. A decoder // at odds with its provider fails every time, so this is kept below // MaxAttempts; 0 or 1 doesn't retry a malformed response. Malformed int // Base is the initial backoff; Max caps computed waits after jitter. Base, Max time.Duration // MaxRetryAfter caps provider-requested waits independently of Max. // Zero uses ten minutes; a negative value is invalid. MaxRetryAfter time.Duration // Random supplies a sample in [0, 1) for each computed backoff. // It must be safe for concurrent use. Nil uses a source owned by the driver. Random func() float64}Retry says how the driver retries a model call that failed in a way worth retrying: it was never dispatched, failed transiently, was rate-limited, or got a malformed response (provider.Retryable). Each retry is a new attempt of the same effect, recorded with its own EffectStarted after a Warning saying why.
The computed wait before attempt n+1 is Base·2^(n-1), jittered by up to 20% in either direction and capped at Max. A positive Retry-After instead waits at least the unjittered backoff, without jitter, and is accepted up to MaxRetryAfter (zero means ten minutes). The driver records the actual wait in its warning and absolute retry deadline before waiting.
Example
policy := driver.DefaultRetry()policy.MaxRetryAfter = 2 * time.Minute// An injected source makes computed waits reproducible. A sample of .5// leaves the exponential backoff unchanged; Retry-After never draws jitter.policy.Random = func() float64 { return .5 }fmt.Println(policy.Max, policy.MaxRetryAfter)// Output: 30s 2m0sOutput:
30s 2m0sDefaultRetry
Section titled “DefaultRetry”func DefaultRetry() RetryDefaultRetry is the retry policy a Driver uses unless told otherwise: ten attempts with one-second exponential backoff, jittered by up to 20% and capped at 30 seconds, and a separate ten-minute cap on Retry-After. Without Retry-After the waits total about two and a half minutes. A usage limit is never retried. A malformed response gets three attempts: enough to outlast a stream corrupted once without spending ten paid calls on a decoder at odds with its provider. Driver construction supplies a private random source when Random is nil; tests can inject a deterministic one.
ReviewFacts
Section titled “ReviewFacts”type ReviewFacts func(ctx context.Context, dir string, r loop.Review) ([]string, error)ReviewFacts measures what a host can tell the reviewer about an action that can discard unsaved work. It returns facts it measured itself and never text from the workspace, which the agent can write: the reviewer reads them as trusted. dir is the absolute directory the action starts in, since r.Cwd is relative to the workspace. Facts must honour ctx.
RunOption
Section titled “RunOption”type RunOption func(*runConfig)RunOption configures one execution. Options are applied before work starts.
WithCommands
Section titled “WithCommands”func WithCommands(commands *Commands) RunOptionWithCommands supplies the live command source for one execution. Run closes admission and resolves every accepted command before returning.
WithInitialCommands
Section titled “WithInitialCommands”func WithInitialCommands(cmds ...event.CommandAccepted) RunOptionWithInitialCommands admits cmds before dispatch. The option copies the batch; command payloads must remain immutable throughout Run.
WithLaunchSetup
Section titled “WithLaunchSetup”func WithLaunchSetup(setup func(context.Context, loop.State) (event.Config, error)) RunOptionWithLaunchSetup makes the execution a launch taking the session up with the host’s own setup, as Claude Code’s resume does: an idle session’s recorded configuration takes what setup returns for the permission policy, the run limits (MaxTurns, Budget, MaxTime, CallTimeout, ToolTimeout), the classifier, how input is answered and the model route (Provider, Model, Settings, Capabilities, ToolReserves). Nothing else it returns is recorded. setup is given the session’s folded state, after any tool migration, and must copy slices/maps before changing them. The change is recorded as ConfigChanged, with the tool migration’s, under the session lease; one that changes nothing records nothing. A busy or suspended session keeps its configuration.
type Tool interface { Descriptor() tool.Descriptor InputSchema() json.RawMessage Run(ctx context.Context, c tool.Call, input json.RawMessage) (tool.Result, error)}Tool is the part of a tool the driver uses; tool.Tool implements it. Run must be safe for concurrent use: read-only tools run in parallel. The driver gives each call its own tool.Call and records what the call recorded there just before the call’s end.
ToolOutput
Section titled “ToolOutput”type ToolOutput struct { CallID string Text string}ToolOutput is a piece of what a running tool printed, such as a command’s output as it runs. The model sees only the tool’s result.