Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/loop"

Package loop is zelk’s agent loop as a pure reducer.

Step folds one logged event into a State. Its pending effects and run ending tell the driver what to do next. It does no I/O, reads no clock, draws no randomness and never observes the outside world, so folding a session’s log always rebuilds the same state and the same pending effects. That is what makes replay, resume and hosts’ own drivers possible.

A State is plain data and encodes to JSON. The pending effects are part of it, so the reducer knows exactly which effects and attempts are open; Recover plans their reconciliation after a stop, and Records builds the records a fold owes, which a driver appends in the same batch.

The session’s lifecycle (whether a run is under way, how it is ending, what it waits for) is a set of facts with rules between them and the changes each event may make, described in docs/design/loop-states.md. Each event’s fold checks named admission rules against those facts before it changes anything. The promises a driver relies on are in docs/design/durability.md and docs/design/transitions.md.

Policy lives in internal packages (completion, compaction, accounting); this package owns its durable sequencing. Source files group command folds, attempt transitions, model turns, tool waves and run endings; Step dispatches each payload to its fold.

const (
PartSystem = "System prompt"
PartContext = "Session context"
PartMCPNotes = "MCP server instructions"
PartDeferred = "Deferred tool index"
PartMemory = "Memory"
PartSkills = "Skills"
PartTools = "Built-in tools"
PartMessages = "Messages"
PartToolCalls = "Tool calls"
PartToolResults = "Tool results"
PartImages = "Images"
)

The parts of a model call that ContextParts names.

const (
HookSessionStart = "SessionStart"
HookUserPromptSubmit = "UserPromptSubmit"
HookPreToolUse = "PreToolUse"
HookPermissionRequest = "PermissionRequest"
HookPermissionDenied = "PermissionDenied"
HookPostToolUse = "PostToolUse"
HookPostToolUseFailure = "PostToolUseFailure"
HookPostToolBatch = "PostToolBatch"
HookStop = "Stop"
HookSubagentStop = "SubagentStop"
HookSubagentStart = "SubagentStart"
HookPreCompact = "PreCompact"
HookPostCompact = "PostCompact"
HookPreModelSwitch = "PreModelSwitch"
HookPostModelSwitch = "PostModelSwitch"
)

The hook events. Gate events run as run_hook effects recorded with HookDecided; the observe-only ones are the host’s to run asynchronously and never reach the log.

const (
// CronCreateTool creates a cron: a prompt posted at the times a cron
// expression names, recurring or once.
CronCreateTool = "CronCreate"
// CronListTool lists the conversation's pending crons.
CronListTool = "CronList"
// CronDeleteTool deletes a pending cron.
CronDeleteTool = "CronDelete"
)

The tools a conversation schedules prompts into itself with.

const MaxRetainedDenials = 128

MaxRetainedDenials bounds the actions a host may request to review again.

const MaxTruncations = 2

MaxTruncations bounds the continuations a run gets for model turns the output limit cut off without a tool call; the next such turn ends the run incomplete.

const OutputTool = "StructuredOutput"

OutputTool is the StructuredOutput tool’s name. Its contracts must use the canonical subset, including run-specific outputs.

const Version = event.Generation

Version is the format generation a session’s configuration records, the same as the event envelopes’ (event.Generation): a session is folded and resumed only by a reducer of exactly that generation. A change to how the log folds raises it, and a log of another generation is refused rather than folded under rules it wasn’t written by.

const WatchTool = "Watch"

WatchTool starts a command whose output lines wake the session; its command is decided as a Bash command (docs/design/wakes.md).

var ErrCommandConflict = errors.New("command ID reused with different content")

ErrCommandConflict reports reuse of a command ID with different content.

var ErrIncompatible = errors.New("session incompatible with this reducer")

ErrIncompatible is returned by Compatible for a session this reducer can’t resume.

var ErrInconsistent = errors.New("event doesn't follow from the log")

ErrInconsistent is returned by Step for an event that can’t follow the state: a gap in sequence numbers, an effect event for an effect that isn’t pending, or a log that doesn’t start with SessionStarted.

var ErrNewerLog = errors.New("event written by a newer version of zelk")

ErrNewerLog is returned by Step for an event written by a newer version of zelk: a kind this version doesn’t know, or a configuration recorded by a newer reducer. Such a log can still be read as events, but this reducer can’t fold it.

var ErrNoImages = errors.New("this session's model doesn't take images")

ErrNoImages reports a message with an image for a session whose model doesn’t take images.

func Compatible(st State) error

Compatible reports whether this reducer can resume st, wrapping ErrIncompatible if not. Unknown versions and a state with no session started are always refused.

func CopyAnswer(a event.AnswerInput) *event.AnswerInput

CopyAnswer returns a copy of a that shares nothing with it.

func EffectID(session string, seq uint64, index int) string

EffectID returns the ID of the index-th effect (from 0) that Step asked for while folding the event at seq. It is deterministic, so folding a log again yields the same IDs, and it is unique across sessions, since a child session’s ID derives from its parent effect’s.

Example

// The second effect asked for while folding event 12 of session s1.
fmt.Println(loop.EffectID("s1", 12, 1))
// Output: s1/12/1

Output:

s1/12/1
func InputResult(st State, id string) ([]history.Item, error)

InputResult is the result a resolved request gives its call. The driver records it in the request’s EffectFinished; the fold checks it.

func InstructionsText(i event.InstructionsLoaded) string

InstructionsText frames project instructions for the model: repository content, with less authority than the user and the host.

func NativeReserve(st State, cp *event.CallProvider) int64

NativeReserve is the input a compaction call reserves beyond its own request: the provider’s native compaction of the whole window, when the call asks for one (B2).

func Owed(k event.Kind) bool

Owed reports whether the reducer may owe a payload of kind k: one recorded right after the event that led to it, in the same append, so a record group ends at the next event of another kind. A Warning is one, though a host may also record one alone.

func PolicyOf(p *event.Policy) (permission.Policy, error)

PolicyOf converts a policy as a session records it.

func ProviderRequest(st State, cp *event.CallProvider) *provider.Request

ProviderRequest renders a pending call for the provider. It omits withdrawn process notices that were never seen and replaces images with text notes when the current model takes no images. It is separate from Request because replay derives compaction scheduling and fold reservations from Request; the fold must not see this swap. Unchanged parts share immutable state; callers must not mutate the returned slices or their contents.

Example

st, err := loop.Step(loop.New("session"), event.Event{Seq: 1, Payload: event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version, Model: "text-model"}}})
if err != nil {
panic(err)
}
// Drivers use this view for dispatch, adapter bounds and prompt capture.
req := loop.ProviderRequest(st, &event.CallProvider{Model: st.Config().Model})
fmt.Println(req.Model, len(req.History))
// Output: text-model 0

Output:

text-model 0
func QuotaLimit(q *event.Quotas, scope, resource string) int64

QuotaLimit returns the limit a session’s quota sets on resource in scope, 0 for none.

func RecordPolicy(p permission.Policy) *event.Policy

RecordPolicy returns a policy as a session records it.

func Records(st State, at time.Time, ps ...event.Payload) ([]event.Event, error)

Records prepares one atomic append group, including the deterministic decision records caused by its payloads. It leaves st untouched and performs no I/O. Hosts driving Step directly must append this complete group before dispatching any resulting effects, then fold the committed events in order. A failed append leaves the original state authoritative; never use the preview fold. Payloads before a session starts are numbered as they come.

Example

st := loop.New("session")
records, err := loop.Records(st, time.Time{}, event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version}})
if err != nil {
panic(err)
}
// Append this complete group atomically; fold only after the append succeeds.
for _, ev := range records {
fmt.Println(ev.Seq, ev.Kind())
}
fmt.Println("acknowledged sequence:", st.Seq())
// Output:
// 1 session_started
// acknowledged sequence: 0

Output:

1 session_started
acknowledged sequence: 0
func Recover(st State) []event.Payload

Recover plans reconciliation from durable state without I/O or a clock. Persisted termination always wins. Each open attempt is either closed for retry, or reconciled with an unknown result; unstarted effects need no record.

func Replacement(ap event.Approval, input json.RawMessage) string

Replacement returns the digest of the action an approval’s human edited to input: the same tool, working directory and policy revision, with the new arguments. An ApproveEdited answer must name it.

func ReportOf(st State) *event.Report

ReportOf returns the report of the run st is ending, as the driver records it before RunFinished, or nil when the session doesn’t keep reports.

func Request(st State, cp *event.CallProvider) *provider.Request

Request renders a pending model call from the recorded configuration and history. The returned slices share immutable state; callers must not mutate them.

func RunID(st State) uint64

RunID is the ID the current run’s records carry: the sequence number of the event that began it, as its RunStarted named it. It is zero while no run is going. A host that writes a run’s RunFinished or ReportRecorded itself sets their Run to it.

func SameCommand(a, b event.Command) bool

SameCommand compares command content, excluding its caller-assigned ID.

func ScheduleText(j ScheduledMessage) string

ScheduleText is the notice an occurrence of j carries: j’s text.

func SkillShellHooks(cfg event.Config) []event.HookSpec

SkillShellHooks returns the session’s PreToolUse hooks the configured shell runs, in registration order: those a skill’s command runs before it is decided, as a shell call’s run before its permission.

func TurnDiff(st State) *event.TurnDiff

TurnDiff aggregates the run’s file changes by file, in the order files were first changed: each file’s revision before its first change and after its last, and every patch. It is nil for a run that changed nothing. A driver records it with the run’s ending.

func WriteEffect(seen event.FileObserved, ok bool) string

WriteEffect is the review’s Effect for a built-in Write of a file the agent last observed as seen, if ok, or never observed.

type Acceptance struct {
// Digest is the SHA-256 of the command content, excluding its ID.
Digest string `json:"digest,omitempty"`
Command event.Command `json:"command"`
Seq uint64 `json:"seq"`
}

Acceptance is a command’s original durable acceptance.

type Account struct {
// Measured is what providers reported.
Measured event.Tokens `json:"measured,omitzero"`
// Unknown is the reservations charged for attempts whose usage is
// unknown.
Unknown event.Tokens `json:"unknown,omitzero"`
// Estimated is the estimates those attempts carried, for reporting.
Estimated event.Tokens `json:"estimated,omitzero"`
}

Account sums the charges of settled attempts (B4).

func (a Account) Charged() event.Tokens

Charged returns what enforcement counts as spent.

type Action struct {
Tool string `json:"tool"`
// Input is the call's arguments, canonicalized so equal values give
// equal digests whatever their spelling.
Input json.RawMessage `json:"input"`
Cwd string `json:"cwd"`
Revision uint64 `json:"policy_revision"`
}

Action is a proposed tool call as authorization sees it: what runs, where, and under which policy revision. A decision about one action never applies to another (docs/design/permissions.md, “Action digests”).

func (a Action) Digest() string

Digest returns the action’s stable digest, “sha256:” and 64 hex digits.

type AgentScript = event.AgentScript

AgentScript is a file an action runs that the agent wrote or changed.

type ApprovedPlan struct {
Text string `json:"text"`
// Note is what the user added when approving it.
Note string `json:"note,omitempty"`
// Revision is the goal's revision when it was approved.
Revision int `json:"revision,omitempty"`
// Done is set when a run ended successfully after the approval, in a
// session without completion reports, which can't say the goal was met.
Done bool `json:"done,omitempty"`
}

ApprovedPlan is a plan the user approved with ExitPlanMode.

func (p ApprovedPlan) Met(g Goal) bool

Met reports whether the plan is finished work: a run reported the request it served met or, in a session without reports, a run ended successfully once it was approved. Handing a finished plan on after compaction, or offering it for revision on re-entering plan mode, would set the model to do it again.

type Before struct {
History int
Compactions int
}

Before is what a callback may want of the state before an event: Step may reuse that state’s storage, so it can’t be kept.

type Breaker struct {
// Recent are the latest decisions, oldest first, true for a denial.
Recent []bool `json:"recent,omitempty"`
// Actions identifies each recent decision.
Actions []string `json:"actions,omitempty"`
// Consecutive counts the denials since the last allow or trip.
Consecutive int `json:"consecutive,omitempty"`
// Trips counts the times it interrupted a turn.
Trips int `json:"trips,omitempty"`
}

Breaker is the auto-mode circuit breaker’s state. It is folded state, so it survives resume.

type Call struct {
ID string `json:"id"`
Tool string `json:"tool"`
Input json.RawMessage `json:"input,omitempty"`
// Effect is the RunTool effect running the call, once Step has asked
// for it. A call that can't run has none.
Effect string `json:"effect,omitempty"`
// Result is the call's model-visible result, once it has one.
Result []history.Item `json:"result,omitempty"`
// PermissionNotes explain mode-sensitive decisions with this result,
// including decisions made in an intermediate mode between model calls.
PermissionNotes []string `json:"permission_notes,omitempty"`
// Approved is the action digest a human approved for this call; it
// applies only while the call's digest is still that one.
Approved string `json:"approved,omitempty"`
// Edited says Input is a human's replacement for the model's.
Edited bool `json:"edited,omitempty"`
// Offered are the rules its PermissionRequest hooks were offered to
// grant for the session.
Offered []event.Suggestion `json:"offered,omitempty"`
// Hooks are the hook invocations the call waits for; Phases the hook
// phases it has passed ("pre", "permreq", "post", "denied").
Hooks []string `json:"hooks,omitempty"`
Phases []string `json:"phases,omitempty"`
// Hook and HookReason are the combined PreToolUse (or
// PermissionRequest) decision.
Hook event.HookDecision `json:"hook,omitempty"`
HookReason string `json:"hook_reason,omitempty"`
// Raw is a result held back while result hooks decide.
Raw []history.Item `json:"raw,omitempty"`
}

Call is one tool call of a model turn and, once it has one, its result.

type CheckpointPass struct {
Point uint64 `json:"point"`
Run uint64 `json:"run"`
Seq uint64 `json:"seq"`
}

CheckpointPass is the run-start pass of a point: the record (Seq) at which every tracked path’s latest version was its content.

type CheckpointVersion struct {
// Seq is the FileVersionsSaved that saved it, in run Run; Start says
// that record was a run-start pass.
Seq uint64 `json:"seq"`
Run uint64 `json:"run"`
Start bool `json:"start,omitempty"`
event.FileVersion
}

CheckpointVersion is one saved file version and the record that saved it (docs/design/checkpoints.md).

type Child struct {
Allocation event.Tokens `json:"allocation"`
// Run is the sequence number of the run that made it, which it
// counts against while open.
Run uint64 `json:"run"`
// Finished records that what the child didn't use has come back.
Finished bool `json:"finished,omitempty"`
}

Child is one child allocation (B7).

type Claim struct {
Status event.GoalStatus `json:"status"`
Summary string `json:"summary,omitempty"`
BlockedBy string `json:"blocked_by,omitempty"`
Open []string `json:"open,omitempty"`
// Left are failing checks a met report sets aside.
Left []event.LeftCheck `json:"left,omitempty"`
// Requirements say how the model confirmed each requirement.
Requirements []event.RequirementCheck `json:"requirements,omitempty"`
// Kept says the report passed the check and stands while the run is
// sent back for its structured output alone.
Kept bool `json:"kept,omitempty"`
}

Claim is the model’s report of its run’s outcome.

type ContextPart struct {
// Name says what the part is to a person: "System prompt",
// "Project instructions (AGENTS.md)", "MCP tools (docs)", "Messages".
Name string
Bytes int64
}

ContextPart is one part of what the next model call sends, by its size as compaction measures it.

type ContextUse struct {
// Context is the last model call's measured input, cache reads
// included: how much each turn sends.
Context int64 `json:"context,omitempty"`
// Uncached is the session's measured input that no cache served.
Uncached int64 `json:"uncached,omitempty"`
// Cleared is how many times old tool results were cleared.
Cleared int `json:"cleared,omitempty"`
}

ContextUse is what a host shows of a session’s context and its cost.

type Conversation struct {
// contains filtered or unexported fields
}

Conversation is the part of a session’s state that belongs to its conversation: what the model saw and the work it set, as a rewind puts back or a fork carries into a new session (docs/design/rewind.md). The rest, what happened in the world, stays with the session.

It is plain data owned by the loop: a rewind or fork event records it as JSON, so replaying the event never reads the events before it.

func (c Conversation) History() []history.Item

History is the conversation’s history as recorded, at its raw positions: it still holds process notices a stop withdrew before any model call carried them, with the provenance that marks them. For what a reader or a fork should show, use State.VisibleConversation first.

func (c Conversation) MarshalJSON() ([]byte, error)

MarshalJSON encodes the conversation as the event that carries it records it.

func (c *Conversation) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a conversation a rewind or fork event recorded.

type DeniedAction struct {
Digest string `json:"digest"`
Tool string `json:"tool"`
Reason string `json:"reason"`
Policy uint64 `json:"policy"`
Review uint64 `json:"review"`
Seq uint64 `json:"seq"`
Retried bool `json:"retried,omitempty"`
// Input and After are what a later review is told of it: the action,
// bounded, and how many user messages preceded it.
Input string `json:"input,omitempty"`
After int `json:"after,omitempty"`
Armed bool `json:"armed,omitempty"`
Override string `json:"override,omitempty"`
}

DeniedAction is a retained classifier denial. Retried means its one-use override has been accepted, even if classification has not started yet.

type Due struct {
Input event.HookInput `json:"input"`
// Command is the ID of the command whose input the hook decides on:
// the message a UserPromptSubmit hook may block.
Command string `json:"command,omitempty"`
Gate string `json:"gate,omitempty"`
Running bool `json:"running,omitempty"`
// Block and Contexts are the decided outcome.
Decided bool `json:"decided,omitempty"`
Block bool `json:"block,omitempty"`
Reason string `json:"reason,omitempty"`
Contexts []string `json:"contexts,omitempty"`
}

Due is a hook event to run before the next model call.

type EffectState string

EffectState is where a pending effect is in its lifecycle (docs/design/durability.md, E2). An effect that has ended is no longer pending, so it has no EffectState.

const (
// EffectPending is an effect asked for and never started.
EffectPending EffectState = "pending"
// EffectRunning is an effect whose latest attempt is open.
EffectRunning EffectState = "running"
// EffectWaiting is an input request whose attempt is open while it
// waits for its answer, with nothing in flight.
EffectWaiting EffectState = "waiting"
// EffectRetryable is an effect whose latest attempt is closed and
// which hasn't ended.
EffectRetryable EffectState = "retryable"
)
type FileRestore struct {
Requested event.FileRestoreRequested `json:"requested"`
Applied []string `json:"applied,omitempty"`
Finished *event.FileRestoreFinished `json:"finished,omitempty"`
}

FileRestore is the last persisted file-restore transaction. A nil Finished means pending or interrupted work: Applied names known completions, and the remaining files may have changed. Recovery never automatically repeats file mutations.

type Goal struct {
Text string `json:"text,omitempty"`
// Revision counts the goal's changes; a decision about one revision
// never applies to another.
Revision int `json:"revision,omitempty"`
// Explicit says SetGoal set the goal; otherwise it follows the
// request.
Explicit bool `json:"explicit,omitempty"`
// Abandoned says the user abandoned the goal: completion is no longer
// enforced.
Abandoned bool `json:"abandoned,omitempty"`
// Request is the request that began the latest run.
Request string `json:"request,omitempty"`
// Met is the revision a successful run reported met. A run a wake
// starts keeps the goal, so a summary must not hand the model a met
// goal as current work.
Met int `json:"met,omitempty"`
}

Goal is a session’s goal: by default the request that began the current run, or an explicit objective a SetGoal command set.

type HookRun struct {
Hook string `json:"hook"`
// Index is the hook's registration order, which decides how results
// combine; never the order they finish in.
Index int `json:"index"`
// Gate names what waits for the decision, such as "pre:<call>".
Gate string `json:"gate"`
// Decided is the recorded decision, once folded.
Decided *event.HookDecided `json:"decided,omitempty"`
}

HookRun is a gate hook invocation whose gate hasn’t been decided yet.

type HookVerdict struct {
// Decision is the strongest decision: deny over defer over ask over
// allow. A hook that failed, timed out or answered what the gate
// doesn't know, or two that both rewrote the command, deny, as they
// would a Bash call.
Decision event.HookDecision
// Reason says why, for the user.
Reason string
// Input is the rewritten input, if a hook rewrote it: a new command,
// decided as such.
Input json.RawMessage
}

HookVerdict is the PreToolUse hooks’ combined say on a skill’s command.

func CombineSkillShellHooks(runs []HookRun) HookVerdict

CombineSkillShellHooks combines the PreToolUse runs for a skill’s command as the loop combines a shell call’s.

type InputRequest struct {
event.AwaitInput
// Resolution is the first answer or expiry folded; nil while the
// request waits.
Resolution *Settlement `json:"resolution,omitempty"`
}

InputRequest is a request for human input, from its EffectStarted until its call has its result.

type Ledger struct {
// Run is the current run's account, Session the session's.
Run Account `json:"run,omitzero"`
Session Account `json:"session,omitzero"`
// Children holds every child allocation by its ID (B7).
Children map[string]Child `json:"children,omitempty"`
// WrapUp is how far a soft limit's wrap-up turn has got (B5).
WrapUp WrapUp `json:"wrap_up,omitempty"`
// Exceeded records that a call spent more than it reserved while a
// hard limit applies, so the run makes no further call (B3).
Exceeded bool `json:"exceeded,omitempty"`
}

Ledger accounts for model tokens across attempts, crashes and child sessions (docs/design/durability.md, “Budget ledger”). Open reservations aren’t kept here: they are the reservations of the pending effects whose attempt is open.

type Materialization struct {
Bundle event.Materialize `json:"bundle"`
Publication event.SkillMaterialized `json:"publication"`
}

Materialization retains an owned publication and its recorded input. Hosts need both to recover interrupted cleanup without consulting a skill source.

type MaterializationIntent struct {
Identity string
Bundle event.Materialize
}

MaterializationIntent retains possible filesystem ownership even when a backend acted before an error, cancellation or failed completion append.

type Measure struct {
Input int64 `json:"input"`
Items int `json:"items"`
// Revision identifies the request prefix and model the usage measured.
Revision uint64 `json:"revision,omitempty"`
}

Measure is the input a model call was measured to take, and the length of the history it was sent, so the next call’s input can be estimated from it and what was added since.

type Move struct {
event.WorkspaceMovePrepared
// Committed says the session's root is already To.
Committed bool `json:"committed,omitempty"`
}

Move is a workspace move the session has prepared and not yet handed off.

type NativeWindow struct {
Family history.Family `json:"family"`
Items []history.Item `json:"items"`
Skip int `json:"skip"`
// Context is the dynamic context already included in Items, so its
// unchanged text is not prepended again on the next request.
Context string `json:"context,omitempty"`
// Protected is the deterministic handoff sent alongside opaque native items.
Protected string `json:"protected,omitempty"`
}

NativeWindow is a provider’s own compacted window. For that provider family it replaces the first Skip items of the history, which hold the portable summary and the items kept with it.

type Pending struct {
// PermissionMode snapshots a working model attempt's effective mode.
// Classifier and compaction effects leave it empty.
PermissionMode event.PermissionMode `json:"permission_mode,omitempty"`
// TaskKey snapshots the unambiguous active task when a tool is scheduled.
TaskKey string `json:"task_key,omitempty"`
ID string `json:"id"`
Effect event.Effect `json:"effect"`
// Attempt is the attempt number of the latest EffectStarted for the
// effect, or 0 if it hasn't started.
Attempt int `json:"attempt"`
// Open reports whether that attempt is still open.
Open bool `json:"open,omitempty"`
// Deadline is the latest attempt's deadline, from its EffectStarted;
// the zero time means none.
Deadline time.Time `json:"deadline,omitzero"`
// RetryAt is when a retryable effect's next attempt may start, from
// the AttemptEnded that closed the last one.
RetryAt time.Time `json:"retry_at,omitzero"`
// Reserve is what each attempt of an effect that calls a model
// reserves (B2); nil for other effects.
Reserve *event.Tokens `json:"reserve,omitempty"`
// Generation is the workspace generation a tool call's start moved
// to, or 0 if it didn't move it: a fingerprint showing the call
// changed nothing moves it back.
Generation uint64 `json:"generation,omitempty"`
// Refused says why a retryable effect's next attempt can't start: a
// hard limit refuses its reservation. The driver ends it with
// EffectCancelled.
Refused string `json:"refused,omitempty"`
}

Pending is an effect Step asked for that hasn’t ended yet. Its state (docs/design/durability.md, E2) is pending while Attempt is 0, running while Open, and retryable once an attempt has closed without ending it.

func (p Pending) Reservation(attempt int) *event.Reservation

Reservation returns the reservation attempt n records, if the effect reserves anything.

func (p Pending) Retryable() bool

Retryable reports whether the effect has had an attempt, none is open, and it hasn’t ended.

func (p Pending) State() EffectState

State is the effect’s lifecycle state, from its attempt, whether that attempt is open, and its kind.

Example

st := loop.New("s1")
log := []event.Payload{
event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version, Model: "claude", Cwd: "."}},
event.CommandAccepted{CommandID: "c1", Command: event.Command{Kind: event.CommandUserMessage, UserMessage: &event.UserMessage{Text: "hi"}}},
event.EffectStarted{EffectID: "s1/2/0", Attempt: 1, Effect: event.Effect{Kind: event.EffectCallProvider, CallProvider: &event.CallProvider{Model: "claude"}}},
}
for _, p := range log {
// Records adds the decisions the fold owes after p.
records, err := loop.Records(st, time.Time{}, p)
if err != nil {
panic(err)
}
for _, ev := range records {
if st, err = loop.Step(st, ev); err != nil {
panic(err)
}
}
for _, p := range st.Pending() {
fmt.Println(p.ID, p.State())
}
}
// Output:
// s1/2/0 pending
// s1/2/0 running

Output:

s1/2/0 pending
s1/2/0 running
type Process struct {
event.ProcessStarted
// Running is false once the process is recorded as ended: its output
// collected, or it was killed or lost.
Running bool `json:"running,omitempty"`
// Exited says the process exited, as its completion notice recorded,
// with Code and Signal; while Running is still true its output isn't
// collected yet.
Exited bool `json:"exited,omitempty"`
Code int `json:"code,omitempty"`
Signal string `json:"signal,omitempty"`
// Killed says its recorded ending was a kill someone asked for.
Killed bool `json:"killed,omitempty"`
// WakeWithdrawn suppresses subsequent wakes independently of the process exit.
WakeWithdrawn bool `json:"wake_withdrawn,omitempty"`
// Ended holds the first recorded exit, a ProcessEnded's or the one a
// watch's admitted final occurrence carried, even if another writer
// repeated it.
Ended *ProcessExit `json:"ended,omitempty"`
// Lost says it was recorded as gone: nothing could find it again, so
// how it ended is unknown.
Lost bool `json:"lost,omitempty"`
// Tainted says a background check had another possible writer running
// beside it: its evidence can't pass.
Tainted bool `json:"tainted,omitempty"`
}

Process is a background process a tool started.

type ProcessExit struct {
Code int `json:"code"`
Signal string `json:"signal,omitempty"`
}

ProcessExit is the first exit recorded for a handle.

type Refusal = event.Refusal

Refusal is an action the reviewer refused earlier in the session.

type Replay struct {
// contains filtered or unexported fields
}

Replay folds a stored log in which recorded decisions win (docs/design/durability.md, “Recorded decisions”). A heuristic’s outcome, a permission verdict or a completion decision for instance, is recorded right after the event that led to it, in the same atomic append. Step derives each again and refuses a log that recorded another, which is what a live fold and the tests want. Replay instead hands the reducer the decisions recorded after each event, and the reducer uses them, so a log written before a heuristic changed folds as it ran. Recorded decisions must still be structurally valid.

Replay holds each event until the decisions recorded with it have arrived: until the next event that isn’t a decision, or Flush. Appends are atomic, so a log read up to any point ends with whole groups, and a reader that has read what is there calls Flush. A Replay is not safe for concurrent use.

func NewReplay(st State) *Replay

NewReplay returns a Replay that folds onto st, usually New(session).

func (r *Replay) Add(ev event.Event, each func(ev event.Event, before Before, after State) error) error

Add adds the log’s next event, folding the events it held before it once ev shows their group has ended. each, if not nil, is called after every event folds. After an error the Replay must not be used further.

func (r *Replay) Flush(each func(ev event.Event, before Before, after State) error) error

Flush folds the events Add holds.

func (r *Replay) State() State

State is the state after the events folded so far; events Add holds aren’t in it until Flush.

type RequirementView struct {
Requirement event.Requirement
Cause event.RequirementCause
Retirement *event.RequirementRetired
}

RequirementView exposes a requirement’s current revision and causal history. Retirement preserves the definition. Returned records are isolated snapshots.

type Review struct {
// Policy is the host's policy text, the classifier's instructions.
Policy string
// Requests are the user's messages, in order: the task and any
// authorizations the user gave.
Requests []string
// Goal is the session's current goal, if any.
Goal string
// Notes are notes the host attached to tool results for the
// classifier from PostToolUse hooks.
Notes []string
// Environment is what the user declared trusted.
Environment []string
// Effect is what the host knows the action's tool does: for a Write, whether it can only create the file, replaces the
// version the agent read, or fails. It comes from zelk's own rules,
// never from the workspace.
Effect string
// Observed is what the host has just observed, for an action that can
// discard unsaved work. The driver adds it; a host writes only facts
// it measured, never text the workspace could have supplied.
Observed []string
// Tool, Input and Cwd are the action.
Tool string
Input json.RawMessage
Cwd string
// PowerShell says the command uses PowerShell syntax.
PowerShell bool
// Untrusted is a compact transcript of the agent's recent tool calls
// and the project instructions. Agent updates, tool output and hidden
// reasoning are excluded.
Untrusted []string
// Scripts are the files the action runs that the agent wrote or
// changed in this session, with their content as the host read it
// just before the review. The driver adds them; the content is the
// agent's.
Scripts []AgentScript
// Refused are the actions the reviewer has refused in this session and
// that still stand, oldest first. The record is the host's; the text
// of each action is the agent's.
Refused []Refusal
// Metered says the session counts tokens against a budget or a
// parent's allocation, so the review must report what it used: a
// classifier reads the whole answer, which is where providers report
// usage, rather than stopping at an allow.
Metered bool
// CacheKey is the session's key for its reviews, which a classifier
// sends as the request's cache key. Reviews share a prefix with each
// other, not with the agent's calls, so they have a key of their own.
CacheKey string
}

Review is what the auto-mode classifier sees of a pending action. Trusted parts come from the user and the host; everything in Untrusted came from tools, files or the model, and the classifier is told it can’t authorize anything.

func ReviewOf(st State, callID string) (Review, error)

ReviewOf returns the review of the call a classify_action effect is for. It reads only the folded log.

func (r Review) Command() (string, bool)

Command returns the shell command the action runs, if it runs one.

type Rewind struct {
ID string `json:"id"`
Point uint64 `json:"point"`
Files bool `json:"files,omitempty"`
// Restore is the file restore this rewind started, once requested.
Restore string `json:"restore,omitempty"`
// Conversation is what the rewind puts back, until it finishes.
Conversation *Conversation `json:"conversation,omitempty"`
Finished *event.RewindFinished `json:"finished,omitempty"`
}

Rewind is a conversation rewind as the log records it. A nil Finished means it is under way, or was interrupted: the next execution closes it before accepting commands.

type ScheduledMessage struct {
event.Schedule
State string
}

ScheduledMessage is a durable one-shot parent message and its delivery state. State is pending, cancelled or dispatched; a recurring schedule stays pending until its source ends, when it is ended. All times identify absolute instants.

func (j ScheduledMessage) Recurring() bool

Recurring says the schedule fires by cron.

type Settlement struct {
// Expired is set for a request whose deadline passed first.
Expired bool `json:"expired,omitempty"`
Answer *event.AnswerInput `json:"answer,omitempty"`
// Mode is the session's mode when the request settled, which a plan
// left unapproved reports: the host may have switched it meanwhile.
Mode event.PermissionMode `json:"mode,omitempty"`
}

Settlement settles a request, once.

type ShellDecision struct {
// Verdict is allow, ask or deny: with no turn under way no reviewer
// runs, so what auto mode would review is asked of a person.
Verdict event.PermissionVerdict
// Reason says why, for the user.
Reason string
// HumanOnly says only a person may approve it: no rule would.
HumanOnly bool
}

ShellDecision is how a session decides a shell command a skill runs as the user invokes it.

func DecideSkillShell(cfg event.Config, command string, skill event.SkillLoaded, hook event.HookDecision) ShellDecision

DecideSkillShell decides command, a “!`command`” line of the skill being invoked, which runs before the skill’s message is sent, as Claude Code runs it (docs/design/skills.md). It is decided as a shell call of the session configured by cfg would be decided now: its rules, mode, protected paths and read-only allowlist, with the skill’s allowed-tools as allow rules when it speaks for the host, as while it is active. cfg is the session’s configuration as folded, with its mode and rule changes, or a new session’s. hook is the command’s PreToolUse decision (SkillShellHooks), as a shell call’s hooks decide before its permission. It is pure.

func DecideSkillShellWith(ctx context.Context, cfg event.Config, command string, skill event.SkillLoaded, hook event.HookDecision, analyzer engine.PowerShellAnalyzer) ShellDecision

DecideSkillShellWith decides a skill shell line using the supplied analyzer for PowerShell syntax.

type Source struct {
event.Source
// State is live or ended.
State string `json:"state"`
// Cursor is the inclusive last admitted occurrence number.
Cursor uint64 `json:"cursor"`
// Run identifies the run that accepted the last occurrence range.
Run uint64 `json:"run,omitempty"`
// Due is a recurring schedule's last admitted due time.
Due time.Time `json:"due,omitzero"`
// Through is a monitor's output cursor after its last admitted lines.
Through int64 `json:"through,omitempty"`
}

Source is a recorded wake source. State is live or ended; Cursor is the last admitted occurrence number and Run is the run of its last admission.

type State struct {
// contains filtered or unexported fields
}

State is the opaque fold of a session log. Step owns its mutable storage. Read accessors expose snapshots; nested event data remains immutable. State supports JSON checkpoints and Clone for independent future folds.

func New(session string) State

New returns the state of a session before its first event.

func PrepareRecords(ctx context.Context, st State, at time.Time, analyzer engine.PowerShellAnalyzer, ps ...event.Payload) ([]event.Event, State, error)

PrepareRecords derives a batch and its resulting state using analyzer for live PowerShell permission checks. Its result becomes authoritative only after the complete batch commits. Replay uses the decisions in the batch.

func Step(st State, ev event.Event) (State, error)

Step folds ev into st and returns the new state. Pending work is in State.Pending and the run ending is in State.Finish. It is pure: it does no I/O and reads no clock, so the same log always folds to the same state.

Step may reuse st’s storage, so the caller must use only the returned state from then on. It copies the configuration but keeps the history items of events as they are: an event, once folded, must not be modified. On error, the event doesn’t follow from the log; the state must not be used further.

Step derives every decision again and refuses a log that recorded another; a stored log is folded with Replay, where recorded decisions win.

Example

st := loop.New("s1")
log := []event.Payload{
event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version, Model: "claude", Cwd: "."}},
event.CommandAccepted{CommandID: "c1", Command: event.Command{Kind: event.CommandUserMessage, UserMessage: &event.UserMessage{Text: "hi"}}},
}
for i, p := range log {
var err error
st, err = loop.Step(st, event.Event{Seq: uint64(i + 1), Payload: p})
if err != nil {
panic(err)
}
for _, p := range st.Pending() {
fmt.Println(p.Effect.Kind, p.ID, p.Effect.CallProvider.Model)
}
}
fmt.Println("pending:", len(st.Pending()))
// Output:
// call_provider s1/2/0 claude
// pending: 1

Output:

call_provider s1/2/0 claude
pending: 1
func (s State) ActionOf(c Call) Action

ActionOf returns the action a call of the current turn proposes.

func (s State) ApplicableRequirements() []event.Requirement

ApplicableRequirements returns the current focus’s active acceptance plus host invariants.

func (s State) Autonomous() bool

Autonomous reports whether the current run is forbidden to ask for input. Its recorded interaction survives recovery by a host with different callbacks.

func (s State) Breaker() Breaker

Breaker returns the classifier circuit breaker.

func (s State) CheckAnswer(a event.AnswerInput) error

CheckAnswer validates an answer against the request it answers, before a driver appends it: an unknown request, or answers that don’t fit it, are refused; an answer to a request already settled is accepted and changes nothing.

func (s State) CheckCompact() error

CheckCompact says why the session can’t take a compact command now, or is nil: it doesn’t compact, or it is idle with no history to compact. The reason is plain, for a host to show; the driver checks it before appending the command.

func (s State) CheckContinueChild(c event.ContinueChild) error

CheckContinueChild validates a continuation before it is recorded. The driver holds the child’s lease, so the sequence comparison and acceptance are fenced.

func (s State) CheckImages() error

CheckImages says whether the session can take a message with an image: its model must take images. The driver checks it before appending the message, and the reducer when it folds one.

func (s State) CheckModeChange(m event.SetPermissionMode) error

CheckModeChange validates a permission mode command against the session’s policy, before the driver appends its acceptance.

func (s State) CheckModelChange(m event.SetModel) error

CheckModelChange validates a resolved model command against this session’s version and budget requirements, before the driver appends its acceptance.

Example

st := loop.New("session")
var err error
st, err = loop.Step(st, event.Event{Seq: 1, Payload: event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version}}})
if err != nil {
panic(err)
}
fmt.Println(st.CheckModelChange(event.SetModel{Provider: history.FamilyAnthropic, Model: "next", Settings: event.ModelSettings{MaxOutputTokens: 100}}))
// Output: <nil>

Output:

<nil>
func (s State) CheckPolicyChange(p event.SetPolicy) error

CheckPolicyChange reports whether the session accepts p, for a policy zelk can enforce: a root session that records a policy does, and a subagent’s does only to be narrowed by its parent’s (SetPolicy.Narrow).

func (s State) CheckReservation(t event.Tokens) string

CheckReservation reports which hard limit would refuse an additional reservation.

func (s State) CheckRetryDenied(r event.RetryDenied) error

CheckRetryDenied checks a one-use retry against the current policy and review context. Acceptance advances the review revision but does not change policy.

func (s State) CheckRuleChange(event.SetRules) error

CheckRuleChange reports whether the session accepts a rule change: a root session that records a policy does.

func (s State) CheckSchedule(p event.Schedule) error

CheckSchedule checks a schedule operation against durable ownership. It performs no I/O. Cancellation and delivery must be checked again by the reducer under the session’s writer lease, so stale host snapshots cannot deliver cancelled schedules.

func (s State) CheckSkill(p event.SkillLoaded) error

CheckSkill reports whether a skill’s load can be folded in s: a named, revisioned skill whose bundle paths stay inside it and whose allowed-tools entries are rules. Invocation admission additionally checks recorded capabilities through CheckSkillInvocation.

func (s State) CheckSkillInvocation(p event.InvokeSkill) error

CheckSkillInvocation validates a resolved user invocation against recorded session capabilities as well as the bundle’s ordinary load rules.

func (s State) CheckpointPassOwed() bool

CheckpointPassOwed reports whether the current run began at a point and its run-start pass isn’t recorded yet.

func (s State) CheckpointPasses() []CheckpointPass

CheckpointPasses returns the run-start passes the session keeps, oldest first: the points it can restore files to.

func (s State) CheckpointSaved(id string) bool

CheckpointSaved reports whether the current run saved the file of tool call id before it.

func (s State) CheckpointTargets(point uint64) ([]event.FileVersion, bool)

CheckpointTargets returns, sorted by path, the content of every tracked path at point: before the prompt, as docs/design/checkpoints.md defines it. A path tracked by the point’s run-start pass is as its latest version at or before the pass says; any other is as its first version after. It reports false for a point whose pass isn’t kept.

func (s State) CheckpointVersions() []CheckpointVersion

CheckpointVersions returns the versions the session keeps, in log order.

func (s State) Checkpointing() bool

Checkpointing reports whether the session saves checkpoints.

func (s State) Clone() State

Clone returns a copy of s that Step can fold without changing s: Step may reuse the storage of the state it is given, and a host previewing a fold, as Records does, keeps the original. It copies every map, slice and pointer Step writes through; the events and history items the state holds are never modified once folded, and are shared.

func (s State) Commands() map[string]Acceptance

Commands returns accepted commands by ID.

func (s State) CompactionThreshold() int64

CompactionThreshold is the context size, in tokens, at which the next model call compacts the conversation first; zero without compaction.

func (s State) Compactions() int

Compactions returns the number of completed compactions.

func (s State) Config() *event.Config

Config returns an isolated copy of the recorded configuration, or nil before initialization.

func (s State) ContextParts() []ContextPart

ContextParts splits the next model call into its parts: the system prompt, each piece of the session’s context (project instructions per file, memory, the skill index…), the tools by where they come from, and the conversation by kind. The parts’ bytes add up to the call’s, as compaction measures them; parts with no bytes are left out.

func (s State) ContextTokens() (int64, bool)

ContextTokens is the estimated input of the next model call in tokens, and whether a measured call stands behind it: the last measured call’s input plus what the history gained since, or, with no usable measure, the whole request’s size. Compaction decides on the same figure.

func (s State) ContextUse() ContextUse

ContextUse returns the session’s context use.

func (s State) Conversation() Conversation

Conversation returns the conversation part of the state. It shares no container with s; the values inside are immutable by the package’s convention, as for Clone.

func (s State) ConversationSoFar() Conversation

ConversationSoFar is the conversation of a session in the middle of a run, as far as the run has got: every finished step is kept, and the model turn or tool calls still under way are left out, so no tool call lacks its result. Messages queued for the run are kept, as the user sent them, and a note tells the model where the copy was taken. Of an idle session it is the conversation as it stands.

func (s State) Cwd() string

Cwd returns the working directory for tool calls.

func (s State) Decisions() []event.Event

Decisions returns the protocol records owed before dependent work may start.

func (s State) DelegatedRefusals() []Refusal

DelegatedRefusals returns the refusals that stand in this session, for a child session to be reviewed with, each counting the user’s messages as UserRequests hands them on.

func (s State) Deleted() bool

Deleted reports whether the session has been permanently tombstoned.

func (s State) DeniedActions() []DeniedAction

DeniedActions returns retained denials in event order. CheckRetryDenied decides whether a denial still admits a retry in the current context.

func (s State) FileRestore() *FileRestore

FileRestore returns an independent copy of the last file restore, if any.

func (s State) Files() map[string]event.FileObserved

Files returns the latest observations by workspace-relative path.

func (s State) Finish() *event.RunFinished

Finish returns the ending to record for the current run, or nil.

func (s State) Generation() uint64

Generation returns the workspace mutation generation.

func (s State) Goal() Goal

Goal returns the current session goal.

func (s State) Granted() []string

Granted returns the allow rules the user’s approvals granted for the rest of the session, in order.

func (s State) History() []history.Item

History returns the conversation visible to the model, in order.

func (s State) HistoryFrom(i int) []history.Item

HistoryFrom returns the history’s items from index i on, copying only those: a fold’s visitor that wants what an event added reads it without copying the whole history each time. An i past the end returns none.

func (s State) HistoryLen() int

HistoryLen is len(s.History()) without copying the history, for a caller that folds a log and checks its length after every event.

func (s State) Idle() bool

Idle reports whether the session has no run, no pending effect and no suspension.

func (s State) Instructions() map[string]event.InstructionsLoaded

Instructions returns loaded project instructions by directory.

func (s State) Interaction() event.InteractionMode

Interaction returns the current run’s recorded input mode, or event.InteractionSession for a run governed only by the session’s recorded input configuration.

func (s State) Interrupted() string

Interrupted returns the persisted termination reason, or an empty string.

func (s State) Last() *event.RunFinished

Last returns the last completed run, or nil.

func (s State) LastReport() *event.Report

LastReport returns the last completed run report, or nil.

func (s State) Ledger() Ledger

Ledger returns the budget ledger.

func (s State) Live() string

Live says what of the session’s workspace is still running, or “”: a move commits only once nothing is.

func (s State) MarshalJSON() ([]byte, error)

MarshalJSON encodes the derived checkpoint, numbered with its layout: only a reducer whose state has the same layout reads it back.

func (s State) MaterializationIntents() []MaterializationIntent

MaterializationIntents returns every started artifact not yet durably released, including attempts without a successful receipt. Cleanup must use these recorded inputs, not just completed publications. Manifests are copies.

func (s State) Materializations() []Materialization

Materializations returns the session’s owned publications, ordered by identity. Returned manifests are copies, independent of reducer storage.

func (s State) Memory() string

Memory returns the newest memory view the session recorded, which is the one its next compaction takes up.

func (s State) Mode() permission.Mode

Mode returns the session’s current permission mode, or Bypass when no policy is recorded.

func (s State) MonitorProcess(source string) string

MonitorProcess returns the handle of the recorded process that owns source, or “” for a source that owns none.

func (s State) MonitorSource(handle string) (Source, bool)

MonitorSource returns the Watch source bound to process handle, if any. A handle names one process in a log, and only that process’s launch binds a source to it.

func (s State) MoveRequested(effectID string) bool

MoveRequested reports whether a BackgroundCalls command asked the effect, a call of the reply under way, to move to the background.

func (s State) Moving() (Move, bool)

Moving returns the session’s unfinished move, if it has one.

func (s State) NextConfig() event.Config

NextConfig is the configuration the session runs under once the policy, rule and mode changes it has accepted apply, as they will when no tool call is running or being decided: what the reducer will record, worked out the same way.

func (s State) NextOutput() *event.SetOutput

NextOutput returns the output contract queued for the next run, or nil.

func (s State) NextPolicy() event.Policy

NextPolicy is the policy the session decides calls under once the changes it has accepted apply (NextConfig).

func (s State) NextWake() time.Time

NextWake returns the earliest live timer or open attempt deadline. The zero time means the folded session has no persisted deadline requiring a wakeup.

func (s State) Output() *event.StructuredOutputAccepted

Output returns the current accepted structured output, or nil.

func (s State) OutputContract() *event.Output

OutputContract returns the structured output contract in force: the run’s own, if it has one, else the session’s; nil without either.

func (s State) Pending() []Pending

Pending returns effects without terminal events, in request order.

func (s State) Points() []uint64

Points returns the points the conversation can be rewound to, oldest first.

func (s State) PolicyDiffers(p event.SetPolicy) (bool, error)

PolicyDiffers reports whether the session should take p: whether the policy or gate hooks it runs under once the changes it has accepted apply differ with p accepted too (Taking). It fails when the session can’t take p, which a host must not read as p changing nothing.

func (s State) PolicyRevision() uint64

PolicyRevision returns the current permission policy revision.

func (s State) Processes() map[string]Process

Processes returns background processes by handle.

func (s State) Quiet(m Move) bool

Quiet reports whether move m can commit: the session is idle, or, for a tool’s move, its run waits on nothing but the handoff.

func (s State) Records() uint64

Records returns the number of emitted structured records.

func (s State) Report() event.LedgerReport

Report returns the current run’s charges, open reservations and child allocations.

func (s State) Requests() map[string]InputRequest

Requests returns human input requests by ID.

func (s State) Requirements() []RequirementView

Requirements returns current definitions ordered by stable ID, including retired entries.

func (s State) Rewind() *Rewind

Rewind returns a copy of the last rewind, if any.

func (s State) RulesDiffer(r event.SetRules) bool

RulesDiffer reports whether r would change the rules or protected paths the session decides calls under: whether it is a root session’s and differs from what the session records, its grants kept.

func (s State) RunID() uint64

RunID returns the current run identity, or zero while idle.

func (s State) RunOutput() *event.SetOutput

RunOutput returns the current run output contract, or nil.

func (s State) RunPoint() uint64

RunPoint returns the point that began the current run, or 0.

func (s State) Running() []string

Running returns the handles of the background processes not recorded as ended, in order.

func (s State) Schedules() []ScheduledMessage

Schedules returns the conversation’s recorded schedules ordered by due time and ID. A source occurrence acknowledges delivery.

func (s State) ScopedEvidence() map[string]event.EvidenceRecorded

ScopedEvidence returns all scoped observations by stable evidence identity. Labels are display metadata; later observations never overwrite older IDs.

func (s State) ScopedVerification() bool

ScopedVerification reports whether this session recorded the scoped contract.

func (s State) Seq() uint64

Seq returns the last folded event sequence.

func (s State) Session() string

Session returns the session identity.

func (s State) SessionReport() event.LedgerReport

SessionReport returns the cumulative session ledger, including all open allocations.

func (s State) SkillIndex() event.SkillsIndexed

SkillIndex returns the session’s newest skill index: the one recorded last, or the configuration’s.

func (s State) Skills() map[string]event.SkillLoaded

Skills returns loaded skills by name.

func (s State) Sources() []Source

Sources returns independent source records sorted by ID, including ended ones.

Example

st := loop.New("s")
for i, p := range []event.Payload{
event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version}},
event.CommandAccepted{CommandID: "create", Command: event.Command{Kind: event.CommandCreateSource, Source: &event.Source{ID: "build", Kind: "monitor", Description: "Build failures"}}},
} {
var err error
st, err = loop.Step(st, event.Event{Seq: uint64(i + 1), Payload: p})
if err != nil {
panic(err)
}
}
fmt.Println(st.Sources()[0].State, st.Sources()[0].Cursor)
// Output: live 0

Output:

live 0
func (s State) SteerOwed() []event.SteerOutcome

SteerOwed returns steering outcomes the driver must record.

func (s State) Subagents() map[string]Subagent

Subagents returns the child sessions linked to this parent.

func (s State) SuppressesBackgroundWake(c event.Command) bool

SuppressesBackgroundWake reports whether a command’s wake was withdrawn or its process stop was recorded as a kill.

func (s State) Suspended() bool

Suspended returns whether the session is suspended.

func (s State) Tags() []string

Tags returns a copy of the session’s sorted tags.

func (s State) TakenPolicy(p event.SetPolicy) event.Policy

TakenPolicy is the policy the session runs under once it takes p and the changes it has accepted apply.

func (s State) Taking(p event.SetPolicy) State

Taking is the session as it is once it accepts p, which it hasn’t applied yet. CheckPolicyChange says whether it would.

func (s State) Text() string

Text returns the retained final model text.

func (s State) Timers() map[string]Timer

Timers returns derived timers by ID.

func (s State) Title() string

Title returns the session title.

func (s State) Todos() []event.Todo

Todos returns the session’s task list, as TodoWrite last recorded it.

func (s State) Tools() []event.ToolSpec

Tools returns all executable tool specifications, including deferred schemas, with StructuredOutput as the run’s own contract describes it, if it has one. Request omits deferred schemas from the provider-visible tools.

func (s State) Trace() *event.ExecutionTraced

Trace returns the recorded execution trace, or nil.

func (s State) Turns() int

Turns returns the current run model turn count.

func (s *State) UnmarshalJSON(b []byte) error

UnmarshalJSON restores a derived checkpoint. A checkpoint of another layout, or of none recorded, is refused with an error wrapping ErrIncompatible: the session is folded again from its log instead. Resume still requires Compatible.

func (s State) Unmovable() string

Unmovable says why the session can’t move to another root, or “”. What it owns is bound to the workspace it was made in.

func (s State) UnresolvedCarries(handle string) []string

UnresolvedCarries returns the sorted, unique IDs of the handle’s unseen notices in requests handed to open provider attempts. A withdrawal pins these IDs because the attempts might already have reached the model.

func (s State) Usage() event.Usage

Usage returns the current run measured usage.

func (s State) UserRequests() []string

UserRequests returns what the user has said in this session, bounded, for a child session to judge its actions against. A child passes on what it was given. The latest messages are kept, since they are the ones in force.

func (s State) Verification() (event.Verification, []string, []string)

Verification judges checks against their latest evidence.

func (s State) VerificationScope() *event.EvidenceScope

VerificationScope returns producing context for a live tool attempt. A nil result means no work is associated; it never fabricates work provenance.

func (s State) VerificationWork() *event.VerificationWork

VerificationWork returns the explicitly associated work, or nil before the host supplies one. Ordinary user messages do not implicitly retire other work.

func (st State) Visible(items []history.Item) []history.Item

Visible returns a copy of items for display, omitting withdrawn process notices that never reached a model and clearing internal notice provenance.

func (s State) VisibleConversation(c Conversation) Conversation

VisibleConversation returns c as a reader of this session’s conversation shows it, which is how a fork takes it: the notices the session’s wake withdrawals hid are left out of its history and the others lose their notice provenance (Visible). c may be the conversation as it stood at an earlier point, so the withdrawals judged are the ones the state holds now, not those recorded before the point.

A provider’s native window stands for the first Skip items of the history, so Skip counts the items that remain among them: the window and the portable history that follows it keep their alignment. c is left as it was.

func (s State) Waiting() []string

Waiting returns the IDs of the requests waiting for an answer, in order.

func (s State) WakeOwed(handle string) bool

WakeOwed reports whether a process or child may still produce a wake or has a queued or staged notice that has yet to reach a model.

Example

st := loop.New("session")
for _, payload := range []event.Payload{
event.SessionStarted{Config: event.Config{ReducerVersion: loop.Version}},
event.ProcessStarted{Handle: "worker", ProcID: "backend-id"},
} {
var err error
st, err = loop.Step(st, event.Event{Seq: st.Seq() + 1, Payload: payload})
if err != nil {
panic(err)
}
}
fmt.Println(st.WakeOwed("worker"))
st, err := loop.Step(st, event.Event{Seq: st.Seq() + 1, Payload: event.WakeWithdrawn{
Handle: "worker", Pinned: st.UnresolvedCarries("worker"),
}})
if err != nil {
panic(err)
}
fmt.Println(st.WakeOwed("worker"), st.Processes()["worker"].Running)
// Output:
// true
// false true

Output:

true
false true
func (s State) WithdrawnRunOpen() bool

WithdrawnRunOpen reports whether the unfinished run was triggered only by background notices withdrawn before they could reach a model.

func (s State) WorkspaceBaseline() *event.WorkspaceBaseline

WorkspaceBaseline returns a copy of the current run’s persisted baseline. It is nil before capture or after the run ends.

func (s State) WritesPath(name string) (string, bool)

WritesPath returns the input field naming the file a call of tool name writes, when the session saves a checkpoint before it: a trusted built-in tool that declared one.

type Subagent struct {
event.ChildStarted
// WakeWithdrawn suppresses the completion wake independently of settlement.
WakeWithdrawn bool `json:"wake_withdrawn,omitempty"`
// Run is the parent run the child started in.
Run uint64 `json:"run"`
// Finished says a ChildFinished recorded the child's ending: Outcome
// and Used are from it.
Finished bool `json:"finished,omitempty"`
Outcome event.RunOutcome `json:"outcome,omitempty"`
Used event.Tokens `json:"used,omitzero"`
}

Subagent is a child session one of the session’s tool calls started, as its ChildStarted named it, and how it ended once a ChildFinished said so.

type Timer struct {
ID string `json:"id"`
Generation uint64 `json:"generation"`
Origin uint64 `json:"origin"`
Deadline time.Time `json:"deadline"`
Live bool `json:"live"`
Recorded bool `json:"recorded,omitempty"`
// Request is the request a timer expires; empty for the run's
// wall-time timer.
Request string `json:"request,omitempty"`
}

Timer is a derived deadline anchored on an event in the durable log. A timer exists even if its SetTimer record was lost; recovery keeps the same deadline.

type UserAnswer struct {
Seq uint64 `json:"seq"`
Text string `json:"text"`
// Parent says a parent model wrote it, not the user.
Parent bool `json:"parent,omitempty"`
}

UserAnswer is the user’s answer to a request of the agent’s, as the classifier reads it, and the sequence number that recorded it.

type Verdict struct {
Verdict event.ClassifyVerdict `json:"verdict"`
Reason string `json:"reason,omitempty"`
}

Verdict is a classifier verdict a session keeps for exact reuse.

type WrapUp string

WrapUp is the state of a soft limit’s wrap-up turn.

const (
// WrapUpDue: a soft limit was reached; the next model call is the
// wrap-up turn.
WrapUpDue WrapUp = "due"
// WrapUpSent: the wrap-up turn has been asked for; the run ends with
// it.
WrapUpSent WrapUp = "sent"
)

The wrap-up states.