loop
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.
Constants
Section titled “Constants”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 = 128MaxRetainedDenials bounds the actions a host may request to review again.
const MaxTruncations = 2MaxTruncations 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.GenerationVersion 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).
Variables
Section titled “Variables”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.
Compatible
Section titled “Compatible”func Compatible(st State) errorCompatible reports whether this reducer can resume st, wrapping ErrIncompatible if not. Unknown versions and a state with no session started are always refused.
CopyAnswer
Section titled “CopyAnswer”func CopyAnswer(a event.AnswerInput) *event.AnswerInputCopyAnswer returns a copy of a that shares nothing with it.
EffectID
Section titled “EffectID”func EffectID(session string, seq uint64, index int) stringEffectID 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/1Output:
s1/12/1InputResult
Section titled “InputResult”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.
InstructionsText
Section titled “InstructionsText”func InstructionsText(i event.InstructionsLoaded) stringInstructionsText frames project instructions for the model: repository content, with less authority than the user and the host.
NativeReserve
Section titled “NativeReserve”func NativeReserve(st State, cp *event.CallProvider) int64NativeReserve 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) boolOwed 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.
PolicyOf
Section titled “PolicyOf”func PolicyOf(p *event.Policy) (permission.Policy, error)PolicyOf converts a policy as a session records it.
ProviderRequest
Section titled “ProviderRequest”func ProviderRequest(st State, cp *event.CallProvider) *provider.RequestProviderRequest 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 0Output:
text-model 0QuotaLimit
Section titled “QuotaLimit”func QuotaLimit(q *event.Quotas, scope, resource string) int64QuotaLimit returns the limit a session’s quota sets on resource in scope, 0 for none.
RecordPolicy
Section titled “RecordPolicy”func RecordPolicy(p permission.Policy) *event.PolicyRecordPolicy returns a policy as a session records it.
Records
Section titled “Records”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: 0Output:
1 session_startedacknowledged sequence: 0Recover
Section titled “Recover”func Recover(st State) []event.PayloadRecover 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.
Replacement
Section titled “Replacement”func Replacement(ap event.Approval, input json.RawMessage) stringReplacement 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.
ReportOf
Section titled “ReportOf”func ReportOf(st State) *event.ReportReportOf 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.
Request
Section titled “Request”func Request(st State, cp *event.CallProvider) *provider.RequestRequest 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) uint64RunID 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.
SameCommand
Section titled “SameCommand”func SameCommand(a, b event.Command) boolSameCommand compares command content, excluding its caller-assigned ID.
ScheduleText
Section titled “ScheduleText”func ScheduleText(j ScheduledMessage) stringScheduleText is the notice an occurrence of j carries: j’s text.
SkillShellHooks
Section titled “SkillShellHooks”func SkillShellHooks(cfg event.Config) []event.HookSpecSkillShellHooks 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.
TurnDiff
Section titled “TurnDiff”func TurnDiff(st State) *event.TurnDiffTurnDiff 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.
WriteEffect
Section titled “WriteEffect”func WriteEffect(seen event.FileObserved, ok bool) stringWriteEffect is the review’s Effect for a built-in Write of a file the agent last observed as seen, if ok, or never observed.
Acceptance
Section titled “Acceptance”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.
Account
Section titled “Account”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).
Account.Charged
Section titled “Account.Charged”func (a Account) Charged() event.TokensCharged returns what enforcement counts as spent.
Action
Section titled “Action”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”).
Action.Digest
Section titled “Action.Digest”func (a Action) Digest() stringDigest returns the action’s stable digest, “sha256:” and 64 hex digits.
AgentScript
Section titled “AgentScript”type AgentScript = event.AgentScriptAgentScript is a file an action runs that the agent wrote or changed.
ApprovedPlan
Section titled “ApprovedPlan”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.
ApprovedPlan.Met
Section titled “ApprovedPlan.Met”func (p ApprovedPlan) Met(g Goal) boolMet 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.
Before
Section titled “Before”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.
Breaker
Section titled “Breaker”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.
CheckpointPass
Section titled “CheckpointPass”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.
CheckpointVersion
Section titled “CheckpointVersion”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.
ContextPart
Section titled “ContextPart”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.
ContextUse
Section titled “ContextUse”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.
Conversation
Section titled “Conversation”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.
Conversation.History
Section titled “Conversation.History”func (c Conversation) History() []history.ItemHistory 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.
Conversation.MarshalJSON
Section titled “Conversation.MarshalJSON”func (c Conversation) MarshalJSON() ([]byte, error)MarshalJSON encodes the conversation as the event that carries it records it.
Conversation.UnmarshalJSON
Section titled “Conversation.UnmarshalJSON”func (c *Conversation) UnmarshalJSON(b []byte) errorUnmarshalJSON decodes a conversation a rewind or fork event recorded.
DeniedAction
Section titled “DeniedAction”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.
EffectState
Section titled “EffectState”type EffectState stringEffectState 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")FileRestore
Section titled “FileRestore”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.
HookRun
Section titled “HookRun”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.
HookVerdict
Section titled “HookVerdict”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.
CombineSkillShellHooks
Section titled “CombineSkillShellHooks”func CombineSkillShellHooks(runs []HookRun) HookVerdictCombineSkillShellHooks combines the PreToolUse runs for a skill’s command as the loop combines a shell call’s.
InputRequest
Section titled “InputRequest”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.
Ledger
Section titled “Ledger”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.
Materialization
Section titled “Materialization”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.
MaterializationIntent
Section titled “MaterializationIntent”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.
Measure
Section titled “Measure”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.
NativeWindow
Section titled “NativeWindow”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.
Pending
Section titled “Pending”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.
Pending.Reservation
Section titled “Pending.Reservation”func (p Pending) Reservation(attempt int) *event.ReservationReservation returns the reservation attempt n records, if the effect reserves anything.
Pending.Retryable
Section titled “Pending.Retryable”func (p Pending) Retryable() boolRetryable reports whether the effect has had an attempt, none is open, and it hasn’t ended.
Pending.State
Section titled “Pending.State”func (p Pending) State() EffectStateState 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 runningOutput:
s1/2/0 pendings1/2/0 runningProcess
Section titled “Process”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.
ProcessExit
Section titled “ProcessExit”type ProcessExit struct { Code int `json:"code"` Signal string `json:"signal,omitempty"`}ProcessExit is the first exit recorded for a handle.
Refusal
Section titled “Refusal”type Refusal = event.RefusalRefusal is an action the reviewer refused earlier in the session.
Replay
Section titled “Replay”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.
NewReplay
Section titled “NewReplay”func NewReplay(st State) *ReplayNewReplay returns a Replay that folds onto st, usually New(session).
Replay.Add
Section titled “Replay.Add”func (r *Replay) Add(ev event.Event, each func(ev event.Event, before Before, after State) error) errorAdd 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.
Replay.Flush
Section titled “Replay.Flush”func (r *Replay) Flush(each func(ev event.Event, before Before, after State) error) errorFlush folds the events Add holds.
Replay.State
Section titled “Replay.State”func (r *Replay) State() StateState is the state after the events folded so far; events Add holds aren’t in it until Flush.
RequirementView
Section titled “RequirementView”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.
Review
Section titled “Review”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.
ReviewOf
Section titled “ReviewOf”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.
Review.Command
Section titled “Review.Command”func (r Review) Command() (string, bool)Command returns the shell command the action runs, if it runs one.
Rewind
Section titled “Rewind”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.
ScheduledMessage
Section titled “ScheduledMessage”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.
ScheduledMessage.Recurring
Section titled “ScheduledMessage.Recurring”func (j ScheduledMessage) Recurring() boolRecurring says the schedule fires by cron.
Settlement
Section titled “Settlement”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.
ShellDecision
Section titled “ShellDecision”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.
DecideSkillShell
Section titled “DecideSkillShell”func DecideSkillShell(cfg event.Config, command string, skill event.SkillLoaded, hook event.HookDecision) ShellDecisionDecideSkillShell 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.
DecideSkillShellWith
Section titled “DecideSkillShellWith”func DecideSkillShellWith(ctx context.Context, cfg event.Config, command string, skill event.SkillLoaded, hook event.HookDecision, analyzer engine.PowerShellAnalyzer) ShellDecisionDecideSkillShellWith decides a skill shell line using the supplied analyzer for PowerShell syntax.
Source
Section titled “Source”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) StateNew returns the state of a session before its first event.
PrepareRecords
Section titled “PrepareRecords”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: 1Output:
call_provider s1/2/0 claudepending: 1State.ActionOf
Section titled “State.ActionOf”func (s State) ActionOf(c Call) ActionActionOf returns the action a call of the current turn proposes.
State.ApplicableRequirements
Section titled “State.ApplicableRequirements”func (s State) ApplicableRequirements() []event.RequirementApplicableRequirements returns the current focus’s active acceptance plus host invariants.
State.Autonomous
Section titled “State.Autonomous”func (s State) Autonomous() boolAutonomous reports whether the current run is forbidden to ask for input. Its recorded interaction survives recovery by a host with different callbacks.
State.Breaker
Section titled “State.Breaker”func (s State) Breaker() BreakerBreaker returns the classifier circuit breaker.
State.CheckAnswer
Section titled “State.CheckAnswer”func (s State) CheckAnswer(a event.AnswerInput) errorCheckAnswer 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.
State.CheckCompact
Section titled “State.CheckCompact”func (s State) CheckCompact() errorCheckCompact 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.
State.CheckContinueChild
Section titled “State.CheckContinueChild”func (s State) CheckContinueChild(c event.ContinueChild) errorCheckContinueChild validates a continuation before it is recorded. The driver holds the child’s lease, so the sequence comparison and acceptance are fenced.
State.CheckImages
Section titled “State.CheckImages”func (s State) CheckImages() errorCheckImages 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.
State.CheckModeChange
Section titled “State.CheckModeChange”func (s State) CheckModeChange(m event.SetPermissionMode) errorCheckModeChange validates a permission mode command against the session’s policy, before the driver appends its acceptance.
State.CheckModelChange
Section titled “State.CheckModelChange”func (s State) CheckModelChange(m event.SetModel) errorCheckModelChange 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 errorst, 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>State.CheckPolicyChange
Section titled “State.CheckPolicyChange”func (s State) CheckPolicyChange(p event.SetPolicy) errorCheckPolicyChange 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).
State.CheckReservation
Section titled “State.CheckReservation”func (s State) CheckReservation(t event.Tokens) stringCheckReservation reports which hard limit would refuse an additional reservation.
State.CheckRetryDenied
Section titled “State.CheckRetryDenied”func (s State) CheckRetryDenied(r event.RetryDenied) errorCheckRetryDenied checks a one-use retry against the current policy and review context. Acceptance advances the review revision but does not change policy.
State.CheckRuleChange
Section titled “State.CheckRuleChange”func (s State) CheckRuleChange(event.SetRules) errorCheckRuleChange reports whether the session accepts a rule change: a root session that records a policy does.
State.CheckSchedule
Section titled “State.CheckSchedule”func (s State) CheckSchedule(p event.Schedule) errorCheckSchedule 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.
State.CheckSkill
Section titled “State.CheckSkill”func (s State) CheckSkill(p event.SkillLoaded) errorCheckSkill 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.
State.CheckSkillInvocation
Section titled “State.CheckSkillInvocation”func (s State) CheckSkillInvocation(p event.InvokeSkill) errorCheckSkillInvocation validates a resolved user invocation against recorded session capabilities as well as the bundle’s ordinary load rules.
State.CheckpointPassOwed
Section titled “State.CheckpointPassOwed”func (s State) CheckpointPassOwed() boolCheckpointPassOwed reports whether the current run began at a point and its run-start pass isn’t recorded yet.
State.CheckpointPasses
Section titled “State.CheckpointPasses”func (s State) CheckpointPasses() []CheckpointPassCheckpointPasses returns the run-start passes the session keeps, oldest first: the points it can restore files to.
State.CheckpointSaved
Section titled “State.CheckpointSaved”func (s State) CheckpointSaved(id string) boolCheckpointSaved reports whether the current run saved the file of tool call id before it.
State.CheckpointTargets
Section titled “State.CheckpointTargets”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.
State.CheckpointVersions
Section titled “State.CheckpointVersions”func (s State) CheckpointVersions() []CheckpointVersionCheckpointVersions returns the versions the session keeps, in log order.
State.Checkpointing
Section titled “State.Checkpointing”func (s State) Checkpointing() boolCheckpointing reports whether the session saves checkpoints.
State.Clone
Section titled “State.Clone”func (s State) Clone() StateClone 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.
State.Commands
Section titled “State.Commands”func (s State) Commands() map[string]AcceptanceCommands returns accepted commands by ID.
State.CompactionThreshold
Section titled “State.CompactionThreshold”func (s State) CompactionThreshold() int64CompactionThreshold is the context size, in tokens, at which the next model call compacts the conversation first; zero without compaction.
State.Compactions
Section titled “State.Compactions”func (s State) Compactions() intCompactions returns the number of completed compactions.
State.Config
Section titled “State.Config”func (s State) Config() *event.ConfigConfig returns an isolated copy of the recorded configuration, or nil before initialization.
State.ContextParts
Section titled “State.ContextParts”func (s State) ContextParts() []ContextPartContextParts 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.
State.ContextTokens
Section titled “State.ContextTokens”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.
State.ContextUse
Section titled “State.ContextUse”func (s State) ContextUse() ContextUseContextUse returns the session’s context use.
State.Conversation
Section titled “State.Conversation”func (s State) Conversation() ConversationConversation 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.
State.ConversationSoFar
Section titled “State.ConversationSoFar”func (s State) ConversationSoFar() ConversationConversationSoFar 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.
State.Cwd
Section titled “State.Cwd”func (s State) Cwd() stringCwd returns the working directory for tool calls.
State.Decisions
Section titled “State.Decisions”func (s State) Decisions() []event.EventDecisions returns the protocol records owed before dependent work may start.
State.DelegatedRefusals
Section titled “State.DelegatedRefusals”func (s State) DelegatedRefusals() []RefusalDelegatedRefusals 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.
State.Deleted
Section titled “State.Deleted”func (s State) Deleted() boolDeleted reports whether the session has been permanently tombstoned.
State.DeniedActions
Section titled “State.DeniedActions”func (s State) DeniedActions() []DeniedActionDeniedActions returns retained denials in event order. CheckRetryDenied decides whether a denial still admits a retry in the current context.
State.FileRestore
Section titled “State.FileRestore”func (s State) FileRestore() *FileRestoreFileRestore returns an independent copy of the last file restore, if any.
State.Files
Section titled “State.Files”func (s State) Files() map[string]event.FileObservedFiles returns the latest observations by workspace-relative path.
State.Finish
Section titled “State.Finish”func (s State) Finish() *event.RunFinishedFinish returns the ending to record for the current run, or nil.
State.Generation
Section titled “State.Generation”func (s State) Generation() uint64Generation returns the workspace mutation generation.
State.Goal
Section titled “State.Goal”func (s State) Goal() GoalGoal returns the current session goal.
State.Granted
Section titled “State.Granted”func (s State) Granted() []stringGranted returns the allow rules the user’s approvals granted for the rest of the session, in order.
State.History
Section titled “State.History”func (s State) History() []history.ItemHistory returns the conversation visible to the model, in order.
State.HistoryFrom
Section titled “State.HistoryFrom”func (s State) HistoryFrom(i int) []history.ItemHistoryFrom 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.
State.HistoryLen
Section titled “State.HistoryLen”func (s State) HistoryLen() intHistoryLen is len(s.History()) without copying the history, for a caller that folds a log and checks its length after every event.
State.Idle
Section titled “State.Idle”func (s State) Idle() boolIdle reports whether the session has no run, no pending effect and no suspension.
State.Instructions
Section titled “State.Instructions”func (s State) Instructions() map[string]event.InstructionsLoadedInstructions returns loaded project instructions by directory.
State.Interaction
Section titled “State.Interaction”func (s State) Interaction() event.InteractionModeInteraction returns the current run’s recorded input mode, or event.InteractionSession for a run governed only by the session’s recorded input configuration.
State.Interrupted
Section titled “State.Interrupted”func (s State) Interrupted() stringInterrupted returns the persisted termination reason, or an empty string.
State.Last
Section titled “State.Last”func (s State) Last() *event.RunFinishedLast returns the last completed run, or nil.
State.LastReport
Section titled “State.LastReport”func (s State) LastReport() *event.ReportLastReport returns the last completed run report, or nil.
State.Ledger
Section titled “State.Ledger”func (s State) Ledger() LedgerLedger returns the budget ledger.
State.Live
Section titled “State.Live”func (s State) Live() stringLive says what of the session’s workspace is still running, or “”: a move commits only once nothing is.
State.MarshalJSON
Section titled “State.MarshalJSON”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.
State.MaterializationIntents
Section titled “State.MaterializationIntents”func (s State) MaterializationIntents() []MaterializationIntentMaterializationIntents 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.
State.Materializations
Section titled “State.Materializations”func (s State) Materializations() []MaterializationMaterializations returns the session’s owned publications, ordered by identity. Returned manifests are copies, independent of reducer storage.
State.Memory
Section titled “State.Memory”func (s State) Memory() stringMemory returns the newest memory view the session recorded, which is the one its next compaction takes up.
State.Mode
Section titled “State.Mode”func (s State) Mode() permission.ModeMode returns the session’s current permission mode, or Bypass when no policy is recorded.
State.MonitorProcess
Section titled “State.MonitorProcess”func (s State) MonitorProcess(source string) stringMonitorProcess returns the handle of the recorded process that owns source, or “” for a source that owns none.
State.MonitorSource
Section titled “State.MonitorSource”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.
State.MoveRequested
Section titled “State.MoveRequested”func (s State) MoveRequested(effectID string) boolMoveRequested reports whether a BackgroundCalls command asked the effect, a call of the reply under way, to move to the background.
State.Moving
Section titled “State.Moving”func (s State) Moving() (Move, bool)Moving returns the session’s unfinished move, if it has one.
State.NextConfig
Section titled “State.NextConfig”func (s State) NextConfig() event.ConfigNextConfig 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.
State.NextOutput
Section titled “State.NextOutput”func (s State) NextOutput() *event.SetOutputNextOutput returns the output contract queued for the next run, or nil.
State.NextPolicy
Section titled “State.NextPolicy”func (s State) NextPolicy() event.PolicyNextPolicy is the policy the session decides calls under once the changes it has accepted apply (NextConfig).
State.NextWake
Section titled “State.NextWake”func (s State) NextWake() time.TimeNextWake returns the earliest live timer or open attempt deadline. The zero time means the folded session has no persisted deadline requiring a wakeup.
State.Output
Section titled “State.Output”func (s State) Output() *event.StructuredOutputAcceptedOutput returns the current accepted structured output, or nil.
State.OutputContract
Section titled “State.OutputContract”func (s State) OutputContract() *event.OutputOutputContract returns the structured output contract in force: the run’s own, if it has one, else the session’s; nil without either.
State.Pending
Section titled “State.Pending”func (s State) Pending() []PendingPending returns effects without terminal events, in request order.
State.Points
Section titled “State.Points”func (s State) Points() []uint64Points returns the points the conversation can be rewound to, oldest first.
State.PolicyDiffers
Section titled “State.PolicyDiffers”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.
State.PolicyRevision
Section titled “State.PolicyRevision”func (s State) PolicyRevision() uint64PolicyRevision returns the current permission policy revision.
State.Processes
Section titled “State.Processes”func (s State) Processes() map[string]ProcessProcesses returns background processes by handle.
State.Quiet
Section titled “State.Quiet”func (s State) Quiet(m Move) boolQuiet reports whether move m can commit: the session is idle, or, for a tool’s move, its run waits on nothing but the handoff.
State.Records
Section titled “State.Records”func (s State) Records() uint64Records returns the number of emitted structured records.
State.Report
Section titled “State.Report”func (s State) Report() event.LedgerReportReport returns the current run’s charges, open reservations and child allocations.
State.Requests
Section titled “State.Requests”func (s State) Requests() map[string]InputRequestRequests returns human input requests by ID.
State.Requirements
Section titled “State.Requirements”func (s State) Requirements() []RequirementViewRequirements returns current definitions ordered by stable ID, including retired entries.
State.Rewind
Section titled “State.Rewind”func (s State) Rewind() *RewindRewind returns a copy of the last rewind, if any.
State.RulesDiffer
Section titled “State.RulesDiffer”func (s State) RulesDiffer(r event.SetRules) boolRulesDiffer 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.
State.RunID
Section titled “State.RunID”func (s State) RunID() uint64RunID returns the current run identity, or zero while idle.
State.RunOutput
Section titled “State.RunOutput”func (s State) RunOutput() *event.SetOutputRunOutput returns the current run output contract, or nil.
State.RunPoint
Section titled “State.RunPoint”func (s State) RunPoint() uint64RunPoint returns the point that began the current run, or 0.
State.Running
Section titled “State.Running”func (s State) Running() []stringRunning returns the handles of the background processes not recorded as ended, in order.
State.Schedules
Section titled “State.Schedules”func (s State) Schedules() []ScheduledMessageSchedules returns the conversation’s recorded schedules ordered by due time and ID. A source occurrence acknowledges delivery.
State.ScopedEvidence
Section titled “State.ScopedEvidence”func (s State) ScopedEvidence() map[string]event.EvidenceRecordedScopedEvidence returns all scoped observations by stable evidence identity. Labels are display metadata; later observations never overwrite older IDs.
State.ScopedVerification
Section titled “State.ScopedVerification”func (s State) ScopedVerification() boolScopedVerification reports whether this session recorded the scoped contract.
State.Seq
Section titled “State.Seq”func (s State) Seq() uint64Seq returns the last folded event sequence.
State.Session
Section titled “State.Session”func (s State) Session() stringSession returns the session identity.
State.SessionReport
Section titled “State.SessionReport”func (s State) SessionReport() event.LedgerReportSessionReport returns the cumulative session ledger, including all open allocations.
State.SkillIndex
Section titled “State.SkillIndex”func (s State) SkillIndex() event.SkillsIndexedSkillIndex returns the session’s newest skill index: the one recorded last, or the configuration’s.
State.Skills
Section titled “State.Skills”func (s State) Skills() map[string]event.SkillLoadedSkills returns loaded skills by name.
State.Sources
Section titled “State.Sources”func (s State) Sources() []SourceSources 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 0Output:
live 0State.SteerOwed
Section titled “State.SteerOwed”func (s State) SteerOwed() []event.SteerOutcomeSteerOwed returns steering outcomes the driver must record.
State.Subagents
Section titled “State.Subagents”func (s State) Subagents() map[string]SubagentSubagents returns the child sessions linked to this parent.
State.SuppressesBackgroundWake
Section titled “State.SuppressesBackgroundWake”func (s State) SuppressesBackgroundWake(c event.Command) boolSuppressesBackgroundWake reports whether a command’s wake was withdrawn or its process stop was recorded as a kill.
State.Suspended
Section titled “State.Suspended”func (s State) Suspended() boolSuspended returns whether the session is suspended.
State.Tags
Section titled “State.Tags”func (s State) Tags() []stringTags returns a copy of the session’s sorted tags.
State.TakenPolicy
Section titled “State.TakenPolicy”func (s State) TakenPolicy(p event.SetPolicy) event.PolicyTakenPolicy is the policy the session runs under once it takes p and the changes it has accepted apply.
State.Taking
Section titled “State.Taking”func (s State) Taking(p event.SetPolicy) StateTaking is the session as it is once it accepts p, which it hasn’t applied yet. CheckPolicyChange says whether it would.
State.Text
Section titled “State.Text”func (s State) Text() stringText returns the retained final model text.
State.Timers
Section titled “State.Timers”func (s State) Timers() map[string]TimerTimers returns derived timers by ID.
State.Title
Section titled “State.Title”func (s State) Title() stringTitle returns the session title.
State.Todos
Section titled “State.Todos”func (s State) Todos() []event.TodoTodos returns the session’s task list, as TodoWrite last recorded it.
State.Tools
Section titled “State.Tools”func (s State) Tools() []event.ToolSpecTools 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.
State.Trace
Section titled “State.Trace”func (s State) Trace() *event.ExecutionTracedTrace returns the recorded execution trace, or nil.
State.Turns
Section titled “State.Turns”func (s State) Turns() intTurns returns the current run model turn count.
State.UnmarshalJSON
Section titled “State.UnmarshalJSON”func (s *State) UnmarshalJSON(b []byte) errorUnmarshalJSON 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.
State.Unmovable
Section titled “State.Unmovable”func (s State) Unmovable() stringUnmovable says why the session can’t move to another root, or “”. What it owns is bound to the workspace it was made in.
State.UnresolvedCarries
Section titled “State.UnresolvedCarries”func (s State) UnresolvedCarries(handle string) []stringUnresolvedCarries 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.
State.Usage
Section titled “State.Usage”func (s State) Usage() event.UsageUsage returns the current run measured usage.
State.UserRequests
Section titled “State.UserRequests”func (s State) UserRequests() []stringUserRequests 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.
State.Verification
Section titled “State.Verification”func (s State) Verification() (event.Verification, []string, []string)Verification judges checks against their latest evidence.
State.VerificationScope
Section titled “State.VerificationScope”func (s State) VerificationScope() *event.EvidenceScopeVerificationScope returns producing context for a live tool attempt. A nil result means no work is associated; it never fabricates work provenance.
State.VerificationWork
Section titled “State.VerificationWork”func (s State) VerificationWork() *event.VerificationWorkVerificationWork returns the explicitly associated work, or nil before the host supplies one. Ordinary user messages do not implicitly retire other work.
State.Visible
Section titled “State.Visible”func (st State) Visible(items []history.Item) []history.ItemVisible returns a copy of items for display, omitting withdrawn process notices that never reached a model and clearing internal notice provenance.
State.VisibleConversation
Section titled “State.VisibleConversation”func (s State) VisibleConversation(c Conversation) ConversationVisibleConversation 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.
State.Waiting
Section titled “State.Waiting”func (s State) Waiting() []stringWaiting returns the IDs of the requests waiting for an answer, in order.
State.WakeOwed
Section titled “State.WakeOwed”func (s State) WakeOwed(handle string) boolWakeOwed 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 trueOutput:
truefalse trueState.WithdrawnRunOpen
Section titled “State.WithdrawnRunOpen”func (s State) WithdrawnRunOpen() boolWithdrawnRunOpen reports whether the unfinished run was triggered only by background notices withdrawn before they could reach a model.
State.WorkspaceBaseline
Section titled “State.WorkspaceBaseline”func (s State) WorkspaceBaseline() *event.WorkspaceBaselineWorkspaceBaseline returns a copy of the current run’s persisted baseline. It is nil before capture or after the run ends.
State.WritesPath
Section titled “State.WritesPath”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.
Subagent
Section titled “Subagent”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.
UserAnswer
Section titled “UserAnswer”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.
Verdict
Section titled “Verdict”type Verdict struct { Verdict event.ClassifyVerdict `json:"verdict"` Reason string `json:"reason,omitempty"`}Verdict is a classifier verdict a session keeps for exact reuse.
WrapUp
Section titled “WrapUp”type WrapUp stringWrapUp 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.