# event

> Package event defines the entries of a session log and their encoding.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/event (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
import "github.com/barevoidco/zelk/core/event"
```

Package event defines the entries of a session log and their encoding.

A session is an append-only log of events (the log is the truth). Every other view of a session, including the reducer's state, is a fold over its events. An [Event](/reference/go/event/#event) carries a sequence number, a time and a typed [Payload](/reference/go/event/#payload); the payload kinds are listed in kinds.go.

Attempt records and terminal records carry the usage used to settle the budget ledger. Missing usage remains unknown; reservations bound the charge. Timer records preserve absolute deadlines and generations across executions. Commands and usage expose validation before durable admission.

Events encode to JSON as an envelope carrying the log's format [Generation](/reference/go/event/). zelk reads only its own generation: an earlier one fails with [ErrFormatBreak](/reference/go/event/) and a later one with [ErrUnsupportedVersion](/reference/go/event/), before the payload is read. A payload kind this zelk doesn't know is kept as [Unknown](/reference/go/event/#unknown) and written back unchanged (docs/design/durability.md, "Event encoding").

Payload fields use encoding/json's standard forms: a [time.Duration](https://pkg.go.dev/time#Duration) is an integer count of nanoseconds, a [time.Time](https://pkg.go.dev/time#Time) an RFC 3339 string.


## Constants

```go
const (
	ChildTask   = "task"
	ChildSource = "source"
)
```

The kinds of child ID. A session starts only ChildTask children, a Task call's subagent. ChildSource was a retired standing source's run: no zelk starts one, and only storage cleanup recognises its IDs (SplitStoredChildID), so retention and force-delete still find a leftover one under its conversation.

```go
const (
	MaxMCPToolDescription       = 16384
	MaxLoadedMCPToolDescription = 4096
)
```

MaxMCPToolDescription bounds an MCP tool's description, which a ToolSearch returns, and MaxLoadedMCPToolDescription its description in a request's tools, where every call carries it; Claude Code cuts them at 16,384 and 4,096 characters.

```go
const (
	MaxAttachments     = 20
	MaxAttachmentBytes = 1 << 20
	MaxImageBytes      = 3_500_000
	MaxImageTotalBytes = 10 << 20
)
```

The bounds of a message's attachments: how many, how much text in all, how large one image, and how much image data in all.

```go
const (
	MaxMaterializeFiles    = 1000
	MaxMaterializeBytes    = 16 << 20
	MaxMaterializeMetadata = 256 << 10
)
```

Publication bounds are part of the recorded materialization protocol.

```go
const (
	QuotaLogBytes          = "log_bytes"
	QuotaBlobBytes         = "blob_bytes"
	QuotaHookOutputBytes   = "hook_output_bytes"
	QuotaSkillBytes        = "skill_bytes"
	QuotaMaterializedBytes = "materialized_bytes"
	QuotaProcesses         = "processes"
)
```

The resources a Quota bounds, as QuotaExceeded names them.

```go
const (
	ScopeSession   = "session"
	ScopeExecution = "execution"
)
```

The scopes of a quota.

```go
const (
	MaxRequirements            = 1024
	MaxRequirementIDBytes      = 256
	MaxRequirementCommandBytes = 64 << 10
	MaxRequirementReasonBytes  = 4 << 10
	MaxScopedEvidence          = 4096
)
```

Requirement bounds apply before registry publication. Session log and blob quotas remain independent; reaching a bound never evicts an obligation.

```go
const ExitNote = "Exit code %d."
```

ExitNote is the note, in parentheses on a line of its own, in the result of a command that exited with a code other than 0; %d is the code. A host can show the code on its own (transcript.Call.Exit).

```go
const FailureLabels = "\n[certainty: "
```

FailureLabels begins the line zelk adds to a failed or refused tool result for the model: the failure's certainty, policy and recoverability. A person reads the result without it (transcript.Call.Output).

```go
const Generation = 109
```

Generation is the format of every event this zelk writes and the only one it reads, recorded as each envelope's "v". A change to any payload's shape or to how the log folds raises it; nothing upcasts an earlier one. It starts at 100 so that no number an earlier zelk wrote can pass for it.

```go
const MaxCheckpointFileBytes = 8 << 20
```

MaxCheckpointFileBytes is the largest file a checkpoint saves; a larger one is recorded as skipped (docs/design/checkpoints.md).

```go
const MaxCheckpointPoints = 100
```

MaxCheckpointPoints is how many points' run-start passes a session keeps; versions only the older ones need are dropped.

```go
const MaxConversationIDLen = MaxSessionIDLen - len("/"+ChildTask+"/") - 2*childHash
```

MaxConversationIDLen is the longest ID of a conversation, a session that isn't a child: its children's IDs add a kind and a hash to it and must still fit MaxSessionIDLen.

```go
const MaxMCPInstructions = 4096
```

MaxMCPInstructions bounds an MCP server's instructions in the context, as Claude Code cuts them at 4,096 characters.

```go
const MaxOccurrenceBytes = 256 << 10
```

MaxOccurrenceBytes bounds occurrence text in UTF-8 bytes.

```go
const MaxSessionIDLen = 120
```

MaxSessionIDLen is the longest session ID, in bytes, that every store accepts.

```go
const MaxTitleLen = 200
```

MaxTitleLen is the longest session title, in characters.

```go
const ReasonNoRule = "no rule allows it"
```

ReasonNoRule is the Reason of an approval asked for only because nothing decided the action: no rule, mode or hook allowed or denied it. It is the ordinary case, so a host need not show it (present.Why).


## Variables

```go
var ErrFormatBreak = errors.New("log written before the current format")
```

ErrFormatBreak reports an event written before the current log format: its envelope names an earlier generation. zelk reads only logs of its own generation, so such a log is refused rather than read under rules it wasn't written by. It is neither corruption nor a log from a newer zelk.

```go
var ErrInvalidRequirement = errors.New("invalid requirement metadata")
```

ErrInvalidRequirement marks malformed requirement metadata, not a policy denial.

```go
var ErrSessionDeleted = errors.New("session has been deleted")
```

ErrSessionDeleted reports an attempt to continue a tombstoned session.

```go
var ErrUnsupportedVersion = errors.New("unsupported event payload version")
```

ErrUnsupportedVersion is returned when an event's payload version is not one this version of zelk can read: newer than it knows, or not a valid version at all.


## BackgroundCompletionID

```go
func BackgroundCompletionID(job string) string
```

BackgroundCompletionID gives the durable deduplication ID for a job's completion receipt.


## ChildSessionID

```go
func ChildSessionID(parent, kind, key string) string
```

ChildSessionID is the session ID of parent's child of kind ChildTask, started for key: a Task call's effect ID. The same parent, kind and key always give the same child, so a retry or recovery takes up the child it started.

The child sits directly under its conversation, however deep its parent, as \<conversation>/\<kind>/\<hash>: its length doesn't grow with depth, and its conversation is read from the ID alone, as retention needs even of a log it can't read (docs/design/retention.md). Its parent isn't in the ID; the parent's log records the child.


## Encode

```go
func Encode(e Event) ([]byte, error)
```

Encode returns the event's envelope. Log stores write these bytes as they are. An [Unknown](/reference/go/event/#unknown) payload is written back exactly as it was read.


## NewMonitorSourceID

```go
func NewMonitorSourceID() string
```

NewMonitorSourceID names the source of one Watch launch. It is fresh for every launch, whatever process ID the environment gives, so a watch of a session that was deleted can never write to the inbox of a session made later under the same ID, even one whose process has the same handle and process ID.

**Example**

```go
// Two launches never share a source, even of the same handle.
first, second := event.NewMonitorSourceID(), event.NewMonitorSourceID()
fmt.Println(first == second, event.ValidateSourceID(first))
// Output: false <nil>
```

Output:

```text
false <nil>
```


## SplitChildID

```go
func SplitChildID(id string) (conversation, kind string)
```

SplitChildID returns the conversation session id belongs to and, for a child's, its kind; a conversation's is id itself and "". It knows the children a session starts now, so an ID of the retired source kind is a conversation's.


## SplitStoredChildID

```go
func SplitStoredChildID(id string) (conversation, kind string)
```

SplitStoredChildID is SplitChildID for storage cleanup: it also recognises the retired source kind, so a tree that has such a leftover is still found through its conversation.


## ValidCheckpointPath

```go
func ValidCheckpointPath(p string) error
```

ValidCheckpointPath checks that p is a portable, slash-separated workspace-relative path outside Git metadata.


## ValidateCommandID

```go
func ValidateCommandID(id string) error
```

ValidateCommandID checks the persisted ID: 1 to 128 UTF-8 bytes without control characters. It does not normalize IDs; their bytes are their identity.


## ValidateSourceID

```go
func ValidateSourceID(id string) error
```

ValidateSourceID checks a source's 1–96 UTF-8 bytes without controls.


## ValidateWorkspaceID

```go
func ValidateWorkspaceID(id string) error
```

ValidateWorkspaceID checks the shape of a host-selected workspace identity.


## ActionClassified

```go
type ActionClassified struct {
	EffectID string          `json:"effect_id"`
	Digest   string          `json:"digest"`
	Verdict  ClassifyVerdict `json:"verdict"`
	Reason   string          `json:"reason,omitempty"`
	// Observed is what the host told the reviewer it had just observed.
	Observed []string `json:"observed,omitempty"`
	// Scripts are the agent-written files the action runs, as the host
	// showed them to the reviewer.
	Scripts []AgentScript `json:"scripts,omitempty"`
}
```

ActionClassified records the classifier's verdict, immediately before the end of its classify\_action effect.


### ActionClassified.Kind

```go
func (ActionClassified) Kind() Kind
```

Kind returns [KindActionClassified](/reference/go/event/).


## AgentScript

```go
type AgentScript struct {
	// Path is the file's workspace-relative path.
	Path string `json:"path"`
	// Content is the start of the file's content: the agent's, and data
	// to the reviewer, never instructions.
	Content string `json:"content,omitempty"`
	// Truncated says Content is only the file's start.
	Truncated bool `json:"truncated,omitempty"`
	// Unread says why there is no content: the file is gone, or isn't a
	// file the host reads, such as a symbolic link or one too large.
	Unread string `json:"unread,omitempty"`
}
```

AgentScript is a file an action runs that the agent wrote or changed in its session, as the host read it just before the review.


## AnswerInput

```go
type AnswerInput struct {
	RequestID string           `json:"request_id"`
	Questions *QuestionsAnswer `json:"questions,omitempty"`
	Plan      *PlanAnswer      `json:"plan,omitempty"`
	Approval  *ApprovalAnswer  `json:"approval,omitempty"`
	// Denied records that no human answered: the host's callback failed,
	// panicked or timed out, and the request fails closed. Reason says
	// why, for audit.
	Denied bool   `json:"denied,omitempty"`
	Reason string `json:"reason,omitempty"`
	// Relayed says a parent model wrote these answers for its child,
	// so they don't count as the user's words however
	// the parent came by them.
	Relayed bool `json:"relayed,omitempty"`
	// UserRequests replace a relayed child's Config.UserRequests:
	// what the real user has said by now, which may
	// include their answer to the parent's own question.
	UserRequests []string `json:"user_requests,omitempty"`
	// ParentRefused replace a relayed child's Config.ParentRefused.
	ParentRefused []Refusal `json:"parent_refused,omitempty"`
}
```

AnswerInput answers the request RequestID. It is a tagged union, like Command: exactly one of Questions, Plan and Approval is set, matching the request's kind, or none with Denied. The first answer or expiry folded settles a request; later ones change nothing.


## Approval

```go
type Approval struct {
	// Tool and Input are the action as it would run.
	Tool  string          `json:"tool"`
	Input json.RawMessage `json:"input,omitempty"`
	// Digest is the action digest: every answer must name it, and a
	// decision never applies to another (docs/design/permissions.md,
	// "Action digests").
	Digest string `json:"digest"`
	// Reason says why the action needs a human.
	Reason string `json:"reason"`
	// HumanOnly marks an action no session grant may cover, such as a
	// write to a protected path.
	HumanOnly bool `json:"human_only,omitempty"`
	// Cwd and Revision are the working directory and policy revision the
	// digest binds, so a replacement's digest can be computed the same
	// way.
	Cwd      string `json:"cwd"`
	Revision uint64 `json:"policy_revision"`
	// Suggestions are rules the human may grant for the rest of the
	// session instead of approving once.
	Suggestions []Suggestion `json:"suggestions,omitempty"`
	// Trust says the suggestions name a site a person may trust beyond
	// the session: a host that keeps the user's rules may offer to save
	// them, as well as granting them now
	// (docs/design/browser-automation.md, A5).
	Trust bool `json:"trust,omitempty"`
	// OpensTab says the call opens a tab in the user's browser, and
	// approving it trusts that tab: zelk then acts in it without asking
	// (docs/design/browser-automation.md, A13).
	OpensTab bool `json:"opens_tab,omitempty"`
	// Site is the site the tab opens on, when OpensTab: approving it
	// trusts new tabs on that site for the rest of the session
	// (docs/design/permissions.md).
	Site string `json:"site,omitempty"`
	// Defer says a hook asked to suspend for this decision: the session
	// suspends even when a callback could answer.
	Defer bool `json:"defer,omitempty"`
}
```

Approval is an action presented for a human's decision.


## ApprovalAnswer

```go
type ApprovalAnswer struct {
	// Decision is the answer; Digest must be the approval's action digest.
	Decision ApprovalDecision `json:"decision"`
	Digest   string           `json:"digest"`
	// Input and its Replacement digest are the edited action, for
	// ApproveEdited only.
	Input       json.RawMessage `json:"input,omitempty"`
	Replacement string          `json:"replacement,omitempty"`
	// Suggestion names one of the approval's suggestions, for
	// ApproveSession only; Suggestions names several, granted together,
	// as a command of several parts needs one for each. A
	// grant names its suggestions one way or the other, not both.
	Suggestion  string   `json:"suggestion,omitempty"`
	Suggestions []string `json:"suggestions,omitempty"`
	// Message goes to the model with a denial.
	Message string `json:"message,omitempty"`
}
```

ApprovalAnswer answers an InputApproval request.


## ApprovalDecision

```go
type ApprovalDecision string
```

ApprovalDecision is a human's answer to an approval.

```go
const (
	// ApproveOnce runs the action this once.
	ApproveOnce ApprovalDecision = "allow_once"
	// ApproveEdited runs the human's replacement for the action instead;
	// it is decided again, but never asks again.
	ApproveEdited ApprovalDecision = "allow_edited"
	// ApproveSession grants one of the approval's suggestions, or
	// several, for the rest of the session, and runs the action.
	ApproveSession ApprovalDecision = "allow_session"
	// DenyAction denies the action; the message tells the model what to
	// do instead.
	DenyAction ApprovalDecision = "deny"
	// CancelAction denies the action and interrupts the run.
	CancelAction ApprovalDecision = "cancel"
)
```

The approval decisions.


### ApprovalDecision.Valid

```go
func (d ApprovalDecision) Valid() bool
```

Valid reports whether d is one of the approval decisions.


## Attachment

```go
type Attachment struct {
	// Resource marks external MCP content. It records no workspace read.
	Resource bool `json:"resource,omitempty"`
	// Path is the file as the user named it, or a name the host gave an
	// image that is no file, such as one pasted from the clipboard. For a
	// resource it is server:uri.
	Path string `json:"path"`
	// Text is a text file as the Read tool showed it: numbered lines, or
	// what Read says of an empty file; a resource holds labelled untrusted text.
	Text string `json:"text,omitempty"`
	// Image is an image, its data inline. A session whose model doesn't
	// take images refuses a message with one.
	Image *history.Image `json:"image,omitempty"`
	// ImageSourceDigest identifies original image content when admission changes
	// its encoding or replaces it with text, preserving command resend identity.
	ImageSourceDigest string `json:"image_source_digest,omitempty"`
	// Observed is the read of a workspace file, as a Read call records
	// it; it is zero for an image that is no workspace file.
	Observed FileObserved `json:"observed,omitzero"`
}
```

Attachment is a file, image or MCP resource attached to a user message: it holds text or an image, not both.


## AttemptCause

```go
type AttemptCause string
```

AttemptCause names why an attempt ended without ending its effect.

```go
const (
	// AttemptRetry: the attempt failed in a way worth retrying.
	AttemptRetry AttemptCause = "retry"
	// AttemptLost: reconciliation found the attempt open after a crash or
	// stop.
	AttemptLost AttemptCause = "lost"
	// AttemptDeadline: reconciliation found the attempt open past its
	// deadline.
	AttemptDeadline AttemptCause = "deadline"
)
```

The attempt causes (docs/design/durability.md, E2).


## AttemptEnded

```go
type AttemptEnded struct {
	EffectID string       `json:"effect_id"`
	Attempt  int          `json:"attempt"`
	Cause    AttemptCause `json:"cause"`
	// Outcome is how the attempt ended, as far as anyone knows: unknown
	// for a lost attempt.
	Outcome Outcome `json:"outcome"`
	// Usage is what the attempt reported spending, if it did.
	Usage *Usage `json:"usage,omitempty"`
	// RetryAt is the absolute time before which the next attempt mustn't
	// start; the zero time means at once.
	RetryAt time.Time `json:"retry_at,omitzero"`
	Error   string    `json:"error,omitempty"`
}
```

AttemptEnded closes an attempt without ending its effect, which may then start another (docs/design/durability.md, E2). The attempt's charge in the ledger follows from its outcome and usage (B4).


### AttemptEnded.Kind

```go
func (AttemptEnded) Kind() Kind
```

Kind returns [KindAttemptEnded](/reference/go/event/).


## AttemptRecorded

```go
type AttemptRecorded struct {
	ID       string `json:"id"`
	Run      uint64 `json:"run"`
	EffectID string `json:"effect_id"`
	TaskKey  string `json:"task_key"`
	N        int    `json:"n"`
}
```

AttemptRecorded counts a failed tool action attributed at scheduling time to one unambiguous active TodoWrite task. EffectID prevents double counting.


### AttemptRecorded.Kind

```go
func (AttemptRecorded) Kind() Kind
```

Kind returns KindAttemptRecorded.


## AwaitInput

```go
type AwaitInput struct {
	CallID string `json:"call_id"`
	// Kind is InputQuestion, InputPlanExit or InputApproval.
	Kind      InputKind  `json:"kind"`
	Questions []Question `json:"questions,omitempty"`
	// Plan is the plan presented for approval.
	Plan string `json:"plan,omitempty"`
	// ReturnMode, for InputPlanExit, is the mode the session was in before
	// plan mode, when it is still authorized: the one a host offers first,
	// so approving a plan goes back to how the user was working.
	ReturnMode PermissionMode `json:"return_mode,omitempty"`
	// Approval is the action to approve, for InputApproval.
	Approval *Approval `json:"approval,omitempty"`
}
```

AwaitInput is a request for human input made by a tool call.


## BackgroundCalls

```go
type BackgroundCalls struct {
	Run     uint64   `json:"run"`
	SendNow bool     `json:"send_now,omitempty"`
	Steers  []string `json:"steers,omitempty"`
}
```

BackgroundCalls asks run Run to move the calls it is running that can move, a Bash command or a subagent, to the background, where they go on while the run does. Alone, as ctrl+b, it leaves any other work be. With SendNow it delivers the steers named in Steers at once: the run's next model call takes them as soon as the moved calls return, calls of the same reply not started yet are not run, and work that can't move, such as a model reply, is interrupted instead. Once a model call has taken every one of Steers it does nothing.


## BackgroundDisposition

```go
type BackgroundDisposition string
```

BackgroundDisposition is what a BackgroundCalls command did.

```go
const (
	// BackgroundMoving: it asked Effects to move; with SendNow, the run
	// goes on to its next model call once they return.
	BackgroundMoving BackgroundDisposition = "moving"
	// BackgroundInterrupted: with SendNow, work that can't move was under
	// way, so it interrupted the run; the next run takes the steers.
	BackgroundInterrupted BackgroundDisposition = "interrupted"
	// BackgroundNothing: alone, nothing running could move.
	BackgroundNothing BackgroundDisposition = "nothing_movable"
	// BackgroundSatisfied: with SendNow, a model call had already taken
	// every steer named.
	BackgroundSatisfied BackgroundDisposition = "satisfied"
	// BackgroundNoRun: the run named isn't under way.
	BackgroundNoRun BackgroundDisposition = "no_run"
)
```

What a BackgroundCalls command can do.


## BackgroundNotice

```go
type BackgroundNotice struct {
	Job  string `json:"job"`
	Text string `json:"text"`
	// Running scopes the notice to a run under way:
	// folded while none is, or once Job names a subagent or a background
	// process whose ending is already recorded, it is dropped instead of
	// starting a run or asking the model to collect what it has. The
	// runtime sends such notices unasked, for background subagents and
	// commands that end with the parent's execution. A notice
	// still queued leaves the queue when the job's ending is recorded, or
	// its run ends.
	Running bool `json:"running,omitempty"`
	// Exited says Job is a background process that exited, with Code and
	// Signal as its exit gave them. The fold records it on the process, so
	// the session's status says it ended before the model collects its
	// output, which is when its ending is recorded.
	Exited bool   `json:"exited,omitempty"`
	Code   int    `json:"code,omitempty"`
	Signal string `json:"signal,omitempty"`
	// Outcome is how a subagent's run ended, when Job is a subagent that
	// finished; Waiting says it is waiting for input instead.
	Outcome RunOutcome `json:"outcome,omitempty"`
	Waiting bool       `json:"waiting,omitempty"`
}
```

BackgroundNotice is the runtime's word that background job Job finished or waits for input, with Text for the model. The model sees it at the next safe boundary as a notice, not as a message from the user.


## BackgroundRequested

```go
type BackgroundRequested struct {
	CommandID   string                `json:"command_id"`
	Run         uint64                `json:"run"`
	Effects     []string              `json:"effects,omitempty"`
	Disposition BackgroundDisposition `json:"disposition"`
}
```

BackgroundRequested records what a BackgroundCalls command asked of the run: the RunTool effects it asked to move, by ID, and what else it did. A call asked to move ends with a result that names its background job, or, if it couldn't move, with its own result.


### BackgroundRequested.Kind

```go
func (BackgroundRequested) Kind() Kind
```

Kind returns [KindBackgroundRequested](/reference/go/event/).


## Budget

```go
type Budget struct {
	Input  Limit `json:"input,omitzero"`
	Output Limit `json:"output,omitzero"`
	Total  Limit `json:"total,omitzero"`
}
```

Budget limits what a run may commit, per dimension (docs/design/durability.md, B5). A zero Limit is no limit.


## CallProvider

```go
type CallProvider struct {
	Model string `json:"model"`
	// Compact, when set, makes the call summarize the history instead of
	// taking a turn (docs/design/compaction.md).
	Compact Compact `json:"compact,omitzero"`
}
```

CallProvider asks the model for its next turn. The request is rendered from the history and the recorded configuration, so only what varies per call is stored.


## CancelCause

```go
type CancelCause string
```

CancelCause names what cancelled an effect.

```go
const (
	// CancelInterrupt: the user interrupted the run.
	CancelInterrupt CancelCause = "interrupt"
	// CancelBudget: a hard limit refused the effect's next attempt.
	CancelBudget CancelCause = "budget"
)
```

The cancel causes.


## Capabilities

```go
type Capabilities struct {
	ContextWindow     int64 `json:"context_window"`
	MaxOutputTokens   int64 `json:"max_output_tokens"`
	ParallelToolCalls bool  `json:"parallel_tool_calls,omitempty"`
	Images            bool  `json:"images,omitempty"`
	Reasoning         bool  `json:"reasoning,omitempty"`
	// InputBound says how a request's input tokens can be bounded before
	// it is sent (docs/design/durability.md, B2): InputBoundBytes when the
	// provider's tokenizers never take more tokens than a text has bytes;
	// empty when nothing short of the context window bounds them.
	InputBound InputBound `json:"input_bound,omitempty"`
	// InputOverhead is the most tokens the provider adds to a request on
	// its own side, such as a tool-use preamble, beyond what zelk sends.
	InputOverhead int64 `json:"input_overhead,omitempty"`
	// NativeCompaction says the provider can compact a window itself
	// (provider.Compactor).
	NativeCompaction bool `json:"native_compaction,omitempty"`
	// DeferredTools says the provider loads deferred tool definitions
	// mid-conversation without breaking the prompt cache: a ToolSearch
	// result's loaded tools reach the model as definitions it calls by
	// name (docs/design/tools.md, deferred tools).
	DeferredTools bool `json:"deferred_tools,omitempty"`
}
```

Capabilities is what the provider reports the model supports.


## Check

```go
type Check struct {
	Name    string `json:"name"`
	Command string `json:"command"`
}
```

Check is a verification check: a named command whose passing run is evidence.


## CheckRun

```go
type CheckRun struct {
	// ID is the evidence ID, the starting call's effect ID.
	ID     string         `json:"id"`
	Check  string         `json:"check"`
	Source EvidenceSource `json:"source"`
	// Generation is the mutation generation the check started at: its
	// evidence is for the workspace as it was then.
	Generation uint64 `json:"generation"`
}
```

CheckRun is a check running as a background process: the evidence its collection records, or its ending without one, takes these values.


## ChildContinued

```go
type ChildContinued struct{ ChildStarted }
```

ChildContinued links a fresh parent effect and allocation to a finished child without discarding its history.


### ChildContinued.Kind

```go
func (ChildContinued) Kind() Kind
```

Kind returns KindChildContinued.


## ChildFinished

```go
type ChildFinished struct {
	AllocationID string `json:"allocation_id,omitempty"`
	Used         Tokens `json:"used"`
	Returned     Tokens `json:"returned,omitzero"`
	ChildSession string `json:"child_session,omitempty"`
	// Outcome is how the child's run ended.
	Outcome RunOutcome `json:"outcome,omitempty"`
	// Usage is what the child's run used, when no tool result reports it:
	// the runtime settled the ending on its own, at the start of an
	// execution or inside a call that didn't collect the child. The
	// reducer charges it, and Used equals its
	// tokens. It is nil when the call that recorded the ending reports the
	// usage in its own result, which charges it.
	Usage *Usage `json:"usage,omitempty"`
}
```

ChildFinished records how a child session ended, once its parent learned it: from the call that waited for it, or the one that collected or stopped it. It names the child and its run's outcome, and Used is what the child spent, for display: the parent's call settles it (docs/design/durability.md, B7).


### ChildFinished.Kind

```go
func (ChildFinished) Kind() Kind
```

Kind returns [KindChildFinished](/reference/go/event/).


## ChildOrigin

```go
type ChildOrigin struct {
	Session string `json:"session"`
	Key     string `json:"key"`
}
```

ChildOrigin is where a child session comes from: its parent session and the idempotency key of the call that started it.


### ChildOrigin.Derives

```go
func (o ChildOrigin) Derives(id string) bool
```

Derives reports whether o is the origin the child ID id derives from: a task child's ID is ChildSessionID(o.Session, ChildTask, o.Key).


## ChildStarted

```go
type ChildStarted struct {
	// NotifyOnCompletion records explicit authorization for a deduplicated parent wakeup.
	NotifyOnCompletion bool `json:"notify_on_completion,omitempty"`
	// WakeID identifies this notification intent across reuse of the parent
	// session ID, which can also reproduce the same child and effect IDs.
	// The Agent sets it on children that notify on completion.
	WakeID string `json:"wake_id,omitempty"`
	// Lifetime is execution (also the empty value) or conversation.
	Lifetime     string `json:"lifetime,omitempty"`
	ChildSession string `json:"child_session"`
	ParentEffect string `json:"parent_effect"`
	// AllocationID and Allocation are the parent attempt's reservation,
	// if the call reserves the child's budget; zero otherwise.
	AllocationID string `json:"allocation_id,omitempty"`
	Allocation   Tokens `json:"allocation,omitzero"`
	// CallID is the tool call that started the child.
	CallID string `json:"call_id,omitempty"`
	// AgentType is the child's subagent type.
	AgentType string `json:"agent_type,omitempty"`
	// Background says the call returned without waiting for the child.
	Background bool `json:"background,omitempty"`
}
```

ChildStarted names a child session a parent's tool call started, such as a subagent: the parent's log links to the child's. The parent writes it with the call's result, and the allocation is the call's own reservation, which already counts in the parent's commitment (docs/design/durability.md, B7).


### ChildStarted.Kind

```go
func (ChildStarted) Kind() Kind
```

Kind returns [KindChildStarted](/reference/go/event/).


## Classifier

```go
type Classifier struct {
	// Policy is the policy text the classifier judges against: zelk's
	// default or the host's; PolicyRevision its digest.
	Policy         string `json:"policy"`
	PolicyRevision string `json:"policy_revision"`
	// Environment is what the user declared trusted, such as their
	// repositories, buckets or internal services; PolicyRevision covers it.
	Environment []string `json:"environment,omitempty"`
	// Model is the model it runs on, and Effort how much it reasons
	// before a verdict; empty leaves that to the model.
	Model  string `json:"model"`
	Effort Effort `json:"effort,omitempty"`
	// Timeout bounds one classification; Reserve is what each attempt
	// reserves from the budget, its cost cap.
	Timeout time.Duration `json:"timeout"`
	Reserve Tokens        `json:"reserve"`
}
```

Classifier is the auto-mode classifier's configuration as a session records it.


## Classify

```go
type Classify struct {
	// ShellSummary names the PowerShell commands read from the syntax tree.
	ShellSummary string `json:"shell_summary,omitempty"`
	CallID       string `json:"call_id"`
	// Digest is the action digest; Review the review-context revision.
	// A verdict is reused only for the same digest, policy revision and
	// review revision.
	Digest string `json:"digest"`
	Review uint64 `json:"review"`
	// Override is the trusted reason for a consumed one-use retry.
	Override string `json:"override,omitempty"`
	// Observe says the action can discard unsaved work, so the host is
	// asked for the repository's state, and the verdict binds to this one
	// call: the state may differ for an identical command later.
	Observe bool `json:"observe,omitempty"`
	// Compactions is the session's compaction count when an observed
	// action was reviewed: a provider can use a call ID again once
	// compaction has dropped the first use.
	Compactions int `json:"compactions,omitempty"`
	// Scripts are the workspace files the action runs as a program or a
	// script that the agent wrote or changed in this session. The
	// host shows the reviewer their content, and, as for an observed
	// action, the verdict binds to this one call: the agent may change a
	// file before an identical command runs again.
	Scripts []string `json:"scripts,omitempty"`
}
```

Classify asks the classifier about one action.


### Classify.PerCall

```go
func (c Classify) PerCall() bool
```

PerCall reports whether the verdict binds to this one call rather than to every identical action.


## ClassifyVerdict

```go
type ClassifyVerdict string
```

ClassifyVerdict is the auto-mode classifier's verdict on an action.

```go
const (
	ClassifyAllow     ClassifyVerdict = "allow"
	ClassifyDeny      ClassifyVerdict = "deny"
	ClassifyUncertain ClassifyVerdict = "uncertain"
	// ClassifyTimeout and ClassifyError fail closed, to a human or a
	// denial when none can be asked; they are reported to the model
	// apart from denials, so it doesn't learn the action is unsafe.
	ClassifyTimeout ClassifyVerdict = "timeout"
	ClassifyError   ClassifyVerdict = "error"
)
```

The classifier verdicts.


## ClearGoal

```go
type ClearGoal struct {
	Abandon bool `json:"abandon,omitempty"`
}
```

ClearGoal reverts the goal to the user's request, as a new revision, or, with Abandon, marks it abandoned: only the user can.


## Command

```go
type Command struct {
	// Source carries creation or an ID-only lifecycle operation.
	Source *Source `json:"source,omitempty"`
	// Occurrence carries an admitted source range and its fixed payload.
	Occurrence          *SourceOccurrence    `json:"occurrence,omitempty"`
	SetVerificationWork *VerificationWork    `json:"set_verification_work,omitempty"`
	DeclareRequirement  *RequirementDeclared `json:"declare_requirement,omitempty"`
	RetireRequirement   *RequirementRetired  `json:"retire_requirement,omitempty"`
	// ID is assigned by the caller; empty IDs are generated on admission.
	// On acceptance it moves to CommandAccepted.CommandID, and is empty in
	// the log.
	ID string `json:"id,omitempty"`
	// Interrupt supplies the reason for ending the run.
	Interrupt *Interrupt `json:"interrupt,omitempty"`
	// SetModel carries the resolved model and capability snapshot.
	SetModel      *SetModel      `json:"set_model,omitempty"`
	InjectContext *InjectContext `json:"inject_context,omitempty"`
	// SetPermissionMode names the mode to switch to.
	SetPermissionMode *SetPermissionMode `json:"set_permission_mode,omitempty"`
	// SetRules carries the rules and protected paths to switch to.
	SetRules *SetRules `json:"set_rules,omitempty"`
	// SetPolicy carries the permission policy to switch to.
	SetPolicy *SetPolicy `json:"set_policy,omitempty"`
	// InvokeSkill carries the resolved skill the user invoked.
	InvokeSkill *InvokeSkill `json:"invoke_skill,omitempty"`
	// AnswerInput answers a request for human input.
	AnswerInput   *AnswerInput   `json:"answer_input,omitempty"`
	SetGoal       *SetGoal       `json:"set_goal,omitempty"`
	ClearGoal     *ClearGoal     `json:"clear_goal,omitempty"`
	Steer         *Steer         `json:"steer,omitempty"`
	SetOutput     *SetOutput     `json:"set_output,omitempty"`
	SetTitle      *SetTitle      `json:"set_title,omitempty"`
	SetTags       *SetTags       `json:"set_tags,omitempty"`
	DeleteSession *DeleteSession `json:"delete_session,omitempty"`
	RetryDenied   *RetryDenied   `json:"retry_denied,omitempty"`
	ContinueChild *ContinueChild `json:"continue_child,omitempty"`
	// Schedule creates, cancels or dispatches a durable one-shot message.
	Schedule    *Schedule    `json:"schedule,omitempty"`
	Kind        CommandKind  `json:"kind"`
	UserMessage *UserMessage `json:"user_message,omitempty"`
	// BackgroundNotice reports a background job ending or waiting for input.
	BackgroundNotice *BackgroundNotice `json:"background_notice,omitempty"`
	// Compact requests context compaction.
	Compact *CompactRequest `json:"compact,omitempty"`
	// HostNotice carries the host's word of work outside the conversation.
	HostNotice *HostNotice `json:"host_notice,omitempty"`
	// WithdrawSteer takes back a steer no model call has taken yet.
	WithdrawSteer *WithdrawSteer `json:"withdraw_steer,omitempty"`
	// BackgroundCalls asks running calls to move to the background.
	BackgroundCalls *BackgroundCalls `json:"background_calls,omitempty"`
}
```

Command is host input. Kind says which field is set.


### Command.Validate

```go
func (c Command) Validate() error
```

Validate checks command content and a nonempty caller-assigned ID. An empty ID is allowed at ingress so the driver can assign one before acceptance.

**Example**

```go
c := event.Command{ID: "request-1", Kind: event.CommandUserMessage, UserMessage: &event.UserMessage{Text: "go"}}
fmt.Println(c.Validate())
fmt.Println((event.Usage{OutputTokens: 5, ReasoningTokens: 3}).Valid())
fmt.Println((event.Usage{OutputTokens: 2, ReasoningTokens: 3}).Valid())
// Output:
// <nil>
// true
// false
```

Output:

```text
<nil>
true
false
```


### Command.ValidateID

```go
func (c Command) ValidateID(id string) error
```

ValidateID checks an acceptance ID. Occurrences use their canonical range ID (up to 147 bytes); other commands retain the 128-byte command ID bound.


## CommandAccepted

```go
type CommandAccepted struct {
	// CommandID is assigned by the client. It is the command's one ID in
	// the log: Command.ID is empty, or equal to it in logs written before
	// zelk kept one; a log where they differ doesn't fold.
	CommandID string  `json:"command_id"`
	Command   Command `json:"command"`
}
```

CommandAccepted records a host command once it is persisted. Commands take effect only from here.


### CommandAccepted.Kind

```go
func (CommandAccepted) Kind() Kind
```

Kind returns [KindCommandAccepted](/reference/go/event/).


## CommandKind

```go
type CommandKind string
```

CommandKind names the type of a [Command](/reference/go/event/#command).

```go
const (
	CommandUserMessage CommandKind = "user_message"
	// CommandInterrupt ends the current run after cancelling its effects.
	CommandInterrupt CommandKind = "interrupt"
	// CommandSetModel changes the model at the next safe boundary.
	CommandSetModel CommandKind = "set_model"
	// CommandInjectContext appends host context for subsequent model calls.
	CommandInjectContext CommandKind = "inject_context"
	// CommandSetPermissionMode changes the permission mode at the next
	// safe boundary.
	CommandSetPermissionMode CommandKind = "set_permission_mode"
	// CommandSetRules replaces the session's permission rules and
	// protected paths at the next safe boundary.
	CommandSetRules CommandKind = "set_rules"
	// CommandSetPolicy replaces the session's whole permission policy at
	// the next safe boundary.
	CommandSetPolicy CommandKind = "set_policy"
	// CommandSetGoal replaces the goal; CommandClearGoal reverts it to
	// the user's request, or marks it abandoned.
	CommandSetGoal   CommandKind = "set_goal"
	CommandClearGoal CommandKind = "clear_goal"
	// CommandSteer adds input to the current run.
	CommandSteer CommandKind = "steer"
	// CommandAnswerInput answers a request for human input.
	CommandAnswerInput CommandKind = "answer_input"
	// CommandInvokeSkill loads a skill the user invoked by name and sends
	// its instructions as a user message.
	CommandInvokeSkill CommandKind = "invoke_skill"
	// CommandSetOutput gives the next run its own structured output
	// contract.
	CommandSetOutput CommandKind = "set_output"
	// CommandSetTitle names the session for a session picker. It starts no run.
	CommandSetTitle CommandKind = "set_title"
	// CommandSetTags replaces session tags; CommandDeleteSession permanently tombstones an idle session.
	CommandSetTags       CommandKind = "set_tags"
	CommandDeleteSession CommandKind = "delete_session"
	// CommandRetryDenied permits one further classification of a retained denial.
	CommandRetryDenied CommandKind = "retry_denied"
	// CommandContinueChild begins a new run in a finished child.
	CommandContinueChild CommandKind = "continue_child"
	// CommandSchedule creates, cancels or dispatches a durable one-shot message.
	CommandSchedule CommandKind = "schedule"
	// CommandCreateSource records a new wake source.
	CommandCreateSource CommandKind = "create_source"
	// CommandEndSource permanently ends a source, including cancellation.
	CommandEndSource CommandKind = "end_source"
	// CommandOccurrence admits a fixed occurrence range as a background notice.
	CommandOccurrence CommandKind = "occurrence"
	// Requirement commands are accepted only while idle.
	CommandSetVerificationWork CommandKind = "set_verification_work"
	CommandDeclareRequirement  CommandKind = "declare_requirement"
	CommandRetireRequirement   CommandKind = "retire_requirement"
	// CommandBackgroundNotice tells the model a background job finished or
	// waits for input. It is not the user's: it
	// never becomes the goal, and it starts a run only when idle.
	CommandBackgroundNotice CommandKind = "background_notice"
	// CommandCompact asks for a compaction: while
	// idle it starts a run that only compacts; mid-run the next model call
	// compacts first.
	CommandCompact CommandKind = "compact"
	// CommandHostNotice tells the model what the host did for the user
	// outside the conversation, such as a command that failed.
	// It starts no run: the model reads it at its
	// next call, as the host's word, not the user's.
	CommandHostNotice CommandKind = "host_notice"
	// CommandWithdrawSteer takes back a steer no model call has taken yet.
	// Its SteerWithdrawn record says whether it did.
	CommandWithdrawSteer CommandKind = "withdraw_steer"
	// CommandBackgroundCalls asks the run under way to move its running
	// calls that can to the background; with
	// SendNow, to go on to its next model call at once as well. Its
	// BackgroundRequested record says what it asked of which calls.
	CommandBackgroundCalls CommandKind = "background_calls"
)
```

The supported command kinds.


## Compact

```go
type Compact struct {
	// Cut is how many history items, from the start, the summary
	// replaces; the rest are kept as they are.
	Cut int `json:"cut"`
	// Native asks the provider for its own compacted window as well, for
	// later calls to the same provider family.
	Native bool `json:"native,omitempty"`
	// Reactive marks a compaction after the provider refused a request as
	// too long, rather than one the context bounds called for.
	Reactive bool `json:"reactive,omitempty"`
	// Manual marks a compaction someone asked for (CommandCompact), and
	// Focus is what they asked the summary to keep, so a replay sends the
	// same request.
	Manual bool   `json:"manual,omitempty"`
	Focus  string `json:"focus,omitempty"`
}
```

Compact is a compaction call: a model call that writes a portable summary of the history before Cut, which then replaces it. Retries, reservations and recovery are those of every model call.


## CompactRequest

```go
type CompactRequest struct {
	// Focus is what the user wants the summary to keep, added to the
	// summary prompt; empty for none.
	Focus string `json:"focus,omitempty"`
}
```

CompactRequest asks for a compaction now, as a user's /compact does.


## Compaction

```go
type Compaction struct {
	// Threshold is the estimated input, in tokens, above which the
	// history is compacted before the next model call.
	Threshold int64 `json:"threshold"`
	// Keep is how much of the most recent history, in estimated tokens,
	// a full compaction keeps as it is.
	Keep int64 `json:"keep"`
	// Prompt is the instruction a compaction call ends with, recorded so
	// a session keeps the one it started with.
	Prompt string `json:"prompt"`
	// Clear is the estimated input, in tokens, above which older tool
	// results are replaced with stubs before the next model call, however
	// far the full-compaction threshold is. Zero
	// clears only on the way to a full compaction.
	Clear int64 `json:"clear,omitempty"`
	// ClearAtLeast is the fewest estimated tokens a clearing pass removes:
	// a pass rewrites the cached prefix, so a smaller one waits until it
	// is worth that cache miss.
	ClearAtLeast int64 `json:"clear_at_least,omitempty"`
}
```

Compaction configures the compaction ladder.


## Completion

```go
type Completion struct {
	// Continuations is how many continuation turns the completion check
	// may ask for before the run ends incomplete.
	Continuations int `json:"continuations"`
	// RequireVerification makes success need fresh passing evidence for
	// every host check.
	RequireVerification bool `json:"require_verification,omitempty"`
	// RepeatLimit stops a run as incomplete when one action fails the same
	// way this many times; a reminder comes the time before.
	RepeatLimit int `json:"repeat_limit"`
	// RequireReport makes a run end through the model's ReportOutcome
	// step: a turn that ends without one takes a continuation, and a run
	// never succeeds on silence.
	RequireReport bool `json:"require_report,omitempty"`
}
```

Completion configures the completion check.


## CompletionChecked

```go
type CompletionChecked struct {
	ID           string            `json:"id"`
	Run          uint64            `json:"run"`
	GoalRevision int               `json:"goal_revision"`
	EvidenceIDs  []string          `json:"evidence_ids,omitempty"`
	Verdict      CompletionVerdict `json:"verdict"`
	Reason       string            `json:"reason,omitempty"`
	// The rest is the decision the check reached, which a stored log
	// replays as recorded: whether the run continues, else its outcome
	// and detail, and what sent it back (unproven checks or claims, a
	// missing report, a partial or not_met report nothing forced).
	Continue bool       `json:"continue,omitempty"`
	Outcome  RunOutcome `json:"outcome,omitempty"`
	Detail   string     `json:"detail,omitempty"`
	Checks   bool       `json:"checks,omitempty"`
	Report   bool       `json:"report,omitempty"`
	Stopped  bool       `json:"stopped,omitempty"`
}
```

CompletionChecked records the decision about a normal ending candidate. EvidenceIDs includes the latest evidence considered, including failed checks.


### CompletionChecked.Kind

```go
func (CompletionChecked) Kind() Kind
```

Kind returns KindCompletionChecked.


## CompletionVerdict

```go
type CompletionVerdict string
```

CompletionVerdict is the completion check's verdict on a run that reported its outcome.

```go
const (
	// CompletionSuccess ends the run successfully.
	CompletionSuccess CompletionVerdict = "success"
	// CompletionIncomplete ends it incomplete, CompletionBlocked blocked.
	CompletionIncomplete CompletionVerdict = "incomplete"
	CompletionBlocked    CompletionVerdict = "blocked"
	// CompletionContinue sends the model back to work.
	CompletionContinue CompletionVerdict = "continue"
)
```

The completion verdicts.


## Config

```go
type Config struct {
	// VerificationContract is fixed at session creation. The zero value is
	// run-local and is recorded explicitly.
	VerificationContract VerificationContract `json:"verification_contract"`
	// RequirementWorkspaceID is the host-selected identity for scoped verification.
	RequirementWorkspaceID string `json:"requirement_workspace_id,omitempty"`
	// Checkpoints saves the old version of each file the session's tools
	// change, so a restore can undo them (docs/design/checkpoints.md).
	Checkpoints bool `json:"checkpoints,omitempty"`
	// Policy is the permission policy the session starts with.
	// Nil allows every tool.
	Policy *Policy `json:"policy,omitempty"`
	// MaxTime bounds wall time per run, including crash downtime.
	MaxTime time.Duration `json:"max_time,omitempty"`
	// CallTimeout and ToolTimeout bound each dispatched attempt.
	CallTimeout    time.Duration `json:"call_timeout,omitempty"`
	ToolTimeout    time.Duration `json:"tool_timeout,omitempty"`
	HarnessVersion string        `json:"harness_version"`
	// ReducerVersion is the major version of the reducer that wrote the
	// log. Resuming is supported only within the same major version.
	ReducerVersion int `json:"reducer_version"`
	// SystemPrompt is the rendered system prompt.
	SystemPrompt string `json:"system_prompt"`
	// Context is the rendered dynamic context (date, working directory and
	// the like), recorded so replay never reads the clock or the workspace.
	Context string `json:"context,omitempty"`
	// Scratch is the absolute path, on the environment's host, of the
	// session's scratch directory, outside the workspace: its commands may
	// write it and its file tools reach it. Empty for a session
	// without one (zelk.WithScratch).
	Scratch string `json:"scratch,omitempty"`
	// Cwd is the working directory the session starts in, relative to the
	// environment's workspace ("." is its top). Tools start from it until
	// a CwdChanged event moves it.
	Cwd string `json:"cwd"`
	// MaxTurns ends the run with outcome max_turns after this many model
	// turns. Zero means no limit.
	MaxTurns int `json:"max_turns,omitempty"`
	// Budget limits the tokens each run may commit (docs/design/durability.md,
	// B5); nil means no limits.
	Budget *Budget `json:"budget,omitempty"`
	// Allocation is the share of a parent's budget a child session was
	// given, enforced as a hard limit over the session's whole life
	// (B7); nil for a session that isn't a child.
	Allocation *Tokens    `json:"allocation,omitempty"`
	Tools      []ToolSpec `json:"tools"`
	// Shells names the shell tools the session's host runs, in the order it
	// offers them, the primary first: "PowerShell" and "Bash". It is what a
	// session needs of its host even if a tool is withheld from the model:
	// Watch and Verify run commands in the first, and a skill's commands in
	// Bash if it is there, else in the first. A driver must offer the same.
	Shells []string `json:"shells,omitempty"`
	// DeferredTools names tools whose schemas are discovered with ToolSearch.
	// Their full definitions stay in Tools for authorization and recovery.
	DeferredTools []string `json:"deferred_tools,omitempty"`
	// MaterializerNamespace optionally binds publication to a stable backend.
	MaterializerNamespace string `json:"materializer_namespace,omitempty"`
	// Materializer requires recorded skill publication support on every resume.
	Materializer bool `json:"materializer,omitempty"`
	// WorkspaceDelta records that this session requires an environment Differ.
	WorkspaceDelta bool           `json:"workspace_delta,omitempty"`
	Provider       history.Family `json:"provider"`
	Model          string         `json:"model"`
	Settings       ModelSettings  `json:"settings"`
	// Capabilities is the provider's capability snapshot for the model.
	Capabilities Capabilities `json:"capabilities"`
	// ToolReserves are the reservations, by tool name, of tools whose
	// model calls depend on the route (tool.WithRouteReservation),
	// resolved with the capabilities so replay never asks again. An entry
	// replaces the tool's recorded Reserve; zero tokens mean the bound is
	// unknown, which a hard budget refuses.
	ToolReserves map[string]Tokens `json:"tool_reserves,omitempty"`
	// Instructions are the project instruction files loaded when the
	// session started: those of the workspace's top directory.
	Instructions []InstructionsLoaded `json:"instructions,omitempty"`
	// InstructionLimit bounds the combined size, in bytes, of the project
	// instructions loaded at once; zero means project instructions are
	// off.
	InstructionLimit int `json:"instruction_limit,omitempty"`
	// Skills is the skill index the model sees: the skills it may load
	// with the Skill tool.
	Skills []SkillEntry `json:"skills,omitempty"`
	// UnlistedSkills names the skills the index had no room to describe;
	// the model may still load them by name.
	UnlistedSkills []string `json:"unlisted_skills,omitempty"`
	// Input says how requests for human input are resolved; nil for a
	// session without them.
	Input *InputConfig `json:"input,omitempty"`
	// Hooks are the gate hooks registered for the session, in
	// registration order, which decides how their results combine.
	// The functions are looked up by name when a hook
	// runs; replay uses the recorded decisions and runs none.
	Hooks []HookSpec `json:"hooks,omitempty"`
	// Classifier configures the auto-mode classifier; nil for a session
	// that can't enter auto mode.
	Classifier *Classifier `json:"classifier,omitempty"`
	// AgentType is the subagent type of a child session, "" for a root
	// session; hooks see it, and a child's Stop hooks are SubagentStop.
	AgentType string `json:"agent_type,omitempty"`
	// ChildOf is, for a child session, the parent session and the call
	// that started it, from which its ID derives (ChildSessionID); nil for
	// a conversation. It is how a log under a subagent's ID shows it is
	// that subagent's, and it never changes.
	ChildOf *ChildOrigin `json:"child_of,omitempty"`
	// UserRequests are, for a child session, what
	// the real user had said when its parent started or continued it. The
	// child's own messages come from the parent model, so its reviewer
	// judges actions against these instead.
	UserRequests []string `json:"user_requests,omitempty"`
	// ParentRefused are, for a child session, the
	// actions its parent's reviewer had refused when it started or last
	// continued the child, so a refused job handed down isn't judged anew.
	ParentRefused []Refusal `json:"parent_refused,omitempty"`
	// Root is the workspace's absolute path as the model sees it, so the
	// decision algorithm can resolve the paths tool calls name without
	// consulting the environment.
	Root string `json:"root,omitempty"`
	// Worktree says the workspace is a git worktree of its own, so
	// a shell command that may run git against another
	// checkout is refused.
	Worktree bool `json:"worktree,omitempty"`
	// Checks are the host's verification checks.
	Checks []Check `json:"checks,omitempty"`
	// Completion configures finalization; nil, as in logs from before it,
	// finishes a run when the model ends its turn.
	Completion *Completion `json:"completion,omitempty"`
	// Compaction sets when and how the history is compacted; nil turns
	// proactive compaction off.
	Compaction *Compaction `json:"compaction,omitempty"`
	// Memory is the memory view the session starts with, or the one a
	// compaction took up (docs/design/memory.md).
	Memory string `json:"memory,omitempty"`
	// Output is the structured output contract; nil for a session that
	// returns text.
	Output *Output `json:"output,omitempty"`
	// MCP are the MCP servers whose tools the session was offered, as
	// they introduced themselves; the tools themselves are in Tools.
	MCP []MCPServer `json:"mcp,omitempty"`
	// Quotas bound what the session consumes; nil leaves it unbounded.
	Quotas *Quotas `json:"quotas,omitempty"`
}
```

Config is the configuration a session runs with, resolved to plain data.


## ConfigChanged

```go
type ConfigChanged struct {
	Config Config `json:"config"`
}
```

ConfigChanged upgrades the resolved configuration of an idle session.


### ConfigChanged.Kind

```go
func (ConfigChanged) Kind() Kind
```

Kind returns KindConfigChanged.


## Confirmation

```go
type Confirmation string
```

Confirmation is how a model says it confirmed a requirement of its task.

```go
const (
	// RanCheck: the model ran something that shows the requirement holds.
	RanCheck Confirmation = "ran_check"
	// ReadOnly: the model confirmed it by reading, without running
	// anything.
	ReadOnly Confirmation = "read_only"
	// NotChecked: the model couldn't confirm it.
	NotChecked Confirmation = "not_checked"
)
```

The confirmations a report may give.


## ContinuationUsed

```go
type ContinuationUsed struct {
	ID           string `json:"id"`
	Run          uint64 `json:"run"`
	GoalRevision int    `json:"goal_revision"`
	N            int    `json:"n"`
}
```

ContinuationUsed records consumption of one completion continuation.


### ContinuationUsed.Kind

```go
func (ContinuationUsed) Kind() Kind
```

Kind returns KindContinuationUsed.


## ContinueChild

```go
type ContinueChild struct {
	ExpectedSeq   uint64  `json:"expected_seq"`
	ParentSession string  `json:"parent_session"`
	ParentEffect  string  `json:"parent_effect"`
	Prompt        string  `json:"prompt"`
	ParentPolicy  *Policy `json:"parent_policy"`
	Allocation    *Tokens `json:"allocation,omitempty"`
	// UserRequests replace the child's Config.UserRequests:
	// what the real user has said by now.
	UserRequests []string `json:"user_requests,omitempty"`
	// ParentRefused replace the child's Config.ParentRefused.
	ParentRefused []Refusal `json:"parent_refused,omitempty"`
	// Hooks replace the child's gate hooks: those of the agent continuing
	// it, as SetPolicy's do.
	Hooks []HookSpec `json:"hooks,omitempty"`
}
```

ContinueChild is a host-resolved continuation of a finished child. Its command ID derives from the parent effect; replay never appends the same work twice.


## CwdChanged

```go
type CwdChanged struct {
	Cwd string `json:"cwd"`
}
```

CwdChanged records the working directory the Bash tool ended in, relative to the workspace, which the next call starts from.


### CwdChanged.Kind

```go
func (CwdChanged) Kind() Kind
```

Kind returns [KindCwdChanged](/reference/go/event/).


## DeleteSession

```go
type DeleteSession struct{}
```

DeleteSession permanently tombstones an idle session, retaining its audit log.


## Effect

```go
type Effect struct {
	ReleaseMaterialization *ReleaseMaterialization `json:"release_materialization,omitempty"`
	Materialize            *Materialize            `json:"materialize,omitempty"`
	// SetTimer records a timer whose anchor the reducer already folded.
	SetTimer     *TimerSet     `json:"set_timer,omitempty"`
	Kind         EffectKind    `json:"kind"`
	CallProvider *CallProvider `json:"call_provider,omitempty"`
	RunTool      *RunTool      `json:"run_tool,omitempty"`
	AwaitInput   *AwaitInput   `json:"await_input,omitempty"`
	RunHook      *RunHook      `json:"run_hook,omitempty"`
	Classify     *Classify     `json:"classify,omitempty"`
}
```

Effect is what the driver is about to do, as plain data. Kind says which field is set.


### Effect.CallID

```go
func (e Effect) CallID() string
```

CallID is the tool call the effect serves: the call it runs, asks the user about, classifies or runs a hook for. It is empty for a model call or a timer, and for a hook no tool call triggered.


## EffectCancelled

```go
type EffectCancelled struct {
	EffectID string `json:"effect_id"`
	Attempt  int    `json:"attempt"`
	// EffectKind and CallID repeat the effect's kind and the tool call it
	// served, from its EffectStarted, so a reader can show the ending
	// without looking up the start. loop.Records fills them.
	EffectKind EffectKind `json:"effect_kind,omitempty"`
	CallID     string     `json:"call_id,omitempty"`
	Reason     string     `json:"reason"`
	// Cause is what ended the run the effect belonged to. It is never
	// empty: the user's interrupt is CancelInterrupt.
	Cause CancelCause    `json:"cause"`
	Items []history.Item `json:"items,omitempty"`
	// Usage is what a cancelled model call reported spending, if it did.
	Usage *Usage `json:"usage,omitempty"`
}
```

EffectCancelled ends an effect that was cancelled, for example by a user interrupt. Items carries the results the model sees instead, such as "cancelled by user" for each pending tool call.


### EffectCancelled.Kind

```go
func (EffectCancelled) Kind() Kind
```

Kind returns [KindEffectCancelled](/reference/go/event/).


## EffectFinished

```go
type EffectFinished struct {
	EffectID string `json:"effect_id"`
	Attempt  int    `json:"attempt"`
	// EffectKind and CallID repeat the effect's kind and the tool call it
	// served, from its EffectStarted, so a reader can show the ending
	// without looking up the start. loop.Records fills them.
	EffectKind EffectKind     `json:"effect_kind,omitempty"`
	CallID     string         `json:"call_id,omitempty"`
	Outcome    Outcome        `json:"outcome"`
	Items      []history.Item `json:"items,omitempty"`
	Usage      *Usage         `json:"usage,omitempty"`
	// StopReason is the provider's stop reason for a CallProvider effect.
	StopReason string `json:"stop_reason,omitempty"`
	// StopDetails says why a provider stopped, where it says more than
	// the reason: for a refusal, which safety classifier declined, if one
	// did.
	StopDetails *StopDetails `json:"stop_details,omitempty"`
	// Error describes a failed or unknown outcome.
	Error string `json:"error,omitempty"`
	// Estimate is a guess at what a model call spent when its response
	// arrived without usage, for reporting only (docs/design/durability.md, B4).
	Estimate *Tokens `json:"estimate,omitempty"`
	// ErrorKind classifies a failed model call. The loop acts on
	// "context_overflow", a prompt the model refused as too long.
	ErrorKind ModelErrorKind `json:"error_kind,omitempty"`
	// Native is the provider's own compacted window, for a compaction call
	// that asked for one; it is used only with the same provider family.
	Native []history.Item `json:"native,omitempty"`
	// NativeOutcome records delivery separately from the portable request.
	// A native compaction that succeeded must say; no other finish may.
	NativeOutcome NativeOutcome `json:"native_outcome,omitempty"`
}
```

EffectFinished is the one authoritative transition that ends an effect: the model-visible result items and the usage settlement are recorded with it, atomically (docs/design/durability.md, E3).


### EffectFinished.Kind

```go
func (EffectFinished) Kind() Kind
```

Kind returns [KindEffectFinished](/reference/go/event/).


## EffectKind

```go
type EffectKind string
```

EffectKind names the type of an [Effect](/reference/go/event/#effect).

```go
const (
	// EffectSetTimer records a derived timer atomically with its start and finish.
	EffectSetTimer     EffectKind = "set_timer"
	EffectCallProvider EffectKind = "call_provider"
	EffectRunTool      EffectKind = "run_tool"
	// EffectAwaitInput is a request for human input: a
	// question or a plan to approve. Its effect ID is the request ID.
	EffectAwaitInput EffectKind = "await_input"
	// EffectRunHook invokes one gate hook. Its effect ID is the hook's
	// invocation ID (docs/design/durability.md, H1).
	EffectRunHook EffectKind = "run_hook"
	// EffectClassifyAction asks the auto-mode classifier about an action.
	// It reserves and is charged like a model call.
	EffectClassifyAction EffectKind = "classify_action"
	// EffectMaterialize publishes a recorded content-addressed skill bundle.
	EffectMaterialize EffectKind = "materialize"
	// EffectReleaseMaterialization releases a recorded artifact without a model run.
	EffectReleaseMaterialization EffectKind = "release_materialization"
)
```

The effect kinds.


## EffectReconciled

```go
type EffectReconciled struct {
	EffectID string `json:"effect_id"`
	Attempt  int    `json:"attempt"`
	// EffectKind and CallID repeat the effect's kind and the tool call it
	// served, from its EffectStarted, so a reader can show the ending
	// without looking up the start. loop.Records fills them.
	EffectKind EffectKind     `json:"effect_kind,omitempty"`
	CallID     string         `json:"call_id,omitempty"`
	Outcome    Outcome        `json:"outcome"`
	Items      []history.Item `json:"items,omitempty"`
	Reason     string         `json:"reason"`
}
```

EffectReconciled ends a tool call that recovery found open and couldn't run again (docs/design/durability.md, R4): its outcome is unknown, and Items tell the model so. Every other kind of effect is retried instead, and loop.Step refuses an EffectReconciled for one.


### EffectReconciled.Kind

```go
func (EffectReconciled) Kind() Kind
```

Kind returns [KindEffectReconciled](/reference/go/event/).


## EffectStarted

```go
type EffectStarted struct {
	// EffectID is deterministic from the session, the sequence number of
	// the event that produced the effect, and its index among that
	// event's effects.
	EffectID string `json:"effect_id"`
	// Attempt counts dispatches of the same effect, starting at 1.
	Attempt int    `json:"attempt"`
	Effect  Effect `json:"effect"`
	// Deadline is the absolute time by which the effect must finish. The
	// zero time means none.
	Deadline time.Time `json:"deadline,omitzero"`
	// Reservation is the attempt's reservation, for an effect that calls
	// a model; nil otherwise.
	Reservation *Reservation `json:"reservation,omitempty"`
}
```

EffectStarted records the intent to run an effect before it is dispatched (docs/design/durability.md, "Guarantees").


### EffectStarted.Kind

```go
func (EffectStarted) Kind() Kind
```

Kind returns [KindEffectStarted](/reference/go/event/).


## Effort

```go
type Effort string
```

Effort is a level of reasoning effort. The levels are the ones every provider zelk speaks accepts.

```go
const (
	EffortLow    Effort = "low"
	EffortMedium Effort = "medium"
	EffortHigh   Effort = "high"
)
```

The reasoning effort levels.


### Effort.Valid

```go
func (e Effort) Valid() bool
```

Valid reports whether e is one of the defined levels.


## Event

```go
type Event struct {
	// Seq is the event's position in its session log, starting at 1. The
	// driver numbers the events it appends, and the log store checks that
	// they continue the log without a gap.
	Seq uint64
	// Time is when the event was recorded, from the driver's clock.
	Time    time.Time
	Payload Payload
}
```

Event is one entry of a session log.

An Event encodes to and decodes from JSON as an envelope carrying the payload's kind and the log's format [Generation](/reference/go/event/):

	{"seq":1,"time":"...","kind":"warning","v":108,"payload":{...}}

An envelope of another generation is refused before its payload is read. A kind this zelk doesn't know, in an envelope of its generation, decodes as [Unknown](/reference/go/event/#unknown) and encodes back unchanged.

**Example**

```go
ev := event.Event{
	Seq:     1,
	Time:    time.Date(2026, 10, 15, 9, 0, 0, 0, time.UTC),
	Payload: event.Warning{Code: "reasoning_dropped", Message: "opaque reasoning is not sent across provider families"},
}
data, _ := json.Marshal(ev)
fmt.Println(string(data))

var back event.Event
_ = json.Unmarshal(data, &back)
fmt.Println(back.Kind(), back.Payload.(event.Warning).Code)
// Output:
// {"seq":1,"time":"2026-10-15T09:00:00Z","kind":"warning","v":109,"payload":{"code":"reasoning_dropped","message":"opaque reasoning is not sent across provider families"}}
// warning reasoning_dropped
```

Output:

```text
{"seq":1,"time":"2026-10-15T09:00:00Z","kind":"warning","v":109,"payload":{"code":"reasoning_dropped","message":"opaque reasoning is not sent across provider families"}}
warning reasoning_dropped
```


### Decode

```go
func Decode(data []byte) (Event, error)
```

Decode reads an envelope written by [Encode](/reference/go/event/#encode). An envelope of an earlier generation fails with [ErrFormatBreak](/reference/go/event/) and one of a later generation with [ErrUnsupportedVersion](/reference/go/event/). It rejects events that couldn't be encoded again, so everything in a log can be copied.


### Event.Kind

```go
func (e Event) Kind() Kind
```

Kind returns the kind of the event's payload, or "" if it has none.


### Event.MarshalJSON

```go
func (e Event) MarshalJSON() ([]byte, error)
```

MarshalJSON encodes the event like [Encode](/reference/go/event/#encode). Note that encoding/json re-compacts and re-escapes what MarshalJSON returns, so an [Unknown](/reference/go/event/#unknown) payload keeps its meaning through json.Marshal but not necessarily its exact bytes; use [Encode](/reference/go/event/#encode) where bytes matter.


### Event.UnmarshalJSON

```go
func (e *Event) UnmarshalJSON(data []byte) error
```

UnmarshalJSON decodes the event like [Decode](/reference/go/event/#decode).


## EvidenceRecorded

```go
type EvidenceRecorded struct {
	// Scope binds a new-contract observation to its producing run and work.
	// Nil preserves the legacy evidence shape and its recorded semantics.
	Scope *EvidenceScope `json:"scope,omitempty"`
	// ID is the evidence's ID: the Verify call's effect ID.
	ID      string `json:"id"`
	Check   string `json:"check"`
	Command string `json:"command"`
	// Source is EvidenceHost for a host check, EvidenceModel for one the
	// model registered.
	Source     EvidenceSource `json:"source"`
	Exit       int            `json:"exit"`
	Completed  bool           `json:"completed"`
	Passed     bool           `json:"passed"`
	Generation uint64         `json:"generation"`
	// Output is the check's output, bounded.
	Output string `json:"output,omitempty"`
}
```

EvidenceRecorded is a check's run as the harness captured it: its command, exit status and output, and the mutation generation it ran at. The model supplies none of it.


### EvidenceRecorded.Kind

```go
func (EvidenceRecorded) Kind() Kind
```

Kind returns [KindEvidenceRecorded](/reference/go/event/).


## EvidenceScope

```go
type EvidenceScope struct {
	WorkspaceID         string `json:"workspace_id"`
	Run                 uint64 `json:"run"`
	WorkID              string `json:"work_id"`
	WorkRevision        uint64 `json:"work_revision"`
	RequirementID       string `json:"requirement_id,omitempty"`
	RequirementRevision uint64 `json:"requirement_revision,omitempty"`
}
```

EvidenceScope attributes an observation to its producing workspace, run and work revision. An absent requirement reference means observation only. A requirement revision binds meaning; work revision records production context and does not itself retire or invalidate unaffected requirements.


### EvidenceScope.Validate

```go
func (s EvidenceScope) Validate() error
```

Validate checks complete provenance and a paired optional requirement reference. Workspace identity is host-selected opaque data, never inferred from a path.


## EvidenceSource

```go
type EvidenceSource string
```

EvidenceSource says who registered a verification check.

```go
const (
	EvidenceHost  EvidenceSource = "host"
	EvidenceModel EvidenceSource = "model"
)
```

The evidence sources.


## ExecutionTraced

```go
type ExecutionTraced struct {
	// TraceID and SpanID are hex, as W3C Trace Context writes them.
	TraceID string `json:"trace_id"`
	SpanID  string `json:"span_id"`
}
```

ExecutionTraced records the trace span of an execution that took up the session, so a later execution, in this process or another, links its span to this one.


### ExecutionTraced.Kind

```go
func (ExecutionTraced) Kind() Kind
```

Kind returns [KindExecutionTraced](/reference/go/event/).


## FileChanged

```go
type FileChanged struct {
	Path string `json:"path"`
	// Before is the revision replaced; "none" for a file created.
	Before string `json:"before"`
	After  string `json:"after"`
	Tool   string `json:"tool"`
	// Patch is a unified diff of the change; empty if it couldn't be
	// computed, and cut, with a note, past its bound.
	Patch string `json:"patch,omitempty"`
}
```

FileChanged records a change a built-in file tool made: the file's revisions before and after, and a bounded unified patch.


### FileChanged.Kind

```go
func (FileChanged) Kind() Kind
```

Kind returns [KindFileChanged](/reference/go/event/).


## FileDiff

```go
type FileDiff struct {
	Path    string   `json:"path"`
	Before  string   `json:"before"`
	After   string   `json:"after"`
	Tools   []string `json:"tools"`
	Patches []string `json:"patches,omitempty"`
}
```

FileDiff is one file's net change in a turn.


## FileObserved

```go
type FileObserved struct {
	Path     string `json:"path"`
	Revision string `json:"revision"`
	// Lines is the range read, or nil if the whole file was read.
	Lines *LineRange `json:"lines,omitempty"`
}
```

FileObserved records that a built-in tool read a file at a revision. Writes check it to detect files that changed since they were read (docs/design/tools.md, "Staleness").


### FileObserved.Kind

```go
func (FileObserved) Kind() Kind
```

Kind returns [KindFileObserved](/reference/go/event/).


## FileRestoreApplied

```go
type FileRestoreApplied struct {
	ID   string `json:"id"`
	Path string `json:"path"`
}
```

FileRestoreApplied acknowledges one synchronized file write or deletion. A crash before this record leaves that file's outcome unknown.


### FileRestoreApplied.Kind

```go
func (FileRestoreApplied) Kind() Kind
```

Kind returns KindFileRestoreApplied.


## FileRestoreChange

```go
type FileRestoreChange struct {
	Path   string        `json:"path"`
	Before *SnapshotFile `json:"before,omitempty"`
	After  *SnapshotFile `json:"after,omitempty"`
}
```

FileRestoreChange describes one regular file's expected and restored contents. A nil Before creates a file; a nil After deletes one. Both cannot be nil.


## FileRestoreFinished

```go
type FileRestoreFinished struct {
	ID    string `json:"id"`
	Error string `json:"error,omitempty"`
}
```

FileRestoreFinished closes a restore. Empty Error means every file was applied; otherwise unapplied files may have changed and must be inspected before retry.


### FileRestoreFinished.Kind

```go
func (FileRestoreFinished) Kind() Kind
```

Kind returns KindFileRestoreFinished.


## FileRestorePlan

```go
type FileRestorePlan struct {
	Changes  []FileRestoreChange  `json:"changes,omitempty"`
	Excluded []WorkspaceExclusion `json:"excluded,omitempty"`
}
```

FileRestorePlan lists changes in path order and paths that remain untouched. Its ignore/exclusion scope is fixed at the final confirmation check. Exclusions are display metadata, never filesystem inputs.


## FileRestoreRequested

```go
type FileRestoreRequested struct {
	ID       string          `json:"id"`
	Boundary string          `json:"boundary"`
	Plan     FileRestorePlan `json:"plan"`
}
```

FileRestoreRequested records a confirmed file-only restore before any mutation. Boundary is "point:\<seq>", a rewind point whose checkpointed files the plan restores. Conversation history survives.


### FileRestoreRequested.Kind

```go
func (FileRestoreRequested) Kind() Kind
```

Kind returns KindFileRestoreRequested.


## FileVersion

```go
type FileVersion struct {
	Path       string `json:"path"`
	Digest     string `json:"digest,omitempty"`
	Size       int64  `json:"size,omitempty"`
	Executable bool   `json:"executable,omitempty"`
	// Absent means no file was at Path.
	Absent bool `json:"absent,omitempty"`
	// Skipped says why the content wasn't saved, such as a symlink or a
	// file too large; such a path is never restored.
	Skipped string `json:"skipped,omitempty"`
}
```

FileVersion is one workspace path's content at one moment, as a checkpoint records it: the digest, size and executable bit of a regular file, or that the path was absent, or why its content wasn't saved. Path is workspace-relative and slash-separated.


### FileVersion.File

```go
func (v FileVersion) File() *SnapshotFile
```

File returns v as the restore plan's description of a file, or nil if no file is to be there.


### FileVersion.SameContent

```go
func (v FileVersion) SameContent(w FileVersion) bool
```

SameContent reports whether v and w describe the same state of a path: the same content and executable bit, or both absent. A skipped version is never the same as anything.


### FileVersion.Saved

```go
func (v FileVersion) Saved() bool
```

Saved reports whether v holds content: a regular file that was saved.


### FileVersion.Validate

```go
func (v FileVersion) Validate() error
```

Validate checks that v names a portable workspace path outside Git metadata and is exactly one of a saved file, an absence or a skip.


## FileVersionsDropped

```go
type FileVersionsDropped struct {
	Before uint64 `json:"before,omitempty"`
	All    bool   `json:"all,omitempty"`
}
```

FileVersionsDropped records versions the session no longer keeps; their content may then be removed from the history. All drops every version. Otherwise versions recorded before sequence number Before are reduced to the latest of each path, which content at the oldest point kept still needs, and older points lose their code restore.


### FileVersionsDropped.Kind

```go
func (FileVersionsDropped) Kind() Kind
```

Kind returns KindFileVersionsDropped.


## FileVersionsSaved

```go
type FileVersionsSaved struct {
	Run   uint64        `json:"run"`
	Start bool          `json:"start,omitempty"`
	More  bool          `json:"more,omitempty"`
	Calls []string      `json:"calls,omitempty"`
	Files []FileVersion `json:"files,omitempty"`
}
```

FileVersionsSaved records versions saved to the session's file history in run Run (docs/design/checkpoints.md). Start marks the run-start pass of a run a point started: the versions of tracked paths that changed since their last version. A pass too large for one record is split into consecutive records; More marks every part but the last, and the pass is the last part's. Otherwise Calls are the tool calls the versions were saved before, each of which may start only once listed. The content of every saved version is in the history before this is recorded.


### FileVersionsSaved.Kind

```go
func (FileVersionsSaved) Kind() Kind
```

Kind returns KindFileVersionsSaved.


## GoalStatus

```go
type GoalStatus string
```

GoalStatus is how far a run's goal was met.

```go
const (
	GoalMet     GoalStatus = "met"
	GoalPartial GoalStatus = "partial"
	GoalNotMet  GoalStatus = "not_met"
	GoalUnknown GoalStatus = "unknown"
)
```

The goal statuses.

```go
const GoalBlocked GoalStatus = "blocked"
```

GoalBlocked is the status a model reports when a constraint or missing information stops it; the run ends blocked.


## HookDecided

```go
type HookDecided struct {
	EffectID string     `json:"effect_id"`
	Hook     string     `json:"hook"`
	Event    string     `json:"event"`
	Result   HookResult `json:"result,omitzero"`
	TimedOut bool       `json:"timed_out,omitempty"`
	Error    string     `json:"error,omitempty"`
}
```

HookDecided records a gate hook's decision in the terminal batch of its invocation, so replay and resume use it and never run the hook again (docs/design/durability.md, H1). A hook that failed, panicked or timed out records Error or TimedOut; its gate fails closed.


### HookDecided.Kind

```go
func (HookDecided) Kind() Kind
```

Kind returns [KindHookDecided](/reference/go/event/).


## HookDecision

```go
type HookDecision string
```

HookDecision is a PreToolUse or PermissionRequest hook's decision; "" decides nothing.

```go
const (
	HookDeny  HookDecision = "deny"
	HookDefer HookDecision = "defer"
	HookAsk   HookDecision = "ask"
	HookAllow HookDecision = "allow"
)
```

The hook decisions, most restrictive first.


## HookInput

```go
type HookInput struct {
	Event     string `json:"event"`
	Session   string `json:"session"`
	AgentType string `json:"agent_type,omitempty"`
	// Tool events: the call, its input and, after it ran, its output.
	Tool    string          `json:"tool,omitempty"`
	CallID  string          `json:"call_id,omitempty"`
	Input   json.RawMessage `json:"input,omitempty"`
	Digest  string          `json:"digest,omitempty"`
	Output  string          `json:"output,omitempty"`
	IsError bool            `json:"is_error,omitempty"`
	// Reason is why a permission was asked for or denied.
	Reason string `json:"reason,omitempty"`
	// Suggestions are the rules a PermissionRequest hook may grant for
	// the rest of the session, as a person may.
	Suggestions []Suggestion `json:"suggestions,omitempty"`
	// Prompt is a submitted user message.
	Prompt string `json:"prompt,omitempty"`
	// Trigger is SessionStart's source (startup, resume, compact),
	// PreCompact's (auto or manual) or Stop's stop reason.
	Trigger string `json:"trigger,omitempty"`
	// CustomInstructions is a manual compaction's focus, for PreCompact.
	CustomInstructions string `json:"custom_instructions,omitempty"`
	// Provider and Model are a model switch's target.
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	// Text is the final assistant text of a run that is stopping.
	Text string `json:"text,omitempty"`
}
```

HookInput is what a hook invocation sees. Event says which fields are set; the hook package presents a typed view of each event.


## HookResult

```go
type HookResult struct {
	// Decision is "allow", "deny", "ask" or "defer" (PreToolUse), or
	// "allow" or "deny" (PermissionRequest); "" decides nothing.
	Decision HookDecision `json:"decision,omitempty"`
	// Block blocks the prompt, the stop, the compaction or the switch.
	Block bool `json:"block,omitempty"`
	// Reason explains a denial or a block; a Stop block's reason is the
	// prompt of the continuation turn.
	Reason string `json:"reason,omitempty"`
	// Input replaces a tool call's input (PreToolUse).
	Input json.RawMessage `json:"input,omitempty"`
	// Output replaces a tool's output (PostToolUse), when Replace is set.
	Output  string `json:"output,omitempty"`
	Replace bool   `json:"replace,omitempty"`
	// Context is extra context for the model.
	Context string `json:"context,omitempty"`
	// Note is a note to the model about a denial, or for the classifier.
	Note string `json:"note,omitempty"`
	// Suggestion, with an allow from a PermissionRequest hook, grants
	// the suggestion with that ID for the rest of the session.
	Suggestion string `json:"suggestion,omitempty"`
	// Message is for the user, never the model: a warning a host shows
	// where the hook ran, as Claude Code shows a hook's systemMessage.
	Message string `json:"message,omitempty"`
}
```

HookResult is what a hook invocation decided, for every event alike.


## HookSpec

```go
type HookSpec struct {
	// Patterns are separate wildcard patterns; no patterns matches every invocation.
	Patterns []string `json:"patterns,omitempty"`
	// Name identifies the hook function across processes.
	Name string `json:"name"`
	// Event is the hook event, such as "PreToolUse".
	Event string `json:"event"`
	// Timeout bounds one invocation. A gate that times out fails closed.
	Timeout time.Duration `json:"timeout"`
}
```

HookSpec is a gate hook as a session records it.


## HostNotice

```go
type HostNotice struct {
	Text string `json:"text"`
	// Error says it reports a failure.
	Error bool `json:"error,omitempty"`
}
```

HostNotice is the host's word of something it did for the user outside the conversation, such as a command the user ran that failed. The model reads it at its next call, so it can say what went wrong when asked, framed so it doesn't act on it unasked; a transcript shows it where it came.


## InjectContext

```go
type InjectContext struct {
	Text string `json:"text"`
}
```

InjectContext appends host text to the recorded dynamic context. It changes subsequent requests, preserves the static prompt prefix and starts no run.


## InputBound

```go
type InputBound string
```

InputBound names how a provider's input tokens are bounded.

```go
const (
	// InputBoundBytes: a text never takes more tokens than it has bytes.
	InputBoundBytes InputBound = "bytes"
)
```

The input bounds.


## InputConfig

```go
type InputConfig struct {
	Policy InputPolicy `json:"policy"`
	// Timeout expires an unanswered request this long after it is made;
	// zero means never.
	Timeout time.Duration `json:"timeout,omitempty"`
	// CountSuspended makes time spent suspended count against MaxTime;
	// by default it doesn't.
	CountSuspended bool `json:"count_suspended,omitempty"`
}
```

InputConfig configures requests for human input.


## InputKind

```go
type InputKind string
```

InputKind is the kind of a request for human input.

```go
const (
	InputQuestion InputKind = "question"
	InputPlanExit InputKind = "plan_exit"
	// InputApproval asks a human to approve an action the decision
	// algorithm couldn't allow. It is the AwaitApproval of
	// docs/design/durability.md, Q1: its effect ID is the approval ID.
	InputApproval InputKind = "approval"
)
```

The kinds of input request.


## InputPolicy

```go
type InputPolicy string
```

InputPolicy says who resolves a request for human input.

```go
const (
	// InputCallback: a host callback answers while the execution waits.
	InputCallback InputPolicy = "callback"
	// InputSuspend: the execution suspends; the answer comes with a
	// later Start.
	InputSuspend InputPolicy = "suspend"
	// InputDeny: no human is available (headless).
	InputDeny InputPolicy = "deny"
)
```

The input policies.


## InstructionsLoaded

```go
type InstructionsLoaded struct {
	// Dir is the workspace-relative directory the instructions apply to;
	// "." is the workspace's top.
	Dir string `json:"dir"`
	// Path is the file's workspace-relative path; empty records that the
	// directory's file is gone.
	Path     string `json:"path,omitempty"`
	Revision string `json:"revision,omitempty"`
	Content  string `json:"content,omitempty"`
	// Omitted says why a file that exists wasn't loaded, such as the
	// limit on the combined size of project instructions.
	Omitted string `json:"omitted,omitempty"`
}
```

InstructionsLoaded records a project instruction file (AGENTS.md and the like) as zelk loaded it, with the directory whose files it applies to. A later record for the same directory replaces it.


### InstructionsLoaded.Kind

```go
func (InstructionsLoaded) Kind() Kind
```

Kind returns [KindInstructionsLoaded](/reference/go/event/).


## InteractionMode

```go
type InteractionMode string
```

InteractionMode records whether a run may ask a person.

```go
const (
	// InteractionSession is the zero value: the run is governed only by the
	// session's recorded input configuration.
	InteractionSession InteractionMode = ""
	// InteractionInteractive allows the recorded input policy to ask a person.
	InteractionInteractive InteractionMode = "interactive"
	// InteractionAutonomous refuses all requests for human input, on every host.
	InteractionAutonomous InteractionMode = "autonomous"
)
```


## Interrupt

```go
type Interrupt struct {
	Reason string `json:"reason"`
}
```

Interrupt is a durable request to end the current run.


## InvokeSkill

```go
type InvokeSkill struct {
	// RequiresMaterializer binds pending-publication instructions to a session
	// with durable publication enabled. Older sessions must not silently accept
	// instructions promising a capability they did not record.
	RequiresMaterializer bool        `json:"requires_materializer,omitempty"`
	Skill                SkillLoaded `json:"skill"`
	// Args is what the user passed the skill, which the reviewer sees
	// separately. Text mixes it with the skill's own instructions.
	Args string `json:"args,omitempty"`
	// Commands are the skill's "!`command`" lines that ran as it was
	// invoked, in order; Text holds their output where each stood.
	Commands []string `json:"commands,omitempty"`
	// Files are the files and MCP resources the invocation names with @,
	// attached as a user message's are and bounded as theirs.
	Files []Attachment `json:"files,omitempty"`
	// Text is what the model receives as the user's message: the skill's
	// framed instructions and the user's arguments.
	Text string `json:"text"`
}
```

InvokeSkill is a skill the user invoked by name, as /name in the CLI. The host resolves it before sending, as SetModel resolves a model: the load and the rendered instructions are recorded, and replay reads no skill. It starts a run, or joins the next, like a user message, and the skill is active for that run.


## Kind

```go
type Kind string
```

Kind names the type of an event's payload.

```go
const (
	KindFileRestoreRequested   Kind = "file_restore_requested"
	KindFileRestoreApplied     Kind = "file_restore_applied"
	KindFileRestoreFinished    Kind = "file_restore_finished"
	KindRewindRequested        Kind = "rewind_requested"
	KindRewindFinished         Kind = "rewind_finished"
	KindSessionForked          Kind = "session_forked"
	KindFileVersionsSaved      Kind = "file_versions_saved"
	KindFileVersionsDropped    Kind = "file_versions_dropped"
	KindTimerSet               Kind = "timer_set"
	KindTimerFired             Kind = "timer_fired"
	KindConfigChanged          Kind = "config_changed"
	KindSessionStarted         Kind = "session_started"
	KindCommandAccepted        Kind = "command_accepted"
	KindEffectStarted          Kind = "effect_started"
	KindEffectFinished         Kind = "effect_finished"
	KindEffectCancelled        Kind = "effect_cancelled"
	KindAttemptEnded           Kind = "attempt_ended"
	KindEffectReconciled       Kind = "effect_reconciled"
	KindChildStarted           Kind = "child_started"
	KindChildFinished          Kind = "child_finished"
	KindChildContinued         Kind = "child_continued"
	KindFileObserved           Kind = "file_observed"
	KindCwdChanged             Kind = "cwd_changed"
	KindWorkspaceMovePrepared  Kind = "workspace_move_prepared"
	KindWorkspaceMoveCommitted Kind = "workspace_move_committed"
	KindWorkspaceMoveHandedOff Kind = "workspace_move_handed_off"
	KindWarning                Kind = "warning"
	KindRunStarted             Kind = "run_started"
	KindRunFinished            Kind = "run_finished"
	// Observations of the session and its work.
	KindInstructionsLoaded              Kind = "instructions_loaded"
	KindTodosUpdated                    Kind = "todos_updated"
	KindMemoryLoaded                    Kind = "memory_loaded"
	KindSkillLoaded                     Kind = "skill_loaded"
	KindSkillsIndexed                   Kind = "skills_indexed"
	KindMaterializeRequested            Kind = "materialize_requested"
	KindSkillMaterialized               Kind = "skill_materialized"
	KindMaterializationReleaseRequested Kind = "materialization_release_requested"
	KindMaterializationReleased         Kind = "materialization_released"
	KindProcessStarted                  Kind = "process_started"
	KindWakeWithdrawn                   Kind = "wake_withdrawn"
	KindProcessEnded                    Kind = "process_ended"
	KindFileChanged                     Kind = "file_changed"
	KindWorkspaceFingerprinted          Kind = "workspace_fingerprinted"
	KindWorkspaceMoved                  Kind = "workspace_moved"
	KindTurnDiff                        Kind = "turn_diff"
	KindWorkspaceBaseline               Kind = "workspace_baseline"
	KindSuspended                       Kind = "suspended"
	KindResumed                         Kind = "resumed"
	KindSteerOutcome                    Kind = "steer_outcome"
	KindSteerWithdrawn                  Kind = "steer_withdrawn"
	KindSteersTaken                     Kind = "steers_taken"
	KindBackgroundRequested             Kind = "background_requested"
	KindEvidenceRecorded                Kind = "evidence_recorded"
	KindRequirementDeclared             Kind = "requirement_declared"
	KindRequirementRetired              Kind = "requirement_retired"
	KindReportRecorded                  Kind = "report_recorded"
	KindCompletionChecked               Kind = "completion_checked"
	KindContinuationUsed                Kind = "continuation_used"
	KindShortcutFlagged                 Kind = "shortcut_flagged"
	KindAttemptRecorded                 Kind = "attempt_recorded"

	KindPermissionDecided Kind = "permission_decided"
	KindPolicyDecided     Kind = "policy_decided"
	KindPolicyAmended     Kind = "policy_amended"
	KindHookDecided       Kind = "hook_decided"
	KindActionClassified  Kind = "action_classified"
)
```

The payload kinds zelk records.

```go
const (
	KindStructuredOutputAccepted    Kind = "structured_output_accepted"
	KindStructuredOutputRejected    Kind = "structured_output_rejected"
	KindStructuredOutputInvalidated Kind = "structured_output_invalidated"
	KindRecordEmitted               Kind = "record_emitted"
)
```

The structured output kinds.

```go
const KindExecutionTraced Kind = "execution_traced"
```

KindExecutionTraced is the kind of [ExecutionTraced](/reference/go/event/#executiontraced).

```go
const KindQuotaExceeded Kind = "quota_exceeded"
```

KindQuotaExceeded is the kind of [QuotaExceeded](/reference/go/event/#quotaexceeded).


## LedgerReport

```go
type LedgerReport struct {
	// Measured is what providers reported spending.
	Measured Tokens `json:"measured,omitzero"`
	// Unknown is the reservations charged for attempts whose usage is
	// unknown; it may overstate what they spent.
	Unknown Tokens `json:"unknown,omitzero"`
	// Reserved is the reservations of attempts still open.
	Reserved Tokens `json:"reserved,omitzero"`
	// Allocated is the child allocations not yet returned.
	Allocated Tokens `json:"allocated,omitzero"`
	// Estimated is the best guess at what the Unknown part actually spent;
	// it isn't added in.
	Estimated Tokens `json:"estimated,omitzero"`
}
```

LedgerReport is a run's commitment in four parts that add up to what enforcement counts, and an estimate of what the unknown part spent (docs/design/durability.md, B6).


### LedgerReport.Committed

```go
func (r LedgerReport) Committed() Tokens
```

Committed returns the sum of the four parts.


## LeftCheck

```go
type LeftCheck struct {
	Check  string `json:"check"`
	Reason string `json:"reason"`
}
```

LeftCheck is a failing check a report leaves as it was, such as one that failed for a reason the task doesn't touch, and why.


## Limit

```go
type Limit struct {
	Max  int64 `json:"max"`
	Soft bool  `json:"soft,omitempty"`
}
```

Limit is one dimension's limit: hard, so a reservation that would pass it isn't made, or soft, so passing it gets a warning and one wrap-up turn.


## LineRange

```go
type LineRange struct {
	Start int `json:"start"`
	End   int `json:"end"`
}
```

LineRange is an inclusive range of 1-based line numbers.


## MCPServer

```go
type MCPServer struct {
	// State and Error describe an unavailable server. An absent state denotes connected.
	State string `json:"state,omitempty"`
	Error string `json:"error,omitempty"`
	// Name is the host's name for it, which namespaces its tools.
	Name string `json:"name"`
	// Protocol is the MCP protocol version agreed.
	Protocol      string `json:"protocol"`
	ServerName    string `json:"server_name,omitempty"`
	ServerVersion string `json:"server_version,omitempty"`
	// Instructions are the server's own instructions for using it, bounded
	// to MaxMCPInstructions bytes; the model sees them as the server's
	// words, not the host's.
	Instructions string `json:"instructions,omitempty"`
}
```

MCPServer is an MCP server as a session recorded it.


## MaterializationReleaseRequested

```go
type MaterializationReleaseRequested struct {
	Identity string `json:"identity"`
}
```

MaterializationReleaseRequested selects a recorded artifact for idle cleanup.


### MaterializationReleaseRequested.Kind

```go
func (MaterializationReleaseRequested) Kind() Kind
```

Kind returns KindMaterializationReleaseRequested.


## MaterializationReleased

```go
type MaterializationReleased struct {
	EffectID string `json:"effect_id"`
	Identity string `json:"identity"`
}
```

MaterializationReleased records successful removal before the atomic finish.


### MaterializationReleased.Kind

```go
func (MaterializationReleased) Kind() Kind
```

Kind returns KindMaterializationReleased.


## Materialize

```go
type Materialize struct {
	Skill    string      `json:"skill"`
	Revision string      `json:"revision"`
	Key      string      `json:"key"`
	Files    []SkillFile `json:"files"`
}
```

Materialize is the exact recorded manifest one filesystem effect publishes. Key is a stable session-local publication key, preserved across resume.


### Materialize.Identity

```go
func (m Materialize) Identity(session string) (string, error)
```

Identity validates the recorded manifest and derives its canonical publication identity for session. It hashes ownership, Key, paths, sizes and content digests, independently of file order. Callers must separately verify bytes against these digests before publishing. Skill and Revision identify the load; Key binds that load's publication across effects and recovery.

**Example**

```go
data := []byte("recorded")
manifest := event.Materialize{Key: "effect", Files: []event.SkillFile{{Path: "asset", Digest: blob.Digest(data), Size: int64(len(data))}}}
identity, err := manifest.Identity("s")
fmt.Println(identity, err)
// Output: sha256:b50f5eb56e79cce142b89de0868254a3bc5e2f79577edaeca4c0a7316f71f776 <nil>
```

Output:

```text
sha256:b50f5eb56e79cce142b89de0868254a3bc5e2f79577edaeca4c0a7316f71f776 <nil>
```


## MaterializeRequested

```go
type MaterializeRequested struct {
	Skill    string `json:"skill"`
	Revision string `json:"revision"`
}
```

MaterializeRequested asks the reducer to publish an already recorded bundle. It never authorizes loading the current skill source.


### MaterializeRequested.Kind

```go
func (MaterializeRequested) Kind() Kind
```

Kind returns KindMaterializeRequested.


## MemoryLoaded

```go
type MemoryLoaded struct {
	View string `json:"view"`
	// Outside marks a change made outside this session, by another session
	// or by a person; the model is told of it before its next call.
	Outside bool `json:"outside,omitempty"`
	// Off marks memory turned off for the session, with an empty View:
	// the model is told to disregard the notes it was shown.
	Off bool `json:"off,omitempty"`
}
```

MemoryLoaded is the memory view as the store held it (docs/design/memory.md). A memory tool records it after it changes the store, and the host at a run's start when the store's view differs from the session's. The view reaches the request context at the next compaction, so the cached prompt prefix holds until then.


### MemoryLoaded.Kind

```go
func (MemoryLoaded) Kind() Kind
```

Kind returns [KindMemoryLoaded](/reference/go/event/).


## ModelErrorKind

```go
type ModelErrorKind string
```

ModelErrorKind classifies a failed model call: the loop acts on a context overflow, and a host explains the others.

```go
const (
	// ErrorContextOverflow is a prompt the model refused as too long.
	ErrorContextOverflow ModelErrorKind = "context_overflow"
	// ErrorTransient is a server error or dropped connection that retries
	// didn't outlast.
	ErrorTransient ModelErrorKind = "transient"
	// ErrorRateLimited is a provider that kept asking to slow down.
	ErrorRateLimited ModelErrorKind = "rate_limited"
	// ErrorInvalidRequest is a request the provider rejected.
	ErrorInvalidRequest ModelErrorKind = "invalid_request"
	// ErrorAuth is missing or rejected credentials.
	ErrorAuth ModelErrorKind = "auth"
	// ErrorQuota is an account out of credit or past a usage limit.
	ErrorQuota ModelErrorKind = "quota"
	// ErrorUnsupported is a capability or route the provider doesn't offer.
	ErrorUnsupported ModelErrorKind = "unsupported"
	// ErrorMalformed is a response that broke the provider's protocol on
	// every attempt the retry policy allowed.
	ErrorMalformed ModelErrorKind = "malformed"
)
```

The classes of failed model call, as provider.ErrorKind classifies them.


## ModelSettings

```go
type ModelSettings struct {
	MaxOutputTokens int64 `json:"max_output_tokens"`
	// Reasoning sets how hard the model reasons; nil leaves it to the
	// provider and model, some of which always reason.
	Reasoning *ReasoningSettings `json:"reasoning,omitempty"`
}
```

ModelSettings are the request settings the session uses.


## NativeOutcome

```go
type NativeOutcome string
```

NativeOutcome records whether the native request of a compaction could reach the provider.

```go
const (
	// NativeSkipped means a native compaction sent no native request: the
	// provider has no native compaction.
	NativeSkipped NativeOutcome = "skipped"
	// NativeNotDispatched means the native request provably did not reach the provider.
	NativeNotDispatched NativeOutcome = "not_dispatched"
	// NativeSent means the native request may have reached the provider.
	NativeSent NativeOutcome = "sent"
)
```


## OccurrenceExit

```go
type OccurrenceExit struct {
	// Code is the exit status, or -1 for a command a signal ended.
	Code   int    `json:"code"`
	Signal string `json:"signal,omitempty"`
	// Killed says the command was stopped: by its stop_after, its hourly
	// cap, or a kill someone asked for.
	Killed bool `json:"killed,omitempty"`
}
```

OccurrenceExit is the exit a watch observed. Admitting the final occurrence records it as the process's end, so a later stop or inspection reports it rather than inventing one.


## OccurrencePayload

```go
type OccurrencePayload struct {
	// End ends the source atomically with admission of this final occurrence.
	End bool `json:"end,omitempty"`
	// Quiet ends observation without a notice or model run. It requires End.
	Quiet bool `json:"quiet,omitempty"`

	// Text is the fixed UTF-8 notice, bounded by MaxOccurrenceBytes.
	Text string `json:"text"`
	// Folded counts occurrences replaced by this payload.
	Folded uint64 `json:"folded,omitempty"`
	// Missed counts observations the observer could not record.
	Missed uint64 `json:"missed,omitempty"`
	// Through is a monitor's output cursor after this payload's lines, where
	// a watch resumes after a restart; zero for other sources.
	Through int64 `json:"through,omitempty"`
	// Exit is how a monitor's command ended, on the final occurrence of a
	// watch that saw it end. It is nil when no one saw the end, as for a
	// command that didn't survive a restart, and on every other occurrence.
	Exit *OccurrenceExit `json:"exit,omitempty"`
}
```

OccurrencePayload is fixed before admission. Folded counts replaced occurrences; Missed counts observations the observer could not record.


### OccurrencePayload.Validate

```go
func (p OccurrencePayload) Validate() error
```

Validate checks the payload's text and representable combined gap count.


## Option

```go
type Option struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}
```

Option is one choice of a question.


## Origin

```go
type Origin string
```

Origin is where a tool comes from.

```go
const (
	OriginBuiltin Origin = "builtin"
	OriginMCP     Origin = "mcp"
	OriginClient  Origin = "client"
	// OriginHarness tools are control requests the loop handles itself,
	// such as AskUserQuestion; no driver tool runs them.
	OriginHarness Origin = "harness"
)
```

The tool origins.


## Outcome

```go
type Outcome string
```

Outcome is how a finished effect ended: success or one of the error classes.

```go
const (
	// OutcomeDone is success.
	OutcomeDone Outcome = "done"
	// OutcomeFailed is a definite failure; the error goes to the model.
	OutcomeFailed Outcome = "failed"
	// OutcomeUnknown means the effect may have acted. It is never retried
	// automatically.
	OutcomeUnknown Outcome = "unknown"
	// OutcomeNotDispatched means the effect provably did nothing.
	OutcomeNotDispatched Outcome = "not_dispatched"
)
```

The effect outcomes.


## Output

```go
type Output struct {
	// Schema is the output's JSON Schema, in the canonical subset; it is
	// the StructuredOutput tool's input schema.
	Schema json.RawMessage `json:"schema"`
	// Records lets the model emit many values, one per call, instead of
	// one at the end.
	Records bool `json:"records,omitempty"`
	// Attempts is how many failed attempts to deliver the output, rejected
	// calls and endings without one, the run allows before it ends with
	// outcome invalid_structured_output.
	Attempts int `json:"attempts"`
	// Validators name the host's semantic validators, in the order they
	// run after the schema check.
	Validators []string `json:"validators,omitempty"`
}
```

Output is a session's structured output contract: what the StructuredOutput tool accepts and how often it may be called wrong. The schema is the canonical one the model sees, recorded so a resumed session validates against the schema it started with.


## OutputError

```go
type OutputError struct {
	Path      string `json:"path,omitempty"`
	Validator string `json:"validator,omitempty"`
	Message   string `json:"message"`
}
```

OutputError is one problem with a structured output value: where it is, as a JSON Pointer ("" for the whole value), and what is wrong. A validator's error has the validator's name instead of a path.


## Payload

```go
type Payload interface {
	Kind() Kind
}
```

Payload is the typed body of an event. Each payload type reports its own kind.


## PermissionDecided

```go
type PermissionDecided struct {
	CallID string `json:"call_id"`
	Tool   string `json:"tool"`
	Digest string `json:"digest"`
	// Verdict is PermissionDeny, PermissionAsk or PermissionClassify;
	// Step the algorithm's step.
	Verdict PermissionVerdict `json:"verdict"`
	Step    int               `json:"step"`
	Reason  string            `json:"reason"`
	Rule    string            `json:"rule,omitempty"`
}
```

PermissionDecided records a decision of the permission algorithm about a tool call that didn't simply run, for audit and evaluation oracles. It is a derived record: the fold computes it and checks the log holds it.


### PermissionDecided.Kind

```go
func (PermissionDecided) Kind() Kind
```

Kind returns [KindPermissionDecided](/reference/go/event/).


## PermissionMode

```go
type PermissionMode string
```

PermissionMode is a permission mode as the log records it; package permission defines what each allows.

```go
const (
	ModePlan        PermissionMode = "plan"
	ModeDefault     PermissionMode = "default"
	ModeAcceptEdits PermissionMode = "accept-edits"
	ModeAuto        PermissionMode = "auto"
	ModeDontAsk     PermissionMode = "dont-ask"
	ModeBypass      PermissionMode = "bypass"
)
```

The permission modes.


## PermissionVerdict

```go
type PermissionVerdict string
```

PermissionVerdict is what the permission decision algorithm decided.

```go
const (
	PermissionAllow    PermissionVerdict = "allow"
	PermissionDeny     PermissionVerdict = "deny"
	PermissionAsk      PermissionVerdict = "ask"
	PermissionClassify PermissionVerdict = "classify"
)
```

The permission verdicts. A plain allow isn't recorded.


## PlanAnswer

```go
type PlanAnswer struct {
	// Approved approves the plan; Mode is the permission mode it switches
	// to, one the session authorizes other than plan.
	Approved bool           `json:"approved,omitempty"`
	Mode     PermissionMode `json:"mode,omitempty"`
	// Message is the user's note to the model, such as why the plan was
	// rejected.
	Message string `json:"message,omitempty"`
}
```

PlanAnswer answers an InputPlanExit request.


## Policy

```go
type Policy struct {
	// Mode is the permission mode, such as ModePlan or ModeBypass.
	Mode PermissionMode `json:"mode"`
	// Modes are the modes a SetPermissionMode command may select,
	// including Mode.
	Modes []PermissionMode `json:"modes"`
	// Tools is the ceiling on the tools that may run, by name; nil allows
	// every recorded tool.
	Tools []string `json:"tools,omitempty"`
	// Rules are the deny, human-only, ask and allow rules, in their
	// written form, such as "Bash(npm test *)".
	Rules *Rules `json:"rules,omitempty"`
	// Protected are the host's own protected path patterns.
	Protected []string `json:"protected,omitempty"`
	// NoSkillGrants says no skill's allowed-tools pre-approve calls, as
	// under a managed policy that keeps only its own allow rules.
	NoSkillGrants bool `json:"no_skill_grants,omitempty"`
}
```

Policy is a session's permission policy as recorded. The permission package defines the modes; the log keeps their names.


## PolicyAmended

```go
type PolicyAmended struct {
	// Approval is the approval whose answer granted the rules.
	Approval string   `json:"approval"`
	Allow    []string `json:"allow"`
	// Revision is the policy revision from this record on.
	Revision uint64 `json:"revision"`
}
```

PolicyAmended records a session grant: allow rules a human added for the rest of the session. It is appended atomically with the approval that granted it, and raises the policy revision.


### PolicyAmended.Kind

```go
func (PolicyAmended) Kind() Kind
```

Kind returns [KindPolicyAmended](/reference/go/event/).


## PolicyDecided

```go
type PolicyDecided struct {
	// ShellSummary and Observe preserve the PowerShell facts used for review.
	ShellSummary string `json:"shell_summary,omitempty"`
	Observe      bool   `json:"observe,omitempty"`
	// Prior is the verdict under the mode last shown to the model.
	Prior   PermissionVerdict `json:"prior,omitempty"`
	ID      string            `json:"id"`
	CallID  string            `json:"call_id"`
	Verdict PermissionVerdict `json:"verdict"`
	Step    int               `json:"step"`
	Reason  string            `json:"reason,omitempty"`
	Rule    string            `json:"rule,omitempty"`
	// HumanOnly says only a human may approve; Defer that a hook asked to
	// suspend for the decision.
	HumanOnly bool `json:"human_only,omitempty"`
	Defer     bool `json:"defer,omitempty"`
	// Suggestions are the allow rules a human may grant instead of
	// approving once.
	Suggestions []string `json:"suggestions,omitempty"`
	// Block types a denial. Logs from before it was recorded replay a
	// denial as RefusalOther.
	Block RefusalKind `json:"block,omitempty"`
}
```

PolicyDecided records what the permission policy decided for a tool call, plain allows included, each time the reducer consults it. A stored log replays with the decisions it recorded, whatever the policy's rules say today (docs/design/durability.md, "Recorded decisions"). PermissionDecided, which follows a decision other than an allow, records what was done about it.


### PolicyDecided.Kind

```go
func (PolicyDecided) Kind() Kind
```

Kind returns [KindPolicyDecided](/reference/go/event/).


## ProcessEnded

```go
type ProcessEnded struct {
	Handle string `json:"handle"`
	// Code is the exit status, or -1 for a process a signal ended.
	Code   int    `json:"code"`
	Signal string `json:"signal,omitempty"`
	// Lost says the process couldn't be found: it ran in an earlier
	// execution, and the environment can't find processes again.
	Lost bool `json:"lost,omitempty"`
	// Killed says the process was stopped (the model's ProcessKill, the
	// host's KillProcess, or the end of the execution that owned it), so
	// it didn't finish and no completion wake is owed for it.
	Killed bool `json:"killed,omitempty"`
}
```

ProcessEnded records that a background process ended, was killed, or was found gone.


### ProcessEnded.Kind

```go
func (ProcessEnded) Kind() Kind
```

Kind returns [KindProcessEnded](/reference/go/event/).


## ProcessStarted

```go
type ProcessStarted struct {
	// NotifyOnCompletion records explicit authorization for a deduplicated parent wakeup.
	NotifyOnCompletion bool `json:"notify_on_completion,omitempty"`
	// Lifetime is execution (also the empty value), conversation or persistent.
	Lifetime string `json:"lifetime,omitempty"`
	Handle   string `json:"handle"`
	// CallID is the tool call that started the process.
	CallID string `json:"call_id,omitempty"`
	// ProcID is the environment's ID for the process, with its
	// generation, for a process reconciler to find it again.
	ProcID  string `json:"proc_id"`
	Command string `json:"command"`
	Cwd     string `json:"cwd"`
	// Shell names the shell tool whose dialect Command is in: "Bash" or
	// "PowerShell"; empty for a process no shell started.
	Shell string `json:"shell,omitempty"`
	// Check says the process is a check Verify runs in the background;
	// Command is the check's command.
	Check *CheckRun `json:"check,omitempty"`
	// Report and Deadline are set for a foreground Bash command the user
	// moved to the background: the mark of the report its
	// wrapper writes as it ends, which readers cut from its output, and
	// when it is killed, as it would have been in the foreground.
	Report   string    `json:"report,omitempty"`
	Deadline time.Time `json:"deadline,omitzero"`
}
```

ProcessStarted records a background process a tool started, under the handle the model uses for it.


### ProcessStarted.Kind

```go
func (ProcessStarted) Kind() Kind
```

Kind returns [KindProcessStarted](/reference/go/event/).


## Question

```go
type Question struct {
	Header   string `json:"header,omitempty"`
	Question string `json:"question"`
	// Options are 2 to 4 choices; the user may also answer in their own
	// words.
	Options     []Option `json:"options"`
	MultiSelect bool     `json:"multi_select,omitempty"`
	// Category is "authorization", "correctness" or "preference"; it
	// decides what happens when no human can answer.
	Category string `json:"category"`
}
```

Question is one structured question for the user.


## QuestionsAnswer

```go
type QuestionsAnswer struct {
	// Answers holds, for each question in order, the labels of the
	// options chosen or the user's own text.
	Answers [][]string `json:"answers"`
	// Message is the user's note to the model.
	Message string `json:"message,omitempty"`
}
```

QuestionsAnswer answers an InputQuestion request.


## Quota

```go
type Quota struct {
	// LogBytes bounds the log's encoded size.
	LogBytes int64 `json:"log_bytes,omitempty"`
	// BlobBytes bounds the bytes of the blobs the log references: full
	// tool outputs, raw payloads held aside, skill files. A blob
	// referenced twice counts twice.
	BlobBytes int64 `json:"blob_bytes,omitempty"`
	// HookOutputBytes bounds what hooks returned: their reasons, context,
	// notes and replacements.
	HookOutputBytes int64 `json:"hook_output_bytes,omitempty"`
	// SkillBytes bounds the bundle bytes of the skills loaded.
	SkillBytes int64 `json:"skill_bytes,omitempty"`
	// MaterializedBytes bounds newly owned published file contents. Each
	// canonical publication identity counts once; resume verification is free.
	MaterializedBytes int64 `json:"materialized_bytes,omitempty"`
	// Processes bounds the background processes started.
	Processes int64 `json:"processes,omitempty"`
}
```

Quota is a set of limits, each what may be used: going over one ends the run. Zero leaves a resource unlimited.


## QuotaExceeded

```go
type QuotaExceeded struct {
	// Proposed is file content refused before publication, not consumed bytes.
	// It is valid only for materialized_bytes.
	Proposed int64  `json:"proposed,omitempty"`
	Scope    string `json:"scope"`
	Resource string `json:"resource"`
	Limit    int64  `json:"limit"`
	Used     int64  `json:"used"`
}
```

QuotaExceeded records that the driver found a quota gone over, Used above Limit (or Used + Proposed above Limit), before starting more work: the run ends with outcome quota\_exceeded once what was already running is recorded. Used is what the driver measured.


### QuotaExceeded.Kind

```go
func (QuotaExceeded) Kind() Kind
```

Kind returns [KindQuotaExceeded](/reference/go/event/).


## Quotas

```go
type Quotas struct {
	// Session bounds the whole session: everything its log records.
	Session Quota `json:"session,omitzero"`
	// Execution bounds what one execution, one driver's Run, adds.
	Execution Quota `json:"execution,omitzero"`
}
```

Quotas bound what a session, and one execution of it, may consume. They are recorded with the session, so every driver that takes it up enforces the same limits.


## ReadOnlyWhen

```go
type ReadOnlyWhen struct {
	Field  string   `json:"field"`
	Values []string `json:"values"`
	Unless []string `json:"unless,omitempty"`
}
```

ReadOnlyWhen says a call is read-only when its input's string field Field has one of Values, and none of the fields Unless is set: Task's isolation, which makes a worktree, so a call with it never is.


### ReadOnlyWhen.Equal

```go
func (w *ReadOnlyWhen) Equal(o *ReadOnlyWhen) bool
```

Equal reports whether w and o name the same calls.


### ReadOnlyWhen.Matches

```go
func (w *ReadOnlyWhen) Matches(input json.RawMessage) bool
```

Matches reports whether a call with input is read-only by w. A field the call leaves out, or sets to null, is "". A nil w, an input that isn't an object, or a field that isn't a string matches nothing.


## ReasoningSettings

```go
type ReasoningSettings struct {
	// Effort is how much reasoning the model spends per turn. Providers
	// control reasoning by effort rather than a token budget, which
	// current models reject.
	Effort Effort `json:"effort"`
}
```

ReasoningSettings configure model reasoning. One harness serves every model, so these are the same for all of them; adapters translate them to each provider's wire format.


## RecordEmitted

```go
type RecordEmitted struct {
	EffectID string          `json:"effect_id"`
	N        uint64          `json:"n"`
	Value    json.RawMessage `json:"value"`
}
```

RecordEmitted records one value of records mode. N numbers the session's records from 1, so a host reading them by N sees each exactly once.


### RecordEmitted.Kind

```go
func (RecordEmitted) Kind() Kind
```

Kind returns [KindRecordEmitted](/reference/go/event/).


## Refusal

```go
type Refusal struct {
	Tool string `json:"tool"`
	// Input is the action's input, bounded.
	Input  string `json:"input"`
	Reason string `json:"reason,omitempty"`
	// After is how many of the user's messages came before the refusal, so
	// that one sent since can be read as answering it.
	After int `json:"after,omitempty"`
}
```

Refusal is an action an auto-mode reviewer refused, as a later review is told of it.


## RefusalKind

```go
type RefusalKind string
```

RefusalKind types why a call was refused, so a reader can tell a refusal a rule would fix from one no rule can lift.

```go
const (
	// RefusalNoRule: no allow rule covers the action.
	RefusalNoRule RefusalKind = "no_rule"
	// RefusalTool: the tool isn't among those the session may use.
	RefusalTool RefusalKind = "tool"
	// RefusalDenyRule: a deny rule matches.
	RefusalDenyRule RefusalKind = "deny_rule"
	// RefusalProtected: the action touches a protected path.
	RefusalProtected RefusalKind = "protected_path"
	// RefusalHumanOnly: a human-only or ask rule needs a person.
	RefusalHumanOnly RefusalKind = "human_only"
	// RefusalOther: anything else, such as a hook's deny.
	RefusalOther RefusalKind = "other"
)
```

The refusal kinds.


## ReleaseMaterialization

```go
type ReleaseMaterialization struct {
	Identity string      `json:"identity"`
	Bundle   Materialize `json:"bundle"`
}
```

ReleaseMaterialization is an owned cleanup effect's exact recorded input.


## Report

```go
type Report struct {
	Goal         string       `json:"goal"`
	GoalRevision int          `json:"goal_revision"`
	GoalStatus   GoalStatus   `json:"goal_status"`
	Verification Verification `json:"verification"`
	// Verified are the evidence IDs of fresh passing checks.
	Verified []string `json:"verified,omitempty"`
	// Unverified names each check without fresh passing evidence, and why.
	Unverified []string `json:"unverified,omitempty"`
	// Changed lists the files built-in tools changed.
	Changed []string `json:"changed,omitempty"`
	// Flags are the shortcut flags raised during the run.
	Flags []string `json:"flags,omitempty"`
	// UnsupportedClaims are claims in the final message that no evidence
	// supports.
	UnsupportedClaims []string `json:"unsupported_claims,omitempty"`
	// Forced says the report was synthesized from the log, without the
	// model, for a run that didn't end normally.
	Forced bool `json:"forced,omitempty"`
	// Claimed is the goal status the model reported, if it did; Summary,
	// BlockedBy and Open are what it said with it.
	Claimed   GoalStatus `json:"claimed,omitempty"`
	Summary   string     `json:"summary,omitempty"`
	BlockedBy string     `json:"blocked_by,omitempty"`
	Open      []string   `json:"open,omitempty"`
	// Left are the failing checks the model reported leaving as they
	// were, each with its reason; a met report may name them.
	Left []LeftCheck `json:"left,omitempty"`
	// Requirements are the task's requirements as the model stated them,
	// each with how it confirmed it. A met report with one not checked is
	// recorded as partial.
	Requirements []RequirementCheck `json:"requirements,omitempty"`
	// Replied says the run ended on the model's reply to a completion
	// check that sent it back, given at once, in a session that requires
	// no report: there a reply is how the model says why the goal can't or
	// needn't be met, such as a check left failing for a reason outside
	// the task.
	Replied bool `json:"replied,omitempty"`
	// Records is how many records the run emitted, in records mode.
	Records int `json:"records,omitempty"`
	// OutputErrors are the problems with the last structured output the
	// run rejected, for a run that ended invalid_structured_output.
	OutputErrors []OutputError `json:"output_errors,omitempty"`
}
```

Report is a run's honest account of itself.


## ReportRecorded

```go
type ReportRecorded struct {
	// Run names the run the report ends, as RunFinished does.
	Run    uint64 `json:"run,omitempty"`
	Report Report `json:"report"`
}
```

ReportRecorded records a run's report with its ending.


### ReportRecorded.Kind

```go
func (ReportRecorded) Kind() Kind
```

Kind returns [KindReportRecorded](/reference/go/event/).


## Requirement

```go
type Requirement struct {
	ID           string           `json:"id"`
	Revision     uint64           `json:"revision"`
	Scope        RequirementScope `json:"scope"`
	WorkID       string           `json:"work_id,omitempty"`
	WorkRevision uint64           `json:"work_revision,omitempty"`
	Name         string           `json:"name"`
	Command      string           `json:"command"`
}
```

Requirement identifies one revision of a standing check. Name is a display label, not identity. Host requirements have no work owner.


### Requirement.Validate

```go
func (r Requirement) Validate() error
```

Validate checks bounded structural metadata. It proves neither ownership nor authorization; the reducer must validate the causal command or running effect.


## RequirementCause

```go
type RequirementCause struct {
	CommandID     string `json:"command_id,omitempty"`
	EffectID      string `json:"effect_id,omitempty"`
	InstructionID string `json:"instruction_id,omitempty"`
}
```

RequirementCause attributes a mutation to exactly one accepted host command or running model tool effect. InstructionID names the originating instruction; these labels never grant authority without reducer validation.


### RequirementCause.Validate

```go
func (c RequirementCause) Validate() error
```

Validate checks causal identifier shape, not the referenced log entries.


## RequirementCheck

```go
type RequirementCheck struct {
	Requirement string       `json:"requirement"`
	Confirmed   Confirmation `json:"confirmed"`
	How         string       `json:"how"`
}
```

RequirementCheck is a requirement of the task, as a report states it, how the model confirmed it, and with what: the check it ran, what it read, or why it couldn't check.


## RequirementDeclared

```go
type RequirementDeclared struct {
	Requirement      Requirement      `json:"requirement"`
	ExpectedRevision uint64           `json:"expected_revision"`
	Cause            RequirementCause `json:"cause"`
}
```

RequirementDeclared creates or revises a requirement using compare-and-swap. ExpectedRevision is zero for creation; the declared revision is exactly one greater.


### RequirementDeclared.Kind

```go
func (RequirementDeclared) Kind() Kind
```

Kind returns KindRequirementDeclared.


### RequirementDeclared.Validate

```go
func (p RequirementDeclared) Validate() error
```

Validate checks the declaration's shape. Registry state supplies the expected revision, ownership, instruction provenance and permission checks at admission.

**Example**

```go
p := event.RequirementDeclared{
	Requirement: event.Requirement{ID: "acceptance-1", Revision: 1, Scope: event.RequirementWork,
		WorkID: "work-1", WorkRevision: 1, Name: "absent", Command: "test ! -e xx.md"},
	Cause: event.RequirementCause{EffectID: "parent/4/0", InstructionID: "delete-request"},
}
// Structural validation does not authorize the effect or its instruction.
fmt.Println(p.Kind(), p.Validate())
retired := event.RequirementRetired{RequirementID: "acceptance-1", ExpectedRevision: 1,
	Reason: "The user replaced this requirement.", Cause: event.RequirementCause{CommandID: "retire-1", InstructionID: "replacement-request"}}
fmt.Println(retired.Kind(), retired.Validate())
// Output:
// requirement_declared <nil>
// requirement_retired <nil>
```

Output:

```text
requirement_declared <nil>
requirement_retired <nil>
```


## RequirementRetired

```go
type RequirementRetired struct {
	RequirementID    string           `json:"requirement_id"`
	ExpectedRevision uint64           `json:"expected_revision"`
	Reason           string           `json:"reason"`
	Cause            RequirementCause `json:"cause"`
}
```

RequirementRetired resolves or supersedes an exact requirement revision. Retirement retains the declaration and evidence history; it is not deletion.


### RequirementRetired.Kind

```go
func (RequirementRetired) Kind() Kind
```

Kind returns KindRequirementRetired.


### RequirementRetired.Validate

```go
func (p RequirementRetired) Validate() error
```

Validate requires an exact target and an attributed, bounded reason. The registry must additionally prevent model effects from retiring host checks.


## RequirementScope

```go
type RequirementScope string
```

RequirementScope describes who owns a standing verification requirement.

```go
const (
	RequirementHost RequirementScope = "host"
	RequirementWork RequirementScope = "work"
)
```

The requirement scopes. Observations have no requirement scope.


## Reservation

```go
type Reservation struct {
	// AllocationID is "<effect_id>#<attempt>", unique in the session.
	AllocationID string `json:"allocation_id"`
	Tokens
}
```

Reservation is what one attempt of a model call may spend at most, reserved before it is dispatched (docs/design/durability.md, B2). A zero dimension is unknown, such as the output of a provider that sends no output cap; a hard budget refuses models whose limits are unknown.


## Resumed

```go
type Resumed struct{}
```

Resumed records that an execution took up a suspended session again.


### Resumed.Kind

```go
func (Resumed) Kind() Kind
```

Kind returns [KindResumed](/reference/go/event/).


## RetryDenied

```go
type RetryDenied struct {
	ActionDigest string `json:"action_digest"`
	// Reason is optional trusted context supplied by the user or host.
	Reason string `json:"reason,omitempty"`
}
```

RetryDenied asks for one more review of the exact denied action. It never authorizes execution; current policy and classifier limits still apply.


## RewindFinished

```go
type RewindFinished struct {
	ID    string `json:"id"`
	Error string `json:"error,omitempty"`
}
```

RewindFinished closes a rewind. Empty Error means the conversation was rewound; otherwise it is unchanged, and any files the restore applied stay applied.


### RewindFinished.Kind

```go
func (RewindFinished) Kind() Kind
```

Kind returns KindRewindFinished.


## RewindRequested

```go
type RewindRequested struct {
	ID           string          `json:"id"`
	Point        uint64          `json:"point"`
	Files        bool            `json:"files,omitempty"`
	Conversation json.RawMessage `json:"conversation"`
}
```

RewindRequested records a confirmed conversation rewind before anything changes (docs/design/rewind.md). Point is the sequence number of the user prompt the conversation goes back to, before it. Conversation is the conversation part of the session's state at that point, as the loop encodes it, so replay never reads the events before this one. With Files, a file restore to the point's checkpointed files follows, and the rewind applies only if it finishes done.


### RewindRequested.Kind

```go
func (RewindRequested) Kind() Kind
```

Kind returns KindRewindRequested.


## Rules

```go
type Rules struct {
	Deny  []string `json:"deny,omitempty"`
	Human []string `json:"human,omitempty"`
	Ask   []string `json:"ask,omitempty"`
	Allow []string `json:"allow,omitempty"`
}
```

Rules are a policy's rules as recorded, by what a match does.


## RunFinished

```go
type RunFinished struct {
	// Run names the run: the sequence number of the event that began it,
	// as its RunStarted recorded.
	Run uint64 `json:"run,omitempty"`
	// Refused records an adapter-bound reservation declined before the first
	// attempt. It is zero for every other run ending.
	Refused Reservation `json:"refused,omitzero"`
	Outcome RunOutcome  `json:"outcome"`
	// Usage is the usage providers measured, in detail.
	Usage Usage `json:"usage"`
	// Ledger is the run's commitment in four parts (docs/design/durability.md,
	// B6).
	Ledger LedgerReport `json:"ledger,omitzero"`
	Turns  int          `json:"turns"`
	// StopReason is the provider's final stop reason, if any.
	StopReason string `json:"stop_reason,omitempty"`
	// Error describes an error outcome.
	Error string `json:"error,omitempty"`
	// ErrorKind is the class of the failed model call that ended an error
	// run, so a host can say which recovery fits. It is empty for other
	// endings.
	ErrorKind ModelErrorKind `json:"error_kind,omitempty"`
}
```

RunFinished ends a run with its outcome and total usage.


### RunFinished.Kind

```go
func (RunFinished) Kind() Kind
```

Kind returns [KindRunFinished](/reference/go/event/).


## RunHook

```go
type RunHook struct {
	Hook  string    `json:"hook"`
	Input HookInput `json:"input"`
}
```

RunHook invokes a gate hook with its input.


## RunOutcome

```go
type RunOutcome string
```

RunOutcome is how a run ended.

```go
const (
	RunSuccess    RunOutcome = "success"
	RunIncomplete RunOutcome = "incomplete"
	// RunUnverified: the work is done as far as the model can tell, but a
	// requirement remains it had no way to check: its report is partial,
	// with nothing open but requirements not_checked, each with why. It
	// isn't success, which needs every requirement confirmed, and isn't
	// incomplete, which leaves work undone.
	RunUnverified  RunOutcome = "unverified"
	RunMaxTurns    RunOutcome = "max_turns"
	RunMaxBudget   RunOutcome = "max_budget"
	RunRefused     RunOutcome = "refused"
	RunInterrupted RunOutcome = "interrupted"
	RunError       RunOutcome = "error"
	// RunBlocked: the run needs an answer only a human can give, and none
	// is available.
	RunBlocked RunOutcome = "blocked"
	// RunInvalidOutput: the model didn't deliver a structured output that
	// passed within the attempts allowed.
	RunInvalidOutput RunOutcome = "invalid_structured_output"
	// RunSuspended: the run waits for human input with no driver running
	// it. A host sees it in a result; the log records Suspended instead,
	// since the run goes on once answered.
	RunSuspended RunOutcome = "suspended"
)
```

The run outcomes.

```go
const RunQuotaExceeded RunOutcome = "quota_exceeded"
```

RunQuotaExceeded is the outcome of a run that went over a quota of the session or the execution. The run ends without a model call, its report synthesized from the log.


## RunStarted

```go
type RunStarted struct {
	// Interaction is fixed for the run; InteractionSession, the zero value,
	// leaves input to the session's recorded configuration.
	Interaction InteractionMode `json:"interaction,omitempty"`
	// Run is the sequence number of the event that began the run. The run's
	// RunFinished, ReportRecorded and decision records carry the same ID.
	Run uint64 `json:"run"`
}
```

RunStarted records that a run began (docs/design/durability.md, X1). The reducer owes it right after the event that began the run, so a reader learns a run's ID before any of its work.


### RunStarted.Kind

```go
func (RunStarted) Kind() Kind
```

Kind returns [KindRunStarted](/reference/go/event/).


## RunTool

```go
type RunTool struct {
	CallID string          `json:"call_id"`
	Tool   string          `json:"tool"`
	Input  json.RawMessage `json:"input"`
}
```

RunTool runs one tool call.


## Schedule

```go
type Schedule struct {
	ID     string    `json:"id"`
	Action string    `json:"action"`
	At     time.Time `json:"at,omitzero"`
	Text   string    `json:"text,omitempty"`
	// Cron, on a create, makes the schedule recur at the
	// times its five-field expression names, read in Zone, an IANA name;
	// At is then its first due time, which the creating host computed.
	Cron string `json:"cron,omitempty"`
	Zone string `json:"zone,omitempty"`
}
```

Schedule is a schedule operation. Action is create or cancel. A create records a wake source named by ID, and the schedule is delivered as occurrences of that source; a cancel ends it. Only create carries At, Text, Cron and Zone. ID belongs to this conversation, remains reserved after cancellation/delivery, and must not be reused.


## SchemaKind

```go
type SchemaKind string
```

SchemaKind distinguishes authored portable contracts from foreign JSON Schema. Its zero value, SchemaCanonical, is the canonical subset.

```go
const (
	// SchemaCanonical is zelk's portable canonical subset.
	SchemaCanonical SchemaKind = ""
	// SchemaOpen is a foreign JSON Schema validated locally and rendered non-strict.
	SchemaOpen SchemaKind = "open"
)
```


## SessionForked

```go
type SessionForked struct {
	From         string          `json:"from"`
	Point        uint64          `json:"point,omitempty"`
	Prompt       string          `json:"prompt,omitempty"`
	Conversation json.RawMessage `json:"conversation"`
}
```

SessionForked follows SessionStarted in a session forked from another (docs/design/rewind.md). Conversation is the source's conversation at Point, or as it stood when forked if Point is zero, as the loop encodes it. The fork reads nothing of the source afterwards.


### SessionForked.Kind

```go
func (SessionForked) Kind() Kind
```

Kind returns KindSessionForked.


## SessionStarted

```go
type SessionStarted struct {
	Config Config `json:"config"`
}
```

SessionStarted opens a session log with the fully resolved configuration. Replay and resume use only what is recorded here, never the current prompt files, tool set or model registry, so a hash of the configuration would not be enough.


### SessionStarted.Kind

```go
func (SessionStarted) Kind() Kind
```

Kind returns [KindSessionStarted](/reference/go/event/).


## SetGoal

```go
type SetGoal struct {
	Text string `json:"text"`
}
```

SetGoal replaces the goal with an explicit objective, as a new revision.


## SetModel

```go
type SetModel struct {
	Provider     history.Family `json:"provider"`
	Model        string         `json:"model"`
	Settings     ModelSettings  `json:"settings"`
	Capabilities Capabilities   `json:"capabilities"`
	// ToolReserves replaces Config.ToolReserves for the new route.
	ToolReserves map[string]Tokens `json:"tool_reserves,omitempty"`
}
```

SetModel requests a model change with settings and capabilities resolved by the host. It waits for outstanding effects and tool results; changing families additionally waits for the current run to finish. Acceptance is durable even when application is deferred. Multiple changes apply in acceptance order.


## SetOutput

```go
type SetOutput struct {
	Output Output   `json:"output"`
	Tool   ToolSpec `json:"tool"`
}
```

SetOutput is the structured output contract of the next run to start, in place of the session's own, if any, for that run alone: a host with one agent can ask each execution for a different shape. Tool is the StructuredOutput tool as the model sees it during the run; its input schema is the contract's.


## SetPermissionMode

```go
type SetPermissionMode struct {
	Mode PermissionMode `json:"mode"`
}
```

SetPermissionMode requests a permission mode the session's policy authorizes. It applies once no tool call is running, so a call is always decided and run under one mode; calls not yet decided see the new mode.


## SetPolicy

```go
type SetPolicy struct {
	Policy Policy     `json:"policy"`
	Launch bool       `json:"launch,omitempty"`
	Narrow bool       `json:"narrow,omitempty"`
	Hooks  []HookSpec `json:"hooks,omitempty"`
}
```

SetPolicy replaces the permission policy the host gave a session (mode, authorized modes, tool ceiling, rules, protected paths, skill grants), as a host does when it takes up a session that isn't idle, or starts one whose policy it has since changed. It applies as SetRules does: once no tool call is running, keeping the user's grants after the rules, and an approval asked under the old policy is decided afresh when answered. The session takes Policy.Mode when Launch is set or its own mode isn't among Policy.Modes; otherwise it keeps its mode, so a switch made within the session lasts.

With Narrow, the session's own policy is instead narrowed by Policy, as a subagent's is by its parent's: it can never widen. A subagent's session accepts only that.

Hooks replace the session's gate hooks when it applies: those of the agent starting it, which is what runs them by name. A hook the session recorded that the agent doesn't have would fail its gate closed on every call, as under a managed policy that turns hooks off.


## SetRules

```go
type SetRules struct {
	Rules     *Rules   `json:"rules,omitempty"`
	Protected []string `json:"protected,omitempty"`
}
```

SetRules replaces the permission rules and protected paths the host gave a session, as a host does when its user changes them while the session runs. It applies once no tool call is running, as a mode change does: a call is decided and run under one policy, and an approval asked under the old one is decided afresh when answered. The rules the user granted in the session stay allowed, after these; a deny rule still overrides them.


## SetTags

```go
type SetTags struct {
	Tags []string `json:"tags"`
}
```

SetTags replaces the session's tags. An empty list clears them.


## SetTitle

```go
type SetTitle struct {
	Title string `json:"title"`
}
```

SetTitle names the session; an empty title clears the name.


## ShortcutFlagged

```go
type ShortcutFlagged struct {
	ID   string `json:"id"`
	Run  uint64 `json:"run"`
	Flag string `json:"flag"`
}
```

ShortcutFlagged records a distinct advisory finding in the current run.


### ShortcutFlagged.Kind

```go
func (ShortcutFlagged) Kind() Kind
```

Kind returns KindShortcutFlagged.


## SkillEntry

```go
type SkillEntry struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	// Source names where the skill comes from; Trust is "host" or
	// "project".
	Source string     `json:"source"`
	Trust  SkillTrust `json:"trust"`
	// Revision is the digest of the skill's bundle manifest.
	Revision string `json:"revision"`
}
```

SkillEntry is a skill as the index shows it.


## SkillFile

```go
type SkillFile struct {
	// Path is relative to the skill's directory, with forward slashes.
	Path string `json:"path"`
	// Digest names the content in the blob store; Size is its length.
	Digest string `json:"digest"`
	Size   int64  `json:"size"`
}
```

SkillFile is one file of a skill's bundle, its content kept as a blob.


## SkillLoaded

```go
type SkillLoaded struct {
	Name     string     `json:"name"`
	Source   string     `json:"source"`
	Trust    SkillTrust `json:"trust"`
	Revision string     `json:"revision"`
	// AllowedTools are permission rules that, while a host-trust skill is
	// active, allow as the session's allow rules do; a project-trust
	// skill's grant nothing.
	AllowedTools []string `json:"allowed_tools,omitempty"`
	// Dir is the skill's directory in the workspace, for a skill whose
	// scripts can run there; empty otherwise.
	// ScriptSourceDir retains the original directory for script hash checks
	// when Dir points at a materialized publication. It grants no permissions.
	ScriptSourceDir string      `json:"script_source_dir,omitempty"`
	Dir             string      `json:"dir,omitempty"`
	Files           []SkillFile `json:"files"`
}
```

SkillLoaded records that a skill's instructions were loaded, with its content-addressed bundle manifest. Replay and resume use the manifest, never the skill's current files.


### SkillLoaded.Kind

```go
func (SkillLoaded) Kind() Kind
```

Kind returns [KindSkillLoaded](/reference/go/event/).


## SkillMaterialized

```go
type SkillMaterialized struct {
	EffectID string `json:"effect_id"`
	Identity string `json:"identity"`
	Dir      string `json:"dir"`
	Bytes    int64  `json:"bytes"`
}
```

SkillMaterialized records a complete verified publication before the effect finishes. Identity binds its session, key and recorded files; Dir is relative to the Environment workspace. Bytes counts bundled file contents.


### SkillMaterialized.Kind

```go
func (SkillMaterialized) Kind() Kind
```

Kind returns KindSkillMaterialized.


## SkillTrust

```go
type SkillTrust string
```

SkillTrust is a skill source's trust level.

```go
const (
	TrustHost    SkillTrust = "host"
	TrustProject SkillTrust = "project"
)
```

The skill trust levels.


## SkillsIndexed

```go
type SkillsIndexed struct {
	Skills []SkillEntry `json:"skills,omitempty"`
	// Unlisted are the skills the index had no room to describe.
	Unlisted []string `json:"unlisted,omitempty"`
}
```

SkillsIndexed is the skill index as the host's skill sources held it at an execution's start, or after a tool call reached a directory holding skills of its own (zelk.WithSkillDiscovery), recorded when it differs from the session's newest (docs/design/skills.md): a skill added, changed or removed since. The model is told of the change before its next call; the index reaches the request context at the next compaction, so the cached prompt prefix holds until then.


### SkillsIndexed.Kind

```go
func (SkillsIndexed) Kind() Kind
```

Kind returns [KindSkillsIndexed](/reference/go/event/).


## SnapshotFile

```go
type SnapshotFile struct {
	Path       string `json:"path"`
	Digest     string `json:"digest"`
	Size       int64  `json:"size"`
	Executable bool   `json:"executable,omitempty"`
}
```

SnapshotFile identifies one regular file in a restore plan and its executable bit. Digest identifies content stored in the session's file history.


## Source

```go
type Source struct {
	// ID identifies the source permanently within its session.
	ID string `json:"id"`
	// Kind is schedule, monitor, watch or job.
	Kind string `json:"kind,omitempty"`
	// ProcessHandle binds a Watch source to the process its launch started,
	// recorded under that handle in the same call. It is empty for sources
	// that observe without owning a process.
	ProcessHandle string `json:"process_handle,omitempty"`
	// Description names the work the source reports.
	Description string `json:"description,omitempty"`
	// Idle requires occurrences to wait for an idle session.
	Idle bool `json:"idle,omitempty"`
	// MinInterval and StopAt are a monitor's: the least time between its
	// occurrences, and when it stops, if it does; a watch resumed after a
	// restart keeps them (docs/design/wakes.md, Watch).
	MinInterval time.Duration `json:"min_interval,omitempty"`
	StopAt      time.Time     `json:"stop_at,omitzero"`
}
```

Source identifies a wake source. Only creation carries Kind, Description and Idle. IDs remain reserved after ending; Idle occurrences require an idle session.


## SourceOccurrence

```go
type SourceOccurrence struct {
	// Source names the recorded source.
	Source string `json:"source"`
	// Kind must match the source kind.
	Kind string `json:"kind"`
	// From is the recorded source cursor plus one.
	From uint64 `json:"from"`
	// To is the inclusive last occurrence admitted.
	To uint64 `json:"to"`
	// Payload is immutable across admission retries.
	Payload OccurrencePayload `json:"payload"`
	// Interaction records an idle joining follow-up's input mode at admission.
	Interaction InteractionMode `json:"interaction,omitempty"`
	// Due is a recurring schedule's latest due time the range covers, which
	// the host computed; zero for any other source.
	Due time.Time `json:"due,omitzero"`
}
```

SourceOccurrence admits an inclusive range of occurrence numbers atomically. Kind must match the recorded source; Payload never changes on delivery retry.


### SourceOccurrence.CommandID

```go
func (p SourceOccurrence) CommandID() string
```

CommandID returns the stable identity of this exact source range.

**Example**

```go
p := event.SourceOccurrence{Kind: "monitor", Source: "build", From: 1, To: 3, Payload: event.OccurrencePayload{Text: "Build failed", Folded: 2}}
c := event.Command{Kind: event.CommandOccurrence, Occurrence: &p, ID: p.CommandID()}
fmt.Println(c.ID, c.Validate())
// Output: monitor:build:1-3 <nil>
```

Output:

```text
monitor:build:1-3 <nil>
```


## Steer

```go
type Steer struct {
	ExpectedRun uint64 `json:"expected_run"`
	Text        string `json:"text"`
}
```

Steer adds input to the run that began at ExpectedRun, the RunID the host saw; a run that has ended rejects it.


## SteerOutcome

```go
type SteerOutcome struct {
	CommandID string `json:"command_id"`
	Applied   bool   `json:"applied"`
	Reason    string `json:"reason,omitempty"`
}
```

SteerOutcome records whether a Steer command applied to its run.


### SteerOutcome.Kind

```go
func (SteerOutcome) Kind() Kind
```

Kind returns [KindSteerOutcome](/reference/go/event/).


## SteerWithdrawn

```go
type SteerWithdrawn struct {
	// CommandID is the WithdrawSteer command's ID; Steer is the steer's.
	CommandID string `json:"command_id"`
	Steer     string `json:"steer"`
	Withdrawn bool   `json:"withdrawn"`
	// Reason says why a steer wasn't withdrawn.
	Reason WithdrawReason `json:"reason,omitempty"`
}
```

SteerWithdrawn records what became of a WithdrawSteer command: whether the steer it names was taken back before a model call took it. A steer taken back never reaches the model, and no longer holds its run open.


### SteerWithdrawn.Kind

```go
func (SteerWithdrawn) Kind() Kind
```

Kind returns [KindSteerWithdrawn](/reference/go/event/).


## SteersTaken

```go
type SteersTaken struct {
	Run    uint64   `json:"run"`
	Steers []string `json:"steers"`
}
```

SteersTaken records that a model call took the steers it names, by command ID and in order, into the conversation: from then on they are the model's to read and can't be withdrawn. It is recorded for a model call that took any steer.


### SteersTaken.Kind

```go
func (SteersTaken) Kind() Kind
```

Kind returns [KindSteersTaken](/reference/go/event/).


## StopDetails

```go
type StopDetails struct {
	Category    string `json:"category,omitempty"`
	Explanation string `json:"explanation,omitempty"`
}
```

StopDetails is what a provider says about why it stopped. For a refusal, Category names the safety classifier that declined the request, such as "cyber" or "bio"; it is empty when none did and the model itself declined, or the provider doesn't say. Explanation is the provider's text, if any.


## StructuredOutputAccepted

```go
type StructuredOutputAccepted struct {
	// EffectID is the StructuredOutput call's effect.
	EffectID string          `json:"effect_id"`
	Value    json.RawMessage `json:"value"`
	// Generation is the session's mutation generation as the call ran.
	Generation uint64 `json:"generation"`
}
```

StructuredOutputAccepted records a StructuredOutput call whose value passed the schema and every validator. It is the run's output while the mutation generation it was produced at stands.


### StructuredOutputAccepted.Kind

```go
func (StructuredOutputAccepted) Kind() Kind
```

Kind returns [KindStructuredOutputAccepted](/reference/go/event/).


## StructuredOutputInvalidated

```go
type StructuredOutputInvalidated struct {
	ID  string `json:"id"`
	Run uint64 `json:"run"`
	// EffectID is the call whose value is invalidated; Generation is the
	// mutation generation that invalidated it.
	EffectID   string `json:"effect_id"`
	Generation uint64 `json:"generation"`
}
```

StructuredOutputInvalidated is the reducer's record that an accepted value no longer stands: an action that may have changed the workspace started after it was produced.


### StructuredOutputInvalidated.Kind

```go
func (StructuredOutputInvalidated) Kind() Kind
```

Kind returns [KindStructuredOutputInvalidated](/reference/go/event/).


## StructuredOutputRejected

```go
type StructuredOutputRejected struct {
	EffectID string        `json:"effect_id"`
	Errors   []OutputError `json:"errors"`
}
```

StructuredOutputRejected records a StructuredOutput call whose value didn't pass, with every problem found.


### StructuredOutputRejected.Kind

```go
func (StructuredOutputRejected) Kind() Kind
```

Kind returns [KindStructuredOutputRejected](/reference/go/event/).


## Suggestion

```go
type Suggestion struct {
	ID   string `json:"id"`
	Rule string `json:"rule"`
}
```

Suggestion is a narrowly scoped allow rule a human may grant.


## Suspended

```go
type Suspended struct {
	// Requests are the requests waiting for an answer.
	Requests []string `json:"requests"`
	// WakeAt is the earliest deadline a host must Start the session by
	// for it to fire on time; zero means none.
	WakeAt time.Time `json:"wake_at,omitzero"`
}
```

Suspended records that an execution stopped to wait for answers, releasing the session (docs/design/durability.md, P1).


### Suspended.Kind

```go
func (Suspended) Kind() Kind
```

Kind returns [KindSuspended](/reference/go/event/).


## TimerFired

```go
type TimerFired struct {
	ID         string `json:"id"`
	Generation uint64 `json:"generation"`
}
```

TimerFired records a live deadline before its consequences cancel any work.


### TimerFired.Kind

```go
func (TimerFired) Kind() Kind
```

Kind returns KindTimerFired.


## TimerSet

```go
type TimerSet struct {
	ID         string    `json:"id"`
	Generation uint64    `json:"generation"`
	Deadline   time.Time `json:"deadline"`
}
```

TimerSet records a timer anchored on an originating log event.


### TimerSet.Kind

```go
func (TimerSet) Kind() Kind
```

Kind returns KindTimerSet.


## Todo

```go
type Todo struct {
	Content string     `json:"content"`
	Status  TodoStatus `json:"status"`
	// Key is a short stable name for the task, which attempt tracking
	// counts failures against.
	Key string `json:"key,omitempty"`
}
```

Todo is one item of the session's task list.


## TodoStatus

```go
type TodoStatus string
```

TodoStatus is the state of one todo item.

```go
const (
	TodoPending    TodoStatus = "pending"
	TodoInProgress TodoStatus = "in_progress"
	TodoCompleted  TodoStatus = "completed"
)
```

The todo states.


## TodosUpdated

```go
type TodosUpdated struct {
	Todos []Todo `json:"todos"`
}
```

TodosUpdated replaces the session's task list.


### TodosUpdated.Kind

```go
func (TodosUpdated) Kind() Kind
```

Kind returns [KindTodosUpdated](/reference/go/event/).


## Tokens

```go
type Tokens struct {
	Input  int64 `json:"input"`
	Output int64 `json:"output"`
}
```

Tokens counts tokens in the ledger's two directions (docs/design/durability.md, B1): input, which includes cache reads and writes, and output, which includes reasoning. Its fields are named apart from Usage's on purpose: Usage.InputTokens is the provider's uncached input only, while Tokens.Input is every input token, the sum TokensOf takes.


### TokensOf

```go
func TokensOf(u Usage) Tokens
```

TokensOf returns the tokens usage counts.

**Example**

```go
t := event.TokensOf(event.Usage{InputTokens: 10, CacheReadTokens: 5, OutputTokens: 8, ReasoningTokens: 3})
fmt.Println(t.Input, t.Output, t.Total())
// Output: 15 8 23
```

Output:

```text
15 8 23
```


### Tokens.Add

```go
func (t Tokens) Add(u Tokens) Tokens
```

Add returns t plus u.


### Tokens.Sub

```go
func (t Tokens) Sub(u Tokens) Tokens
```

Sub returns t minus u.


### Tokens.Total

```go
func (t Tokens) Total() int64
```

Total returns input plus output.


## ToolSpec

```go
type ToolSpec struct {
	// EnforcedIdempotency promises that repeated calls with one key act once.
	EnforcedIdempotency bool            `json:"enforced_idempotency,omitempty"`
	Name                string          `json:"name"`
	Description         string          `json:"description"`
	Origin              Origin          `json:"origin"`
	InputSchema         json.RawMessage `json:"input_schema"`
	// SchemaKind is omitted for a canonical spec.
	SchemaKind SchemaKind `json:"schema_kind,omitempty"`
	ReadOnly   bool       `json:"read_only,omitempty"`
	Idempotent bool       `json:"idempotent,omitempty"`
	Trusted    bool       `json:"trusted,omitempty"`
	// Reserve is what each call reserves from the budget, for a tool that
	// calls a model itself.
	Reserve *Tokens `json:"reserve,omitempty"`
	// ReadOnlyWhen, for a tool that isn't read-only as a whole, names the
	// calls that are: Task's calls for a subagent type that runs in plan
	// mode. Like ReadOnly, it is relied on only for a trusted tool.
	ReadOnlyWhen *ReadOnlyWhen `json:"read_only_when,omitempty"`
	// WritesPath names the input's string field holding the one
	// workspace path a call may write, so a checkpoint saves that file
	// before the call runs (docs/design/checkpoints.md). Like ReadOnly,
	// it is relied on only for a trusted tool.
	WritesPath string `json:"writes_path,omitempty"`
	// URLField names the input's string field holding the URL a call
	// acts on, which domain permission rules match. ReadsPath names the
	// one holding a file a call reads and sends, which is decided as a
	// file tool's path. Like ReadOnly, both are relied on only for a
	// trusted tool.
	URLField  string `json:"url_field,omitempty"`
	ReadsPath string `json:"reads_path,omitempty"`
	// PersonDecides, if set, says an allow rule or a person decides each
	// call, never auto mode's reviewer alone, and is the tool pattern a
	// person's session grant names with the call's domain. Relied on only
	// for a trusted tool.
	PersonDecides string `json:"person_decides,omitempty"`
	// TrustedTab says a call a person decides acts in a tab of the user's
	// browser they trusted, so with a person attending it runs without
	// asking; NewTabField, if set, names the input's boolean field that
	// makes a call open a new tab instead, which the person decides.
	// Relied on only for a trusted tool.
	TrustedTab  bool   `json:"trusted_tab,omitempty"`
	NewTabField string `json:"new_tab_field,omitempty"`
	// Deferred marks a host tool that is always deferred: the model finds
	// it through ToolSearch whatever the session's threshold.
	Deferred bool `json:"deferred,omitempty"`
}
```

ToolSpec records a tool's input contract and the properties the action pipeline relies on. Providers choose a rendering from SchemaKind.


## TurnDiff

```go
type TurnDiff struct {
	Files     []FileDiff      `json:"files"`
	Workspace *WorkspaceDelta `json:"workspace,omitempty"`
}
```

TurnDiff aggregates the changes built-in tools made during a run, by file: each file's revision before its first change and after its last. Files is the exact, attributable part of the turn diff. Workspace, when present, additionally observes Bash and external changes.


### TurnDiff.Kind

```go
func (TurnDiff) Kind() Kind
```

Kind returns [KindTurnDiff](/reference/go/event/).


## Unknown

```go
type Unknown struct {
	Raw json.RawMessage
	// contains filtered or unexported fields
}
```

Unknown is the payload of an event whose kind this zelk doesn't know, in an envelope of its own generation. It keeps the payload so the event can be written back unchanged; the fold refuses it. Only [Decode](/reference/go/event/#decode) makes one: Encode refuses an Unknown built by hand, which has no kind.


### Unknown.Kind

```go
func (u Unknown) Kind() Kind
```

Kind returns the unknown event's kind as recorded in the log.


## Usage

```go
type Usage struct {
	// Breakdown preserves per-request pricing and model attribution for aggregated work.
	Breakdown *UsageBreakdown `json:"breakdown,omitempty"`
	// Family and Model identify a tool's separate model call for pricing.
	// Empty values use the effect's recorded provider and model.
	Family history.Family `json:"family,omitempty"`
	Model  string         `json:"model,omitempty"`
	// InputTokens are prompt tokens neither read from nor written to a
	// cache.
	InputTokens int64 `json:"input_tokens"`
	// OutputTokens are generated tokens, reasoning included.
	OutputTokens     int64 `json:"output_tokens"`
	CacheReadTokens  int64 `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
	// ReasoningTokens are the part of OutputTokens spent reasoning.
	ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
	// OutputUnread says the caller stopped reading before the provider
	// reported the output, as the reviewer does at an allow: the input
	// counts are measured, OutputTokens is zero, and the output is charged
	// as its reservation, not as a measurement.
	OutputUnread bool `json:"output_unread,omitempty"`
}
```

Usage is token usage reported by a provider. The input counts are disjoint, whatever the provider's own convention, so they add up to the whole prompt: adapters normalize to this.


### Usage.Valid

```go
func (u Usage) Valid() bool
```

Valid reports whether usage is normalized, nonnegative and representable in the token ledger. Reasoning is a subset of output, and cached input is disjoint.


## UsageBreakdown

```go
type UsageBreakdown struct {
	// Requests are flat per-call usages whose token counts sum to the owning Usage.
	Requests []Usage `json:"requests"`
}
```

UsageBreakdown retains individual requests when a tool aggregates model work.

**Example**

```go
usage := event.Usage{InputTokens: 300000, Breakdown: &event.UsageBreakdown{Requests: []event.Usage{{InputTokens: 150000, Model: "m"}, {InputTokens: 150000, Model: "m"}}}}
fmt.Println(usage.Valid(), len(usage.Breakdown.Requests))
// Output: true 2
```

Output:

```text
true 2
```


## UserMessage

```go
type UserMessage struct {
	Text string `json:"text"`
	// Files are files, images and MCP resources attached to the message. The
	// model sees each after the message. A workspace file the user named
	// is recorded as the Read tool showed it, and was read at Observed: the
	// model may edit it without reading it again.
	Files []Attachment `json:"files,omitempty"`
}
```

UserMessage is a new message from the user.


### UserMessage.HasImage

```go
func (m UserMessage) HasImage() bool
```

HasImage reports whether any of the message's attachments is an image.


## Verification

```go
type Verification string
```

Verification is how a run's result was verified.

```go
const (
	VerifyPassed  Verification = "verified"
	VerifyNone    Verification = "none_available"
	VerifyFailed  Verification = "failed"
	VerifyStale   Verification = "stale"
	VerifyUnknown Verification = "unknown"
)
```

The verification states.


## VerificationContract

```go
type VerificationContract uint8
```

VerificationContract determines which evidence can satisfy session completion.

```go
const (
	// VerificationRunLocal enrolls host checks and model checks within a run.
	VerificationRunLocal VerificationContract = iota
	// VerificationScoped evaluates requirements owned by a workspace and its work.
	VerificationScoped
)
```


## VerificationWork

```go
type VerificationWork struct {
	ID            string `json:"id"`
	Revision      uint64 `json:"revision"`
	InstructionID string `json:"instruction_id"`
}
```

VerificationWork is a host-associated work revision. InstructionID names an accepted originating instruction; changing focus never retires other work.


### VerificationWork.Validate

```go
func (w VerificationWork) Validate() error
```

Validate checks bounded work identity and instruction-reference shape.


## WakeWithdrawn

```go
type WakeWithdrawn struct {
	Handle string `json:"handle"`
	// Pinned lists the sorted, unique command IDs carried by open attempts.
	Pinned []string `json:"pinned,omitempty"`
}
```

WakeWithdrawn revokes a process's future wakes or a child's completion wake. It preserves notices handed to an open provider attempt because they may reach the model. Handle is the process handle or child session ID.


### WakeWithdrawn.Kind

```go
func (WakeWithdrawn) Kind() Kind
```

Kind returns [KindWakeWithdrawn](/reference/go/event/).


## Warning

```go
type Warning struct {
	// Code is a stable, machine-readable name for the kind of warning.
	Code    WarningCode `json:"code"`
	Message string      `json:"message,omitempty"`
}
```

Warning records that zelk degraded something instead of failing, so the downgrade is never silent.


### Warning.Kind

```go
func (Warning) Kind() Kind
```

Kind returns [KindWarning](/reference/go/event/).


## WarningCode

```go
type WarningCode string
```

WarningCode is a Warning's stable, machine-readable name. Hosts and their tools may use codes of their own; zelk's are below.

```go
const (
	WarnBudgetSoftLimit             WarningCode = "budget_soft_limit"
	WarnClassifierBreaker           WarningCode = "classifier_breaker"
	WarnCompactionFailed            WarningCode = "compaction_failed"
	WarnContextUnavailable          WarningCode = "context_unavailable"
	WarnHookFailed                  WarningCode = "hook_failed"
	WarnInputHeadless               WarningCode = "input_headless"
	WarnInstructionsOmitted         WarningCode = "instructions_omitted"
	WarnInstructionsUnreadable      WarningCode = "instructions_unreadable"
	WarnInvalidUsage                WarningCode = "invalid_usage"
	WarnLateCompletion              WarningCode = "late_completion"
	WarnMCPServerUnavailable        WarningCode = "mcp_server_unavailable"
	WarnMCPToolSkipped              WarningCode = "mcp_tool_skipped"
	WarnMemoryUnavailable           WarningCode = "memory_unavailable"
	WarnModelSwitchBlocked          WarningCode = "model_switch_blocked"
	WarnNativeCompactionFailed      WarningCode = "native_compaction_failed"
	WarnNativeCompactionUnavailable WarningCode = "native_compaction_unavailable"
	WarnOpaqueReasoningDropped      WarningCode = "opaque_reasoning_dropped"
	WarnPromptBlocked               WarningCode = "prompt_blocked"
	WarnProviderRetry               WarningCode = "provider_retry"
	WarnReasoningDropped            WarningCode = "reasoning_dropped"
	WarnReservationExceeded         WarningCode = "reservation_exceeded"
	WarnSkillDescriptionUnclear     WarningCode = "skill_description_unclear"
	WarnSkillDescriptionsOverlap    WarningCode = "skill_descriptions_overlap"
	WarnSkillFileSkipped            WarningCode = "skill_file_skipped"
	WarnSkillIndexFull              WarningCode = "skill_index_full"
	WarnSkillInvalid                WarningCode = "skill_invalid"
	WarnSkillScriptsUnavailable     WarningCode = "skill_scripts_unavailable"
	WarnSkillShadowed               WarningCode = "skill_shadowed"
	WarnSkillSourceInvalid          WarningCode = "skill_source_invalid"
	WarnSkillSourceUnreadable       WarningCode = "skill_source_unreadable"
	WarnSubagentDescriptionsLarge   WarningCode = "subagent_descriptions_large"
	WarnSubagentInvalid             WarningCode = "subagent_invalid"
	WarnSubagentModeNarrowed        WarningCode = "subagent_mode_narrowed"
	WarnUnknownStopReason           WarningCode = "unknown_stop_reason"
	WarnUnsupportedOutput           WarningCode = "unsupported_output"
	WarnUnsupportedStreamEvent      WarningCode = "unsupported_stream_event"
	WarnUsageReasoningCapped        WarningCode = "usage_reasoning_capped"
)
```

The warning codes zelk records.


## WithdrawReason

```go
type WithdrawReason string
```

WithdrawReason is why a steer could not be withdrawn.

```go
const (
	// WithdrawTaken: a model call has taken it, or it was already
	// withdrawn or turned away. Its words are no longer waiting.
	WithdrawTaken WithdrawReason = "not_waiting"
	// WithdrawUnknown: no steer of that command ID was accepted.
	WithdrawUnknown WithdrawReason = "unknown"
)
```

The reasons a steer could not be withdrawn.


## WithdrawSteer

```go
type WithdrawSteer struct {
	Steer string `json:"steer"`
}
```

WithdrawSteer takes back the steer whose command ID is Steer, if no model call has taken it yet.


## WorkspaceBaseline

```go
type WorkspaceBaseline struct {
	Run      uint64          `json:"run"`
	Snapshot json.RawMessage `json:"snapshot"`
}
```

WorkspaceBaseline records an environment's self-contained run baseline. Snapshot is opaque JSON, bounded to 512 KiB and interpreted only by its Differ.


### WorkspaceBaseline.Kind

```go
func (WorkspaceBaseline) Kind() Kind
```

Kind returns KindWorkspaceBaseline.


## WorkspaceDelta

```go
type WorkspaceDelta struct {
	Files      []WorkspaceFile      `json:"files,omitempty"`
	Excluded   []WorkspaceExclusion `json:"excluded,omitempty"`
	Incomplete bool                 `json:"incomplete,omitempty"`
}
```

WorkspaceDelta records observed changes, including changes outside file tools. It does not attribute changes to zelk; Excluded and Incomplete bound its claim.


## WorkspaceExclusion

```go
type WorkspaceExclusion struct {
	Path   string `json:"path"`
	Reason string `json:"reason"`
}
```

WorkspaceExclusion explains a path or subtree omitted from a workspace delta.


## WorkspaceFile

```go
type WorkspaceFile struct {
	Path   string `json:"path"`
	Before string `json:"before,omitempty"`
	After  string `json:"after,omitempty"`
}
```

WorkspaceFile is a changed path with opaque before and after content hashes. An empty Before means creation; an empty After means deletion.


## WorkspaceFingerprinted

```go
type WorkspaceFingerprinted struct {
	EffectID string `json:"effect_id"`
	Attempt  int    `json:"attempt"`
	Before   string `json:"before,omitempty"`
	After    string `json:"after,omitempty"`
}
```

WorkspaceFingerprinted records the workspace's fingerprint before and after a shell command's first attempt, recorded with the call's end. When both are complete and equal, the command changed nothing, and evidence from before it stays fresh. An empty fingerprint means the environment couldn't cover the workspace.


### WorkspaceFingerprinted.Kind

```go
func (WorkspaceFingerprinted) Kind() Kind
```

Kind returns [KindWorkspaceFingerprinted](/reference/go/event/).


## WorkspaceMoveCommitted

```go
type WorkspaceMoveCommitted struct {
	ID string `json:"id"`
}
```

WorkspaceMoveCommitted switches the session to the prepared move's root, once nothing of the old root is live.


### WorkspaceMoveCommitted.Kind

```go
func (WorkspaceMoveCommitted) Kind() Kind
```

Kind returns [KindWorkspaceMoveCommitted](/reference/go/event/).


## WorkspaceMoveHandedOff

```go
type WorkspaceMoveHandedOff struct {
	ID string `json:"id"`
}
```

WorkspaceMoveHandedOff records that an execution at the committed move's root took the session up; dispatch resumes.


### WorkspaceMoveHandedOff.Kind

```go
func (WorkspaceMoveHandedOff) Kind() Kind
```

Kind returns [KindWorkspaceMoveHandedOff](/reference/go/event/).


## WorkspaceMovePrepared

```go
type WorkspaceMovePrepared struct {
	// ID is the move's key: move-<seq> for a host's move, or the tool
	// call's effect ID for the model's own.
	ID string `json:"id"`
	// From is the root the session leaves, To the one it goes to: clean
	// absolute slash-separated paths, as Config.Root.
	From string `json:"from"`
	To   string `json:"to"`
	// Worktree is the session's Config.Worktree at To.
	Worktree bool `json:"worktree,omitempty"`
	// Reason says why, for the model and for audit.
	Reason string `json:"reason,omitempty"`
	// CallID is the tool call that moves the session, whose effect ID is
	// ID; empty for a host's move. A tool's move doesn't interrupt the
	// run: its turn goes on at To after the handoff.
	CallID string `json:"call_id,omitempty"`
}
```

WorkspaceMovePrepared records the intent to move the session to another workspace root, before anything changes (docs/design/transitions.md). Folding it interrupts the current run.


### WorkspaceMovePrepared.Kind

```go
func (WorkspaceMovePrepared) Kind() Kind
```

Kind returns [KindWorkspaceMovePrepared](/reference/go/event/).


## WorkspaceMoved

```go
type WorkspaceMoved struct {
	ID       string `json:"id"`
	EffectID string `json:"effect_id"`
}
```

WorkspaceMoved records that a tool call's start moved the workspace generation: the call may change the workspace, so evidence from before it is stale. The reducer derives it from the call, as with the shell's read-only allowlist, and records it with the call's EffectStarted; a stored log replays with the moves it recorded.


### WorkspaceMoved.Kind

```go
func (WorkspaceMoved) Kind() Kind
```

Kind returns [KindWorkspaceMoved](/reference/go/event/).
