ir

package
v0.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ir is the conversation representation every agent module reads into and writes from, so a session can continue in another agent: N readers and N writers instead of a converter for every pair. It keeps what a coding conversation means (messages, tool calls with their intent, results, plans) and, beside it, each record's native form so a writer for the same agent can emit it unchanged.

Index

Constants

View Source
const (
	OlderExtract = "extract" // a labeled extract of older history plus recent turns
	OlderRecent  = "recent"  // recent complete turns only
)

Older-context choices.

View Source
const (
	DefaultReadBytes       int64 = MaxTranscriptBytes
	DefaultRecordBytes     int64 = 32 << 20
	DefaultArchiveBytes    int64 = MaxTranscriptBytes
	DefaultLineageBytes    int64 = 64 << 20
	DefaultNativeFileBytes int64 = 1 << 30

	CeilingReadBytes       int64 = 4 << 30
	CeilingRecordBytes     int64 = 256 << 20
	CeilingArchiveBytes    int64 = 8 << 30
	CeilingLineageBytes    int64 = 512 << 20
	CeilingNativeFileBytes int64 = 8 << 30
	// MinContextBudget keeps a user budget large enough for a briefing and a request.
	MinContextBudget = 4096
)

Defaults and hard ceilings. Defaults are the limits hopsesh shipped before they were configurable; ceilings bound what a setting may ask for.

View Source
const (
	StageRead    = "read"    // decoding a native transcript
	StageRecord  = "record"  // one native record
	StageLineage = "lineage" // persisted movement ledger
	StageArchive = "archive" // building or merging the portable archive
	StageNative  = "native"  // reading a whole native file (fork, recovery, verification)
	StageContext = "context" // the receiving agent's context
	StageDisk    = "disk"    // free disk space where the archive or session is written
)

Limit stages, as LimitError reports them.

View Source
const FallbackWindow = 64_000

FallbackWindow deliberately does not assume the largest model available to an account.

View Source
const MaxTranscriptBytes = 256 << 20

MaxTranscriptBytes is the default read budget (history.read_memory_mb).

Variables

View Source
var ErrLimit = errors.New("history limit reached")

ErrLimit matches every LimitError.

Functions

func Canonical

func Canonical(v any) ([]byte, error)

Canonical encodes v as RFC 8785 (JSON Canonicalization Scheme) JSON: object keys sorted by UTF-16 code units, no insignificant whitespace, minimal string escaping. Numbers must be integers (hopsesh hashes no floats).

func Chain

func Chain(nodes []Node, parent NodeID)

Chain sets Parent and ID on nodes in order, starting after parent.

func ContentHash added in v0.4.0

func ContentHash(n Node) string

ContentHash excludes chain position, timestamps and representation provenance.

func ItemCost added in v0.4.0

func ItemCost(it Item) int

ItemCost includes every model-visible tool field and message framing. UTF-8 bytes intentionally overestimate byte-based tokenizers instead of relying on bytes/4.

func ItemsCost added in v0.4.0

func ItemsCost(items []Item) int

func WithLimits added in v0.4.2

func WithLimits(ctx context.Context, l Limits) context.Context

WithLimits scopes limits to one operation.

Types

type Actor

type Actor string

Actor is who produced a node.

const (
	User  Actor = "user"
	Agent Actor = "agent"
)

type Attachment

type Attachment struct {
	MIME string `json:"mime"`
	Data []byte `json:"data,omitempty"`
	Name string `json:"name,omitempty"`
}

Attachment is an image or file the user attached.

type BoundedReader added in v0.4.0

type BoundedReader struct {
	Context   context.Context
	Reader    io.Reader
	ReadBytes int64
	Limit     int64
}

BoundedReader caps memory exposure in native decoders and checks cancellation on every read. Crossing the cap is an explicit LimitError; it never truncates a transcript. Limit 0 uses the operation's read budget (LimitsFrom(Context).ReadBytes).

func (*BoundedReader) Read added in v0.4.0

func (r *BoundedReader) Read(p []byte) (int, error)

type Capacity added in v0.4.0

type Capacity struct {
	ConfigHash string `json:"configHash,omitempty"`
	Model      string `json:"model,omitempty"`
	Window     int    `json:"window"`
	Source     string `json:"source"`
	Existing   int    `json:"existing"`
	Unknown    bool   `json:"unknown,omitempty"`
}

Capacity describes a static, conservative check, not a successful model turn.

func (Capacity) Allowance added in v0.4.0

func (c Capacity) Allowance() int

Allowance is what one transfer may add. A new session reserves 30% for instructions, tools and the next response. An existing session's measured usage already includes its instructions and tools, so adding to it reserves only the next response (10%): reserving 30% again refused a return of six messages to a session at 87% of 1M. A single transfer uses at most 30%. Counts are UTF-8 byte upper estimates.

func (Capacity) Check added in v0.4.0

func (c Capacity) Check(items []Item) error

func (Capacity) EffectiveWindow added in v0.4.0

func (c Capacity) EffectiveWindow() int

type Cursor

type Cursor struct {
	Offset int64  `json:"offset"`
	Head   NodeID `json:"head,omitempty"`
}

Cursor is where a read stopped: the byte offset after the last complete record of the session's main file, and the last node read.

type Edit

type Edit struct {
	Path string `json:"path"`
	Old  string `json:"old,omitempty"`
	New  string `json:"new,omitempty"`
	Diff string `json:"diff,omitempty"`
}

Edit changes part of a file: either Old/New text, or a unified diff.

type Fragment added in v0.4.0

type Fragment struct {
	Text     string   `json:"text"`
	Coverage []NodeID `json:"coverage"`
}

Fragment retains individual source coverage when adjacent messages coalesce.

type Header struct {
	Agent     string    `json:"agent"`
	Version   string    `json:"version,omitempty"`
	SessionID string    `json:"sessionId"`
	CWD       string    `json:"cwd"`
	Title     string    `json:"title,omitempty"`
	GitBranch string    `json:"gitBranch,omitempty"`
	Model     string    `json:"model,omitempty"`
	Created   time.Time `json:"created"`
}

Header describes a session as a whole.

type Item

type Item struct {
	Fragments []Fragment `json:"fragments,omitempty"`
	Node      NodeID     `json:"node"`
	Role      Role       `json:"role"`
	Time      time.Time  `json:"time"`
	Text      string     `json:"text,omitempty"`
	Tool      *ToolPair  `json:"tool,omitempty"`   // native replay only
	Native    *Native    `json:"native,omitempty"` // same-agent passthrough
	Coverage  []NodeID   `json:"coverage,omitempty"`
	Generated bool       `json:"generated,omitempty"`
	Fidelity  string     `json:"fidelity,omitempty"`
}

Item is one rendered unit for a writer.

type Kind

type Kind string

Kind is what a node is.

const (
	KindMessage    Kind = "message"
	KindReasoning  Kind = "reasoning"
	KindToolCall   Kind = "tool_call"
	KindToolResult Kind = "tool_result"
	KindPlan       Kind = "plan"
	KindCompaction Kind = "compaction"
	KindAttachment Kind = "attachment"
)

type LimitError added in v0.4.2

type LimitError struct {
	Stage  string `json:"stage"`
	Limit  int64  `json:"limit"`
	Size   int64  `json:"size,omitempty"` // bytes seen when it stopped (a lower bound)
	Detail string `json:"detail,omitempty"`
}

LimitError is a reached limit. Canonical history is never silently truncated: the operation stops, sources and existing destinations stay unchanged, and the error names the stage and the setting that governs it.

func AsLimit added in v0.4.2

func AsLimit(err error) (*LimitError, bool)

AsLimit returns the LimitError in err's chain, if any.

func (*LimitError) Error added in v0.4.2

func (e *LimitError) Error() string

func (*LimitError) Is added in v0.4.2

func (e *LimitError) Is(target error) bool

func (*LimitError) Setting added in v0.4.2

func (e *LimitError) Setting() string

Setting is the configuration key that governs the stage.

type Limits added in v0.4.2

type Limits struct {
	ReadBytes       int64 `json:"readBytes,omitempty"`
	RecordBytes     int64 `json:"recordBytes,omitempty"`
	ArchiveBytes    int64 `json:"archiveBytes,omitempty"`
	LineageBytes    int64 `json:"lineageBytes,omitempty"`
	NativeFileBytes int64 `json:"nativeFileBytes,omitempty"`
	// ContextBudget optionally lowers the receiving context (upper-estimate units, as
	// Capacity.Allowance). 0 is automatic. It can never raise the model's allowance.
	ContextBudget int `json:"contextBudget,omitempty"`
	// Older is how history older than the recent turns is carried: OlderExtract (default)
	// or OlderRecent. Omitted history always stays in the portable archive.
	Older string `json:"older,omitempty"`
}

Limits is one operation's history and resource policy. Each budget is separate: memory a native decoder may hold, one native record, the portable archive on disk, whole native files read for fork/recovery/verification, and the receiving context. A zero field means the default; Normalize clamps every field to its hard ceiling. Limits travel with an operation (Options, context), never as mutable globals.

func DefaultLimits added in v0.4.2

func DefaultLimits() Limits

DefaultLimits are the limits when the user chose none.

func LimitsFrom added in v0.4.2

func LimitsFrom(ctx context.Context) Limits

LimitsFrom returns the operation's limits, or the defaults.

func (Limits) Allowance added in v0.4.2

func (l Limits) Allowance(model int) int

Allowance applies the user's optional context budget to a model allowance.

func (Limits) Check added in v0.4.2

func (l Limits) Check() error

Check reports a limit that is outside its range (for settings validation).

func (Limits) Normalize added in v0.4.2

func (l Limits) Normalize() Limits

Normalize fills defaults and clamps to the hard ceilings.

type MCP

type MCP struct {
	Server string `json:"server"`
	Tool   string `json:"tool"`
}

MCP is a call to a tool of an MCP server.

type Native

type Native struct {
	Format  string          `json:"format"` // "claude.jsonl", "codex.rollout"
	Payload json.RawMessage `json:"payload"`
	Anchor  string          `json:"anchor,omitempty"` // stable native record identity, independent of rewritten paths
}

Native is a node's record as its agent wrote it.

type Node

type Node struct {
	Fragments []Fragment `json:"fragments,omitempty"`
	ID        NodeID     `json:"id"`
	Parent    NodeID     `json:"parent,omitempty"`
	Kind      Kind       `json:"kind"`
	Actor     Actor      `json:"actor"`
	Time      time.Time  `json:"time"`
	// Text is the message, the reasoning summary or the compaction summary.
	Text       string      `json:"text,omitempty"`
	Tool       *ToolCall   `json:"tool,omitempty"`
	Result     *ToolResult `json:"result,omitempty"`
	Plan       []PlanEntry `json:"plan,omitempty"`
	Attachment *Attachment `json:"attachment,omitempty"`
	Reasoning  *Reasoning  `json:"reasoning,omitempty"`
	Native     *Native     `json:"native,omitempty"`
	Generated  bool        `json:"generated,omitempty"` // written by hopsesh (briefing, acknowledgement)
	Coverage   []NodeID    `json:"coverage,omitempty"`  // logical revisions represented by this node
}

Node is one step of a conversation.

type NodeID

type NodeID string

NodeID is a content address: SHA-256 (hex) of the canonical form of a node's model-visible content and its parent's id. The same conversation read twice, or from a copy with other timestamps and native ids, gets the same ids.

func ComputeID

func ComputeID(n Node, parent NodeID) NodeID

ComputeID returns a node's content address given its parent.

type PlanEntry

type PlanEntry struct {
	Content string `json:"content"`
	Status  string `json:"status"` // pending | in_progress | completed
}

PlanEntry is one item of the agent's plan or to-do list.

type Profile

type Profile struct {
	Window       int  `json:"window"`       // the target model's usable context, in tokens
	NativeReplay bool `json:"nativeReplay"` // can render tool calls as its own tool pairs
	// PortableAppend writes ordinary text turns into an existing session in the
	// selected root. It preserves its old records and never imports source-private
	// state. This is independent of permission to replay native tool/reasoning data.
	PortableAppend bool `json:"portableAppend,omitempty"`
}

Profile is what a writer can take.

type Projection added in v0.4.0

type Projection struct {
	Fragments []Fragment `json:"fragments,omitempty"`
	Anchor    string     `json:"anchor"`
	Hash      string     `json:"hash"`
	Coverage  []NodeID   `json:"coverage,omitempty"`
	Generated bool       `json:"generated,omitempty"`
	Fidelity  string     `json:"fidelity,omitempty"`
}

Projection binds the exact native representation to the logical revisions it carries. It lives in the portable sidecar, never in vendor-specific transcript fields.

func ProjectionFor added in v0.4.0

func ProjectionFor(n Node, item Item) Projection

type Reasoning

type Reasoning struct {
	Opaque bool `json:"opaque"` // signed or encrypted content (in Native)
}

Reasoning is the agent's thinking. It never crosses vendors: Opaque content is bound to the model, account or conversation prefix that produced it.

type Role

type Role string

Role is who a rendered item speaks as.

const (
	RoleUser  Role = "user"
	RoleAgent Role = "agent"
)
type Search struct {
	Pattern string `json:"pattern"`
	Path    string `json:"path,omitempty"`
}

Search looks for files or text.

type Segment

type Segment struct {
	Header Header `json:"header"`
	Nodes  []Node `json:"nodes"`
	Cursor Cursor `json:"cursor"`
}

Segment is what a Reader returns: the session's active branch from a cursor on.

type Shell

type Shell struct {
	Command string `json:"command"`
	Dir     string `json:"dir,omitempty"`
}

Shell is a command run in a shell.

type Subagent

type Subagent struct {
	Description string `json:"description,omitempty"`
	Prompt      string `json:"prompt,omitempty"`
}

Subagent hands a task to a sub-agent.

type ToolCall

type ToolCall struct {
	CallID string          `json:"callId"`
	Name   string          `json:"name"`  // the agent's tool name: "Bash", "exec_command", "mcp__github__x"
	Input  json.RawMessage `json:"input"` // exact input
	Kind   ToolKind        `json:"kind"`

	Shell    *Shell    `json:"shell,omitempty"`
	Edit     *Edit     `json:"edit,omitempty"`
	Write    *Write    `json:"write,omitempty"`
	Path     string    `json:"path,omitempty"` // read, delete
	Search   *Search   `json:"search,omitempty"`
	URL      string    `json:"url,omitempty"` // fetch
	Subagent *Subagent `json:"subagent,omitempty"`
	MCP      *MCP      `json:"mcp,omitempty"`
}

ToolCall is a tool the agent called. Exactly one of the intent fields is set when the reader understood the call; Name and Input always keep the original.

type ToolKind

type ToolKind string

ToolKind is the intent of a tool call (the Agent Client Protocol's kinds).

const (
	ToolRead     ToolKind = "read"
	ToolEdit     ToolKind = "edit"
	ToolDelete   ToolKind = "delete"
	ToolMove     ToolKind = "move"
	ToolSearch   ToolKind = "search"
	ToolExecute  ToolKind = "execute"
	ToolThink    ToolKind = "think"
	ToolFetch    ToolKind = "fetch"
	ToolPlan     ToolKind = "plan"
	ToolSubagent ToolKind = "subagent"
	ToolOther    ToolKind = "other"
)

type ToolPair

type ToolPair struct {
	Call   ToolCall   `json:"call"`
	Result ToolResult `json:"result"`
}

ToolPair is a tool call and its result, for native replay.

type ToolResult

type ToolResult struct {
	CallID   string     `json:"callId"`
	Status   ToolStatus `json:"status"`
	ExitCode *int       `json:"exitCode,omitempty"`
	Output   string     `json:"output"`
	// OutputBytes is the size of the full output when Output was shortened by the reader.
	OutputBytes int64 `json:"outputBytes,omitempty"`
}

ToolResult is what a tool call returned.

type ToolStatus

type ToolStatus string

ToolStatus is how a tool call ended.

const (
	StatusCompleted ToolStatus = "completed"
	StatusFailed    ToolStatus = "failed"
)

type Write

type Write struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

Write creates or replaces a whole file.

type WriteMode

type WriteMode string

WriteMode is whether a write creates a session or extends one.

const (
	WriteNew    WriteMode = "new"
	WriteAppend WriteMode = "append"
)

type WriteRequest

type WriteRequest struct {
	OperationID string    `json:"operationId,omitempty"` // stable transfer identity; scopes generated native record IDs
	Mode        WriteMode `json:"mode"`
	// SessionID is the session to append to (WriteAppend), or the id to use for a new one
	// ("" lets the writer choose).
	SessionID string `json:"sessionId,omitempty"`
	// Expect is where the session's main file must still end for an append (it was read up
	// to there); anything else is ErrDiverged.
	Expect Cursor `json:"expect"`
	Header Header `json:"header"`
	Items  []Item `json:"items"`
}

WriteRequest asks a writer for native records.

type WriteResult

type WriteResult struct {
	SessionID  string       `json:"sessionId"`
	Path       string       `json:"path"`
	From       int64        `json:"from"` // byte range written into Path
	To         int64        `json:"to"`
	Cursor     Cursor       `json:"cursor"` // the session's new end
	Projection []Projection `json:"projection,omitempty"`
}

WriteResult is what a writer wrote.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL