# history

> Package history defines the items that make up a session's conversation: zelk's portable envelope around provider messages.

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

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

Package history defines the items that make up a session's conversation: zelk's portable envelope around provider messages.

Each [Item](/reference/go/history/#item) carries two things:

  - normalized semantics: role, turn, status and ordered parts (text, images, tool calls, tool results, reasoning), with tool results linked to their calls by ID, so zelk can render the history for any provider;
  - the raw provider payload, byte for byte, so that opaque state such as Anthropic thinking signatures or OpenAI encrypted reasoning goes back to the same provider family exactly as it came.

Items are plain data. The event log persists them, and both the event codec and the reducer import this package, which is why it sits below both of them.


## Variables

```go
var ErrInvalid = errors.New("invalid history item")
```

ErrInvalid is wrapped by every error [Item.Validate](/reference/go/history/#itemvalidate) returns.


## ImageType

```go
func ImageType(data []byte) string
```

ImageType returns the media type data starts like, among the image types models take: PNG, JPEG, GIF and WebP. It is empty for anything else.


## Family

```go
type Family string
```

Family is the provider wire format a raw payload belongs to. Raw payloads are only ever sent back to the family that produced them.

```go
const (
	// FamilyAnthropic is the Anthropic Messages API.
	FamilyAnthropic Family = "anthropic"
	// FamilyOpenAI is the OpenAI Responses API.
	FamilyOpenAI Family = "openai"
	// FamilyOpenAICompat is the Chat Completions format that OpenAI and
	// compatible servers share. It streams no item whole, so its raw
	// payload is the assistant message assembled from the stream.
	FamilyOpenAICompat Family = "openaicompat"
	// FamilyGemini is the Gemini API's generateContent format. Its raw
	// payload is the model's content assembled from the stream, with the
	// thought signatures that must go back to it unchanged.
	FamilyGemini Family = "gemini"
)
```

The wire families of the built-in adapters. Hosts may define other nonempty family names; raw payloads are only returned to their exact family.


## Image

```go
type Image struct {
	MediaType string    `json:"media_type"`
	Data      []byte    `json:"data,omitempty"`
	Ref       *blob.Ref `json:"ref,omitempty"`
}
```

Image is image content, held inline in Data or in a blob through Ref; exactly one of them is set. Validation checks this storage shape; runtime admission checks supported types, decodability and byte bounds.


### Attached

```go
func Attached(it Item) (name, text string, img *Image, ok bool)
```

Attached returns what FileItem, ImageItem or ResourceItem gives the model: the attachment's name, and the file's text or the image.


## Item

```go
type Item struct {
	Role Role `json:"role"`
	// TurnID is an opaque label; read Origin for where an item came from.
	TurnID string `json:"turn_id,omitempty"`
	// BackgroundCommand identifies the acceptance that supplied a process
	// notice so later projections can honor a wake withdrawal.
	BackgroundCommand string `json:"background_command,omitempty"`
	// Origin is set on user-role items the loop builds. It is empty on
	// assistant and tool items, and on user items a provider returned.
	Origin Origin `json:"origin,omitempty"`
	Status Status `json:"status"`
	// Parts are the item's content in their original order.
	Parts []Part `json:"parts,omitempty"`
	// Family is set on items a provider produced, together with exactly
	// one of Raw and RawRef, and is empty on items zelk built itself.
	Family Family `json:"family,omitempty"`
	// Raw is the provider's payload for the whole item, byte for byte. It
	// is encoded as base64 in JSON because encoding/json would re-compact a
	// json.RawMessage, and opaque reasoning must round-trip exactly.
	Raw []byte `json:"raw,omitempty"`
	// RawRef holds the raw payload instead of Raw when it is too large for
	// a log record.
	RawRef *blob.Ref `json:"raw_ref,omitempty"`
}
```

Item is one entry of a session's history, in the order the provider produced or will receive it.

**Example**

A tool call from the model and the item that carries its result back.

```go
call := history.Item{
	Role:   history.RoleAssistant,
	Status: history.StatusCompleted,
	Parts: []history.Part{{
		Kind:     history.KindToolCall,
		ToolCall: &history.ToolCall{ID: "call_1", Name: "Read", Input: json.RawMessage(`{"path":"go.mod"}`)},
	}},
}
result := history.Item{
	Role:   history.RoleTool,
	Status: history.StatusCompleted,
	Parts: []history.Part{{
		Kind: history.KindToolResult,
		ToolResult: &history.ToolResult{
			CallID:  "call_1",
			Content: []history.Part{{Kind: history.KindText, Text: "module example.com/demo"}},
		},
	}},
}
fmt.Println(call.Validate(), result.Validate())

// A tool result can't come from the assistant.
result.Role = history.RoleAssistant
fmt.Println(result.Validate())
// Output:
// <nil> <nil>
// part 0: invalid history item: assistant items can't contain tool_result parts
```

Output:

```text
<nil> <nil>
part 0: invalid history item: assistant items can't contain tool_result parts
```


### FileItem

```go
func FileItem(path, text string) Item
```

FileItem returns the item that gives the model a file the user attached to a message: path as the user named it, then text, the file as the Read tool showed it.


### ImageItem

```go
func ImageItem(name string, img Image) Item
```

ImageItem returns the item that gives the model an image the user attached to a message, under name: a file's path, or a name the host gave an image pasted from the clipboard.


### ResourceItem

```go
func ResourceItem(name, text string) Item
```

ResourceItem returns attached external resource text without claiming a workspace read. The text should be bounded and fenced by the caller.

**Example**

```go
item := history.ResourceItem("docs:data:notes", "<untrusted>\nNotes\n</untrusted>")
name, _, _, ok := history.Attached(item)
fmt.Println(name, ok)
// Output: docs:data:notes true
```

Output:

```text
docs:data:notes true
```


### Item.Validate

```go
func (it Item) Validate() error
```

Validate reports whether the item is well formed: known role, status, family and part kinds; each part carrying exactly its own payload; tool calls and reasoning only from the assistant; tool results only, and exclusively, in tool items.


## Kind

```go
type Kind string
```

Kind is the type of a [Part](/reference/go/history/#part).

```go
const (
	KindText       Kind = "text"        // Part.Text
	KindImage      Kind = "image"       // Part.Image
	KindToolCall   Kind = "tool_call"   // Part.ToolCall
	KindToolResult Kind = "tool_result" // Part.ToolResult
	KindReasoning  Kind = "reasoning"   // Part.Reasoning
)
```

The kinds of part, each with its own payload field in [Part](/reference/go/history/#part).


## Origin

```go
type Origin string
```

Origin says where a user-role item came from. Assistant and tool items need none: their role says it.

```go
const (
	// OriginUser is a message the user sent.
	OriginUser Origin = "user"
	// OriginSteer is a message the user sent while a run was going, to
	// steer it.
	OriginSteer Origin = "steer"
	// OriginSkill is the text of a skill the user invoked.
	OriginSkill Origin = "skill"
	// OriginNote is a note the harness left for the model, such as a hook's
	// added context or a budget warning. It is not the user's.
	OriginNote Origin = "note"
	// OriginSummary is a compaction's summary of the history it replaced.
	OriginSummary Origin = "summary"
	// OriginBackground is the runtime's notice that a background job
	// finished or waits for input. It is not the user's.
	OriginBackground Origin = "background"
	// OriginFile is a file the user attached to a message, made by
	// FileItem.
	OriginFile Origin = "file"
)
```

The origins of user-role items.


## Part

```go
type Part struct {
	Kind       Kind        `json:"kind"`
	Text       string      `json:"text,omitempty"`
	Image      *Image      `json:"image,omitempty"`
	ToolCall   *ToolCall   `json:"tool_call,omitempty"`
	ToolResult *ToolResult `json:"tool_result,omitempty"`
	Reasoning  *Reasoning  `json:"reasoning,omitempty"`
}
```

Part is one piece of an item's content. Kind says which payload field is set; exactly that one is.


## Reasoning

```go
type Reasoning struct {
	Summary string `json:"summary,omitempty"`
	// Opaque reports that the raw payload carries reasoning state that
	// can't be rendered for another provider family and is dropped, with a
	// warning, when the history is sent to one.
	Opaque bool `json:"opaque,omitempty"`
}
```

Reasoning is model reasoning. Its readable summary, if any, is in Summary; the provider's opaque form lives only in the item's raw payload.


## Role

```go
type Role string
```

Role is who an item comes from.

```go
const (
	// RoleUser is input from the user or the host.
	RoleUser Role = "user"
	// RoleAssistant is output from the model.
	RoleAssistant Role = "assistant"
	// RoleTool carries the results of tool calls back to the model.
	RoleTool Role = "tool"
)
```

The roles an item can have.


## Status

```go
type Status string
```

Status says whether the producer finished an item.

```go
const (
	// StatusCompleted is a finished item.
	StatusCompleted Status = "completed"
	// StatusIncomplete is an item the producer stopped early, for example
	// when the model hit its output limit. A tool call in an incomplete
	// item may have truncated input and is never run.
	StatusIncomplete Status = "incomplete"
)
```

The statuses an item can have.


## ToolCall

```go
type ToolCall struct {
	// ID links the call to its [ToolResult]. It is the provider's call ID.
	ID   string `json:"id"`
	Name string `json:"name"`
	// Input is the call's arguments as JSON. It is nil if the arguments
	// never arrived in full.
	Input json.RawMessage `json:"input,omitempty"`
	// PartialInput holds the arguments as far as they arrived when the
	// model stopped mid-call, which is not valid JSON. It is set only in
	// incomplete items, never together with Input.
	PartialInput string `json:"partial_input,omitempty"`
}
```

ToolCall is the model asking to run a tool.


### ToolCall.Complete

```go
func (c *ToolCall) Complete() bool
```

Complete reports whether the call's arguments arrived in full. A call that isn't complete is never run: its input may be cut short.


## ToolResult

```go
type ToolResult struct {
	// CallID is the ID of the [ToolCall] this result answers.
	CallID string `json:"call_id"`
	// Content is text and image parts.
	Content []Part `json:"content,omitempty"`
	IsError bool   `json:"is_error,omitempty"`
	// FullOutput is the tool's complete output when Content holds only a
	// bounded preview of it, such as the head and tail of a long command
	// output. The model can read it in pages.
	FullOutput *blob.Ref `json:"full_output,omitempty"`
	// Loaded names the deferred tools this result loads, a ToolSearch's
	// answer. A provider that loads tools natively sends them as its own
	// references or definitions; others send Content.
	Loaded []string `json:"loaded,omitempty"`
}
```

ToolResult is the outcome of one tool call.
