session

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 11 Imported by: ? modules, 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

pi: harness/session/commit.ts — transaction write materialization and validation shared by every storage backend.

pi: harness/session/context.ts — session context assembly (v0.85.1: the model/thinking/tools state extraction moved to lane configuration values; only message projection remains here).

Deviations:

  • pi's `timestamp: string | number` parameters are int64 ms here (see harness/messages.go note).
  • pi's async projector contract (EntryProjector returning Promise<AgentMessage[] | undefined>) collapses to a synchronous callback per §3.4; buildSessionContext stays synchronous.

Package session corresponds to pi's packages/agent/src/harness/session.

pi: harness/session/fork.ts — fork snapshot selection and reconstruction.

pi: harness/session/fork-policy.ts — fork disposition of stored values.

pi: harness/session/in-memory-storage-state.ts — complete materialized session state for MemoryStorage and JsonlStorage.

"Intentionally unsuitable for database backends and long-running sessions that may not fit in memory" (pi's comment): those backends query indexed durable state and update durable aggregates within each commit transaction. Not thread-safe; owners (MemoryStorage / JsonlStorage) guard it with their commit mutex.

pi: harness/session/memory.ts — in-memory Storage and SessionRepo.

Concurrency mapping: pi serializes commits through a promise queue; pig guards the state with a mutex (commit serialization is subsumed by it). The MemorySessionFacade's admitted-op tracking maps to a WaitGroup-guarded in-flight counter so Close waits for outstanding operations.

pi: harness/session/mutation-line.ts — serializes complete read-modify- write jobs for one Session.

Deviation: pi chains promises (jobs queue behind the previous tail); Go uses a condition variable. Run waits for the in-flight job, re-checks the seal, executes exclusively, and broadcasts on release. Seal records the error (first one wins) and waits for the in-flight job to drain, matching `seal()` returning this.tail. Jobs rejected by a seal fail with the sealed error exactly like pi's rejected promise chain.

pi: harness/session/session.ts — StorageBackedSession, the branch view, the mutation barrier, and the session-level error types.

Concurrency mapping: pi relies on the single-threaded event loop; pig guards the session state fields with a mutex and serializes mutations through MutationLine. Reads run against the storage's own synchronization.

pi: harness/session/types.ts — the session storage type surface: Entry union, the durable operation-state family, Write/commit shapes, scan queries, and the Storage / Session / SessionRepo interfaces (v0.85.1 redesign: 4-entry union + value/list storage + transactional commits).

Type mapping deviations, all declared here:

  • Entry discriminated union → interface + concrete types + DecodeEntry dispatch (per §3.4). NewEntry<TEntry> (TS Omit) has no Go counterpart: callers pass the concrete entry with Seq/Timestamp zero and storage fills them.
  • SettledAssistantMessage is a type-level refinement of AssistantMessage; no runtime counterpart, not ported.
  • JsonValue (recursive JSON union from chord, type-only) → any.
  • Value<T>/ValueList<T> phantom type parameters collapse to non-generic Value / ValueList (phantom types are compile-time only; values cross the Storage interface as any). See values.go.
  • Storage / Session / SessionReader generic methods (getValue<T> etc.) collapse to erased any-based signatures: Go interfaces cannot declare type-parameterized methods (the TModel generic rule). Typed sugar helpers live in values.go.
  • Session<TMetadata> drops its generic parameter (per §3.4): the interface exposes GetMetadata() SessionMetadata; JSONL consumers reach JsonlSessionMetadata through the concrete *StorageBackedSession's exported Metadata field plus a type assertion.
  • pi's async methods return Promises; Go methods return (T, error) and take ctx context.Context (AbortSignal → context rule; the TS `context: Context` parameter carries cancellation/telemetry, mapped to the Go ctx + harness.GetTelemetryContext).
  • OperationMeta's inline intent union → OperationIntent interface + three concrete kinds (discriminant field "kind"). The 13 flat OperationState leaves are concrete structs with an At discriminant field behind the OperationState marker interface; none are written by pig today (the runtime subsystem is excluded), but the shapes are the durable wire contract and stay 1:1.
  • DurableStructuralPreparation references CompactionPreparation / BranchPreparation type-only from harness/compaction, which imports this package — Go would cycle. The referenced members are plain AgentMessage slices / scalars, so they are inlined here (comment marks the provenance of each field).
  • "returns undefined" reads as (nil, nil) / nil; documented per method.

pi: harness/session/values.ts — typed storage addresses (scalars and lists), the value write shapes, and the well-known address helpers.

Deviations:

  • Value<T>/ValueList<T> phantom type parameters collapse to non-generic Value / ValueList (Go interfaces cannot carry generic methods, so the Storage/Session surface is erased to any; see types.go). The declared value type survives only in the helper constructors' doc comments.
  • TS's `storedValueType` unique-symbol brand and Object.freeze have no runtime counterpart; Go value objects are plain structs.
  • Methods named `value`/`list` in TS become NewValue/NewList (Go keywords/naming).

Index

Constants

View Source
const (
	// ForkScopeBranch copies one path from a configured source lane.
	ForkScopeBranch = "branch"
	// ForkScopeTree copies the whole conversation tree and every branch tip.
	ForkScopeTree = "tree"
)

ForkScope constants pick the fork copying strategy (pi: ForkOptions union).

View Source
const (
	ForkPositionBefore = "before"
	ForkPositionAt     = "at"
)

ForkPosition constants pick where a branch fork places its tip (pi: position union member). Default includes the selected entry ("at").

Variables

View Source
var SessionNameAddress = MustValue(namespaceSessionName, "")

SessionNameAddress is the session name (pi: sessionName; Value<string>).

Functions

func BuildSessionContext

func BuildSessionContext(pathEntries []Entry, options *SessionContextBuildOptions, ctx context.Context) ([]agent.AgentMessage, error)

BuildSessionContext assembles the LLM context for one branch path (pi: buildSessionContext).

func SessionEntryToContextMessages

func SessionEntryToContextMessages(entry Entry) []agent.AgentMessage

SessionEntryToContextMessages projects one entry into context messages (pi: sessionEntryToContextMessages).

func ValidateCommittedWrites

func ValidateCommittedWrites(writes []CommittedWrite, firstSeq int64, state CommitValidationState) error

ValidateCommittedWrites enforces monotonic sequences, entry/usage id uniqueness, and parent existence (pi: validateCommittedWrites).

Types

type AssistantEffectPendingOperation

type AssistantEffectPendingOperation struct {
	OperationScope
	GenerationContext   GenerationContext `json:"generationContext"`
	Attempt             int               `json:"attempt"`
	ResponseEntryID     string            `json:"responseEntryId"`
	UsageID             string            `json:"usageId"`
	IntendedOutputLimit int64             `json:"intendedOutputLimit"`
	ContextWindow       int64             `json:"contextWindow"`
	At                  string            `json:"at"` // "assistant.effect_pending"
}

func (AssistantEffectPendingOperation) OperationAt

func (s AssistantEffectPendingOperation) OperationAt() string

type AssistantReadyOperation

type AssistantReadyOperation struct {
	OperationScope
	GenerationContext GenerationContext `json:"generationContext"`
	NextAttempt       int               `json:"nextAttempt"`
	At                string            `json:"at"` // "assistant.ready"
}

func (AssistantReadyOperation) OperationAt

func (s AssistantReadyOperation) OperationAt() string

type AssistantRetryWaitOperation

type AssistantRetryWaitOperation struct {
	OperationScope
	GenerationContext GenerationContext `json:"generationContext"`
	RetryWait
	At string `json:"at"` // "assistant.retry_wait"
}

func (AssistantRetryWaitOperation) OperationAt

func (s AssistantRetryWaitOperation) OperationAt() string

type Branch

type Branch interface {
	Name() string
	GetTipID(ctx context.Context) (*string, error)
	FindEntries(query *BranchScan, ctx context.Context) ([]Entry, error)
	FindEntry(query *BranchScan, ctx context.Context) (Entry, error)
	AppendMessage(message agent.AgentMessage, ctx context.Context) (string, error)
	AppendCustomEntry(customType string, data JsonValue, ctx context.Context) (string, error)
}

Branch is a branch-scoped read/write view (pi: Branch).

type BranchScan

type BranchScan struct {
	Start      *string    `json:"start,omitempty"`
	StopAtType *EntryType `json:"stopAtType,omitempty"`
	StopAtID   *string    `json:"stopAtId,omitempty"`
	Type       *EntryType `json:"type,omitempty"`
	CustomType *string    `json:"customType,omitempty"`
	// Order is "newestFirst" | "oldestFirst"; the zero value means
	// newestFirst (Branch.FindEntries defaults explicitly).
	Order  string       `json:"order,omitempty"`
	Limit  *int         `json:"limit,omitempty"`
	Cursor *EntryCursor `json:"cursor,omitempty"`
}

BranchScan queries one branch path (pi: BranchScan).

type BranchSummaryEntry

type BranchSummaryEntry struct {
	EntryBase
	// FromID is the source branch tip the summary was taken from; nil
	// encodes pi's fromId: null (root source).
	FromID  *string      `json:"fromId"`
	Summary string       `json:"summary"`
	Details JsonValue    `json:"details,omitempty"`
	Usage   *types.Usage `json:"usage,omitempty"`
	// FromHook is required on the wire (pi: fromHook: boolean).
	FromHook bool `json:"fromHook"`
}

func (BranchSummaryEntry) EntryType

func (e BranchSummaryEntry) EntryType() EntryType

type CheckpointData

type CheckpointData struct {
	Continuation   Continuation `json:"continuation"`
	TriggerEntryID string       `json:"triggerEntryId"`
}

CheckpointData is the checkpoint payload (pi: CheckpointData); the flat leaf literal replaces the old nested phase tag.

type CheckpointOperation

type CheckpointOperation struct {
	OperationScope
	CheckpointData
	At string `json:"at"` // "checkpoint"
}

func (CheckpointOperation) OperationAt

func (s CheckpointOperation) OperationAt() string

type CommitResult

type CommitResult struct {
	FirstSeq  int64        `json:"firstSeq"`
	Seqs      []int64      `json:"seqs"`
	Timestamp int64        `json:"timestamp"`
	Stats     SessionStats `json:"stats"`
}

CommitResult reports the assigned sequences of one commit (pi: CommitResult).

type CommitValidationState

type CommitValidationState interface {
	HasEntryOrUsageID(id string) bool
	HasEntryID(id string) bool
}

CommitValidationState is the duplicate/parent lookup surface used by ValidateCommittedWrites (pi: CommitValidationState).

type CommittedEntryWrite

type CommittedEntryWrite struct {
	Entry
}

CommittedEntryWrite is an entry write with its assigned seq/timestamp (pi: Entry & { kind: "entry" } — the committed entry IS an Entry, flattened on the wire with a kind member).

func (CommittedEntryWrite) CommittedSeq

func (w CommittedEntryWrite) CommittedSeq() int64

func (CommittedEntryWrite) MarshalJSON

func (w CommittedEntryWrite) MarshalJSON() ([]byte, error)

MarshalJSON flattens the entry and adds kind (pi's Entry & { kind }).

func (*CommittedEntryWrite) UnmarshalJSON

func (w *CommittedEntryWrite) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the flattened shape through DecodeEntry.

type CommittedListAppendWrite

type CommittedListAppendWrite struct {
	Kind      string `json:"kind"`
	Op        string `json:"op"`
	Seq       int64  `json:"seq"`
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	Value     any    `json:"value"`
}

CommittedListAppendWrite is a list append with its assigned seq (pi: CommittedListAppendWrite).

func (CommittedListAppendWrite) CommittedSeq

func (w CommittedListAppendWrite) CommittedSeq() int64

type CommittedListDeleteWrite

type CommittedListDeleteWrite struct {
	Kind      string `json:"kind"`
	Op        string `json:"op"`
	Seq       int64  `json:"seq"`
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
}

CommittedListDeleteWrite is a list delete with its assigned seq (pi: CommittedListDeleteWrite).

func (CommittedListDeleteWrite) CommittedSeq

func (w CommittedListDeleteWrite) CommittedSeq() int64

type CommittedUsageWrite

type CommittedUsageWrite struct {
	UsageRow
	Kind string `json:"kind"`
}

CommittedUsageWrite is a usage row with its assigned seq (pi: UsageRow & { kind: "usage" }).

func (CommittedUsageWrite) CommittedSeq

func (w CommittedUsageWrite) CommittedSeq() int64

type CommittedValueDeleteWrite

type CommittedValueDeleteWrite struct {
	Kind      string `json:"kind"`
	Op        string `json:"op"`
	Seq       int64  `json:"seq"`
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
}

CommittedValueDeleteWrite is a scalar delete with its assigned seq (pi: CommittedValueDeleteWrite).

func (CommittedValueDeleteWrite) CommittedSeq

func (w CommittedValueDeleteWrite) CommittedSeq() int64

type CommittedValueSetWrite

type CommittedValueSetWrite struct {
	Kind      string `json:"kind"`
	Op        string `json:"op"`
	Seq       int64  `json:"seq"`
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	Value     any    `json:"value"`
}

CommittedValueSetWrite is a scalar set with its assigned seq (pi: CommittedValueSetWrite).

func (CommittedValueSetWrite) CommittedSeq

func (w CommittedValueSetWrite) CommittedSeq() int64

type CommittedWrite

type CommittedWrite interface {
	CommittedSeq() int64
	// contains filtered or unexported methods
}

CommittedWrite is one write with its storage-assigned sequence (pi: CommittedWrite union). Concrete kinds: CommittedEntryWrite, CommittedUsageWrite, CommittedValueSetWrite, CommittedValueDeleteWrite, CommittedListAppendWrite, CommittedListDeleteWrite.

func CommitWrite

func CommitWrite(write Write, seq int64, timestamp int64) (CommittedWrite, error)

CommitWrite assigns seq (and, for entries, timestamp) to one write (pi: commitWrite).

func ForkSnapshotWrites

func ForkSnapshotWrites(snapshot ForkDestinationSnapshot) []CommittedWrite

ForkSnapshotWrites converts a destination snapshot into committed writes ordered by seq (pi: forkSnapshotWrites).

type CompactionEntry

type CompactionEntry struct {
	EntryBase
	Summary      string               `json:"summary"`
	RetainedTail []agent.AgentMessage `json:"retainedTail"`
	TokensBefore int64                `json:"tokensBefore"`
	Details      JsonValue            `json:"details,omitempty"`
	Usage        *types.Usage         `json:"usage,omitempty"`
	// FromHook reports whether the compaction was triggered by the
	// session_before_compact hook. Required on the wire (pi: fromHook:
	// boolean), never omitted.
	FromHook bool `json:"fromHook"`
}

func (CompactionEntry) EntryType

func (e CompactionEntry) EntryType() EntryType

type CompactionIntent

type CompactionIntent struct {
	Kind               OperationIntentKind `json:"kind"`
	CustomInstructions *string             `json:"customInstructions,omitempty"`
}

func (CompactionIntent) OperationIntentKind

func (i CompactionIntent) OperationIntentKind() OperationIntentKind

type Continuation

type Continuation struct {
	// Kind is "need_assistant" | "may_finish".
	Kind string `json:"kind"`
	// OverflowRecoveryUsed is set only for "need_assistant".
	OverflowRecoveryUsed *bool `json:"overflowRecoveryUsed,omitempty"`
	// IncludeFinalAssistant is set only for "may_finish".
	IncludeFinalAssistant *bool `json:"includeFinalAssistant,omitempty"`
}

Continuation discriminates the checkpoint continuation union (pi: Continuation).

type Control

type Control struct {
	Status string `json:"status"` // "running" | "cancel_requested"
	// RequestedAt is set only when Status is "cancel_requested".
	RequestedAt *int64 `json:"requestedAt,omitempty"`
}

Control is the cancellation state of one running operation (pi: Control).

type CustomEntry

type CustomEntry struct {
	EntryBase
	Data JsonValue `json:"data,omitempty"`
}

func (CustomEntry) EntryType

func (e CustomEntry) EntryType() EntryType

type DeferredEffectPendingOperation

type DeferredEffectPendingOperation struct {
	OperationScope
	StepID          string            `json:"stepId"`
	SourceEntryID   string            `json:"sourceEntryId"`
	Poll            int               `json:"poll"`
	Configuration   LaneConfiguration `json:"configuration"`
	StreamOptions   json.RawMessage   `json:"streamOptions"`
	ResponseEntryID string            `json:"responseEntryId"`
	UsageID         string            `json:"usageId"`
	At              string            `json:"at"` // "deferred.effect_pending"
}

func (DeferredEffectPendingOperation) OperationAt

func (s DeferredEffectPendingOperation) OperationAt() string

type DeferredSuspendedOperation

type DeferredSuspendedOperation struct {
	OperationScope
	StepID        string            `json:"stepId"`
	SourceEntryID string            `json:"sourceEntryId"`
	Poll          int               `json:"poll"`
	Configuration LaneConfiguration `json:"configuration"`
	StreamOptions json.RawMessage   `json:"streamOptions"`
	At            string            `json:"at"` // "deferred.suspended"
}

func (DeferredSuspendedOperation) OperationAt

func (s DeferredSuspendedOperation) OperationAt() string

type DurableFileOperations

type DurableFileOperations struct {
	Read    []string `json:"read"`
	Written []string `json:"written"`
	Edited  []string `json:"edited"`
}

DurableFileOperations accumulates file paths touched by summarized messages (pi: DurableFileOperations).

type DurableStructuralPreparation

type DurableStructuralPreparation struct {
	Kind string `json:"kind"`
	// Compaction members:
	MessagesToSummarize []agent.AgentMessage `json:"messagesToSummarize,omitempty"`
	TurnPrefixMessages  []agent.AgentMessage `json:"turnPrefixMessages,omitempty"`
	RetainedTail        []agent.AgentMessage `json:"retainedTail,omitempty"`
	IsSplitTurn         bool                 `json:"isSplitTurn,omitempty"`
	TokensBefore        int64                `json:"tokensBefore,omitempty"`
	PreviousSummary     *string              `json:"previousSummary,omitempty"`
	// Compaction settings snapshot (pi: settings: CompactionSettings); kept
	// raw to avoid the import cycle.
	Settings json.RawMessage `json:"settings,omitempty"`
	// Branch-summary members:
	Messages    []agent.AgentMessage  `json:"messages,omitempty"`
	FileOps     DurableFileOperations `json:"fileOps"`
	TotalTokens int64                 `json:"totalTokens,omitempty"`
}

DurableStructuralPreparation is the durable preparation payload of a compaction or branch-summary task (pi: DurableStructuralPreparation). Kind: "compaction" | "branch_summary". Fields inline the type-only references into harness/compaction (import-cycle note in the file header): MessagesToSummarize/TurnPrefixMessages/RetainedTail/Messages are AgentMessage slices from CompactionPreparation/BranchPreparation.

type EffectPendingRequest

type EffectPendingRequest struct {
	Index   int    `json:"index"`
	UsageID string `json:"usageId"`
}

EffectPendingRequest is pi's inline `{ index: number; usageId: string }`.

type Entry

type Entry interface {
	// EntryType returns the discriminant literal ("message", "custom", ...).
	EntryType() EntryType
	// Base exposes the shared fields for storage-side assignment (exported:
	// backend implementations and tests outside this package need it).
	Base() *EntryBase
}

Entry is the persisted session-tree node union (pi: Entry).

func BuildContextEntries

func BuildContextEntries(pathEntries []Entry) []Entry

BuildContextEntries keeps everything after the last compaction entry, replacing the pre-compaction history with the compaction entry itself (pi: buildContextEntries).

func DecodeEntry

func DecodeEntry(data json.RawMessage) (Entry, error)

DecodeEntry decodes one entry, dispatching on its "type" field.

type EntryBase

type EntryBase struct {
	ID         string    `json:"id"`
	ParentID   *string   `json:"parentId"`
	Seq        int64     `json:"seq"`       // storage-assigned; zero on NewEntry input
	Timestamp  int64     `json:"timestamp"` // Unix ms, storage-assigned; zero on NewEntry input
	Type       EntryType `json:"type"`
	CustomType *string   `json:"customType,omitempty"`
}

EntryBase carries the storage-assigned fields shared by every entry (pi: EntryBase). ID is caller-supplied (the session's IdGenerator); ParentID is the branch tip the entry appends to; Seq and Timestamp are storage- assigned and must be left zero by callers. CustomType is nominally shared across the union (pi declares it on EntryBase) but is only populated on custom entries.

func (*EntryBase) Base

func (b *EntryBase) Base() *EntryBase

func (*EntryBase) CustomTypeOrValue

func (b *EntryBase) CustomTypeOrValue() string

CustomTypeOrValue returns the custom entry type value (nil-safe accessor over EntryBase.CustomType).

type EntryCursor

type EntryCursor struct {
	Seq int64 `json:"seq"`
}

EntryCursor pages branch scans by sequence (pi: EntryCursor).

type EntryProjector

type EntryProjector func(entry CustomEntry, ctx context.Context) ([]agent.AgentMessage, error)

EntryProjector converts an application-defined custom entry into model context (pi: EntryProjector). pi's Promise return collapses to a synchronous callback (§3.4); returning nil means "no contribution", a non-nil error propagates (pi's rejected promise).

type EntryQuery

type EntryQuery struct {
	Type       *EntryType   `json:"type,omitempty"`
	CustomType *string      `json:"customType,omitempty"`
	Order      string       `json:"order,omitempty"`
	Limit      *int         `json:"limit,omitempty"`
	Cursor     *EntryCursor `json:"cursor,omitempty"`
}

EntryQuery filters session-wide entry reads (pi: EntryQuery). Order: "asc" | "desc" (default "desc" at the Session level).

type EntryScan

type EntryScan struct {
	Type       *EntryType `json:"type,omitempty"`
	CustomType *string    `json:"customType,omitempty"`
	FromSeq    *int64     `json:"fromSeq,omitempty"`
	ToSeq      *int64     `json:"toSeq,omitempty"`
	Order      string     `json:"order,omitempty"`
	Limit      *int       `json:"limit,omitempty"`
}

EntryScan queries entries by sequence window (pi: EntryScan). Order: "asc" | "desc".

type EntryStructure

type EntryStructure struct {
	ID         string    `json:"id"`
	ParentID   *string   `json:"parentId"`
	Seq        int64     `json:"seq"`
	Timestamp  int64     `json:"timestamp"`
	Type       EntryType `json:"type"`
	CustomType *string   `json:"customType,omitempty"`
}

EntryStructure is the structural projection of an entry for cheap branch scans (pi: EntryStructure).

type EntryType

type EntryType string

EntryType is the closed entry discriminant vocabulary (pi: EntryType).

const (
	EntryTypeMessage       EntryType = "message"
	EntryTypeCompaction    EntryType = "compaction"
	EntryTypeBranchSummary EntryType = "branch_summary"
	EntryTypeCustom        EntryType = "custom"
)

type EntryWrite

type EntryWrite struct {
	Entry Entry `json:"entry"`
}

EntryWrite appends one provisioned entry (pi: EntryWrite).

func InsertEntry

func InsertEntry(entry Entry) EntryWrite

InsertEntry wraps one provisioned entry as an entry write (pi: insertEntry).

type ForkDestinationSnapshot

type ForkDestinationSnapshot struct {
	Entries      map[string]Entry
	ScalarValues []StoredValue
	NextSeq      int64
}

ForkDestinationSnapshot is the complete logical state for a forked destination session (pi: ForkDestinationSnapshot).

func CreateForkSnapshot

func CreateForkSnapshot(source ForkSourceSnapshot, options ForkOptions) (ForkDestinationSnapshot, error)

CreateForkSnapshot builds the complete logical state for a forked destination session (pi: createForkSnapshot).

type ForkDisposition

type ForkDisposition string

ForkDisposition is the final action for current state at one address (pi: ForkDisposition):

  • "copy": emit the current value in the destination;
  • "exclude": omit it from the destination;
  • "reconstruct": do not copy the row because lane handling emits a coherent replacement.
const (
	ForkDispositionCopy        ForkDisposition = "copy"
	ForkDispositionExclude     ForkDisposition = "exclude"
	ForkDispositionReconstruct ForkDisposition = "reconstruct"
)

func ClassifyForkAddress

func ClassifyForkAddress(address Value, scope string, isEntryCopied func(entryID string) bool) (ForkDisposition, error)

ClassifyForkAddress decides the final fork action for one current scalar address (pi: classifyForkAddress).

type ForkOptions

type ForkOptions struct {
	Scope    string  `json:"scope,omitempty"`
	Branch   string  `json:"branch,omitempty"`
	EntryID  *string `json:"entryId,omitempty"`
	Position string  `json:"position,omitempty"`
	ID       *string `json:"id,omitempty"`
}

ForkOptions collapses pi's ForkOptions union into one struct. Scope "" behaves as "branch" (pi's discriminated union has no default; the repo layer validates). For branch scope: Branch selects the source branch, EntryID selects the entry on its tip ancestry (default: current tip), and Position selects whether the fork includes the selected entry ("at", default) or stops at its parent ("before"). ID optionally names the destination session.

type ForkSourceSnapshot

type ForkSourceSnapshot struct {
	Entries      []Entry
	ScalarValues []StoredValue
	// EntriesComplete is false when a backend supplied only the requested
	// branch rather than the full tree. Pi's optional-true semantics: nil
	// means complete.
	EntriesComplete *bool
}

ForkSourceSnapshot is the state captured from a source session (pi: ForkSourceSnapshot).

type GenerationContext

type GenerationContext struct {
	StepID               string                `json:"stepId"`
	TriggerEntryID       string                `json:"triggerEntryId"`
	Configuration        LaneConfiguration     `json:"configuration"`
	StreamOptions        json.RawMessage       `json:"streamOptions"`
	RetryPolicy          NormalizedRetryPolicy `json:"retryPolicy"`
	OverflowRecoveryUsed bool                  `json:"overflowRecoveryUsed"`
}

GenerationContext carries the full assistant-generation inputs (pi: GenerationContext).

type IdGenerator

type IdGenerator interface {
	Next(timestampMs int64) string
}

IdGenerator produces entry/session ids (pi: IdGenerator). timestampMs stamps the id's time component; 0 means the current time (pi's optional parameter).

type InMemoryStorageState

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

InMemoryStorageState is the shared materialized state (pi: InMemoryStorageState).

func NewInMemoryStorageState

func NewInMemoryStorageState() *InMemoryStorageState

NewInMemoryStorageState builds an empty state.

func (*InMemoryStorageState) AdvanceNextSeq

func (s *InMemoryStorageState) AdvanceNextSeq(nextSeq int64) error

AdvanceNextSeq raises the sequence high-water mark (pi: advanceNextSeq).

func (*InMemoryStorageState) ApplyValidated

func (s *InMemoryStorageState) ApplyValidated(writes []CommittedWrite) SessionStats

ApplyValidated applies writes already accepted by ValidateCommitted and returns the post-apply totals (pi: applyValidated).

func (*InMemoryStorageState) GetEntries

func (s *InMemoryStorageState) GetEntries(ids []string) map[string]Entry

GetEntries returns the requested entries that exist (pi: getEntries).

func (*InMemoryStorageState) GetStats

func (s *InMemoryStorageState) GetStats() SessionStats

GetStats returns the aggregate ledger (pi: getStats).

func (*InMemoryStorageState) GetValue

func (s *InMemoryStorageState) GetValue(address Value) *StoredValue

GetValue returns one scalar (pi: getValue).

func (*InMemoryStorageState) PrepareCommit

func (s *InMemoryStorageState) PrepareCommit(writes []Write, timestamp int64) (PreparedCommit, error)

PrepareCommit materializes and validates a transaction at the next free sequence (pi: prepareCommit).

func (*InMemoryStorageState) ReadList

func (s *InMemoryStorageState) ReadList(address ValueList, options *ListReadOptions) ([]ListElement, error)

ReadList reads one list with paging (pi: readList).

func (*InMemoryStorageState) ScanBranch

func (s *InMemoryStorageState) ScanBranch(query StorageBranchScan) ([]Entry, error)

ScanBranch walks one branch path from start toward the root (pi: scanBranch).

func (*InMemoryStorageState) ScanBranchStructure

func (s *InMemoryStorageState) ScanBranchStructure(query StorageBranchScan) ([]EntryStructure, error)

ScanBranchStructure projects a branch scan to entry structures (pi: scanBranchStructure).

func (*InMemoryStorageState) ScanEntries

func (s *InMemoryStorageState) ScanEntries(query EntryScan) []Entry

ScanEntries scans all entries by sequence window (pi: scanEntries).

func (*InMemoryStorageState) ScanUsage

func (s *InMemoryStorageState) ScanUsage(query UsageScan) []UsageRow

ScanUsage scans usage rows by sequence window (pi: scanUsage).

func (*InMemoryStorageState) ScanValues

func (s *InMemoryStorageState) ScanValues(prefix Value) []StoredValue

ScanValues returns scalars in one namespace whose key starts with the prefix, ordered by key (pi: scanValues).

func (*InMemoryStorageState) SnapshotEntriesAndValues

func (s *InMemoryStorageState) SnapshotEntriesAndValues() (ForkSourceSnapshot, error)

SnapshotEntriesAndValues captures the state for forking at a serialized boundary (pi: snapshotEntriesAndValues).

func (*InMemoryStorageState) ValidateCommitted

func (s *InMemoryStorageState) ValidateCommitted(writes []CommittedWrite) error

ValidateCommitted validates writes against the current state (pi: validateCommitted).

type InboxItem

type InboxItem struct {
	EntryID string        `json:"entryId"`
	Kind    InboxItemKind `json:"kind"`
}

InboxItem is one queued item on a lane (pi: InboxItem).

type InboxItemKind

type InboxItemKind string

InboxItemKind is the queue vocabulary (pi: InboxItemKind).

const (
	InboxItemSteer    InboxItemKind = "steer"
	InboxItemFollowUp InboxItemKind = "followUp"
	InboxItemNextRun  InboxItemKind = "nextRun"
	InboxItemWrite    InboxItemKind = "write"
)

type JsonValue

type JsonValue = any

JsonValue (pi: recursive JSON union re-exported from chord) maps to any.

type LaneConfiguration

type LaneConfiguration struct {
	Model struct {
		Provider string `json:"provider"`
		ModelID  string `json:"modelId"`
	} `json:"model"`
	ThinkingLevel   string   `json:"thinkingLevel"`
	ActiveToolNames []string `json:"activeToolNames"`
}

LaneConfiguration is the durable per-lane model configuration (pi: LaneConfiguration), reconstructed from legacy model_change entries during v3 migration and written by the (excluded) runtime.

type LaneState

type LaneState struct {
	CurrentOperationID *string     `json:"currentOperationId"`
	LastOperationID    *string     `json:"lastOperationId"`
	Inbox              []InboxItem `json:"inbox"`
}

LaneState is the idle/queueing state of one lane (pi: LaneState).

type ListAppendWrite

type ListAppendWrite struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	Value     any    `json:"value"`
}

ListAppendWrite appends one list element (pi: ListAppendWrite).

func AppendList

func AppendList(address ValueList, element any) ListAppendWrite

AppendList builds a list append write (pi: appendList).

func (ListAppendWrite) Op

func (w ListAppendWrite) Op() string

Op returns the list operation.

type ListCursor

type ListCursor struct {
	Seq int64 `json:"seq"`
}

ListCursor pages list reads by sequence (pi: ListCursor).

type ListDeleteWrite

type ListDeleteWrite struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
}

ListDeleteWrite deletes one list (pi: ListDeleteWrite).

func DeleteList

func DeleteList(address ValueList) ListDeleteWrite

DeleteList builds a list delete write (pi: deleteList).

func (ListDeleteWrite) Op

func (w ListDeleteWrite) Op() string

Op returns the list operation.

type ListElement

type ListElement struct {
	Seq   int64 `json:"seq"`
	Value any   `json:"value"`
}

ListElement is one stored list element (pi: ListElement<T>).

type ListReadOptions

type ListReadOptions struct {
	Cursor *ListCursor `json:"cursor,omitempty"`
	Order  string      `json:"order,omitempty"` // "asc" | "desc"
	Limit  *int        `json:"limit,omitempty"`
}

ListReadOptions parameterizes list reads (pi: ListReadOptions).

type MemorySessionFacade

type MemorySessionFacade struct {
	*StorageBackedSession
	// contains filtered or unexported fields
}

MemorySessionFacade guards a StorageBackedSession behind repo close semantics (pi: MemorySessionFacade).

func (*MemorySessionFacade) AppendList

func (f *MemorySessionFacade) AppendList(address ValueList, element any, ctx context.Context) error

func (*MemorySessionFacade) BeginMutation

func (f *MemorySessionFacade) BeginMutation(ctx context.Context) (SessionMutation, error)

BeginMutation wraps the source mutation with close tracking (pi: beginMutation).

func (*MemorySessionFacade) Branch

func (f *MemorySessionFacade) Branch(name string, ctx context.Context) (Branch, error)

func (*MemorySessionFacade) Close

func (*MemorySessionFacade) CreateBranch

func (f *MemorySessionFacade) CreateBranch(name string, at *string, ctx context.Context) (Branch, error)

func (*MemorySessionFacade) DeleteList

func (f *MemorySessionFacade) DeleteList(address ValueList, ctx context.Context) error

func (*MemorySessionFacade) DeleteValue

func (f *MemorySessionFacade) DeleteValue(address Value, ctx context.Context) error

func (*MemorySessionFacade) FindEntries

func (f *MemorySessionFacade) FindEntries(query *EntryQuery, ctx context.Context) ([]Entry, error)

func (*MemorySessionFacade) FindEntry

func (f *MemorySessionFacade) FindEntry(query *EntryQuery, ctx context.Context) (Entry, error)

func (*MemorySessionFacade) GetEntries

func (f *MemorySessionFacade) GetEntries(ids []string, ctx context.Context) (map[string]Entry, error)

func (*MemorySessionFacade) GetEntry

func (f *MemorySessionFacade) GetEntry(id string, ctx context.Context) (Entry, error)

func (*MemorySessionFacade) GetLabel

func (f *MemorySessionFacade) GetLabel(targetID string, ctx context.Context) (*string, error)

func (*MemorySessionFacade) GetMetadata

func (f *MemorySessionFacade) GetMetadata() SessionMetadata

GetMetadata returns the facade metadata (pi: metadata).

func (*MemorySessionFacade) GetName

func (f *MemorySessionFacade) GetName(ctx context.Context) (*string, error)

func (*MemorySessionFacade) GetStats

func (*MemorySessionFacade) GetValue

func (f *MemorySessionFacade) GetValue(address Value, ctx context.Context) (*StoredValue, error)

func (*MemorySessionFacade) Mutate

Mutate runs the callback under the facade's open check. pi re-checks facade openness INSIDE the mutation callback (after the inner line is acquired) so a queued callback fails when close won the race.

func (*MemorySessionFacade) ReadList

func (f *MemorySessionFacade) ReadList(address ValueList, options *ListReadOptions, ctx context.Context) ([]ListElement, error)

func (*MemorySessionFacade) ScanBranch

func (f *MemorySessionFacade) ScanBranch(query StorageBranchScan, ctx context.Context) ([]Entry, error)

func (*MemorySessionFacade) ScanValues

func (f *MemorySessionFacade) ScanValues(prefix Value, ctx context.Context) ([]StoredValue, error)

func (*MemorySessionFacade) SetLabel

func (f *MemorySessionFacade) SetLabel(targetID string, label *string, ctx context.Context) error

func (*MemorySessionFacade) SetName

func (f *MemorySessionFacade) SetName(name *string, ctx context.Context) error

func (*MemorySessionFacade) SetValue

func (f *MemorySessionFacade) SetValue(address Value, next any, ctx context.Context) error

type MemorySessionRepo

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

MemorySessionRepo is the in-memory SessionRepo (pi: MemorySessionRepo).

func NewMemorySessionRepo

func NewMemorySessionRepo(options MemorySessionRepoOptions) *MemorySessionRepo

NewMemorySessionRepo builds one memory repo (pi: constructor).

func (*MemorySessionRepo) Close

func (r *MemorySessionRepo) Close(ctx context.Context) error

Close closes the repo and every open session handle (pi: close). pi leaves a TODO on ownership semantics for JsonlSessionRepo; MemorySessionRepo closes all sessions, and pig mirrors that for both.

func (*MemorySessionRepo) Create

func (*MemorySessionRepo) Delete

func (r *MemorySessionRepo) Delete(metadata SessionMetadata, ctx context.Context) error

func (*MemorySessionRepo) Fork

func (r *MemorySessionRepo) Fork(source SessionMetadata, options ForkOptions, ctx context.Context) (Session, error)

func (*MemorySessionRepo) List

func (*MemorySessionRepo) Open

type MemorySessionRepoOptions

type MemorySessionRepoOptions struct {
	Now func() int64
}

MemorySessionRepoOptions parameterizes MemorySessionRepo (pi: MemorySessionRepoOptions).

type MemoryStorage

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

MemoryStorage implements Storage entirely in memory (pi: MemoryStorage).

func MemoryStorageFromSnapshot

func MemoryStorageFromSnapshot(options MemoryStorageOptions, snapshot ForkDestinationSnapshot) (*MemoryStorage, error)

MemoryStorageFromSnapshot builds a memory storage from a complete prepared fork snapshot (pi: MemoryStorage.fromSnapshot static).

func NewMemoryStorage

func NewMemoryStorage(options MemoryStorageOptions) *MemoryStorage

NewMemoryStorage builds one memory storage (pi: constructor).

func (*MemoryStorage) CaptureForkSource

func (m *MemoryStorage) CaptureForkSource(_ context.Context) (ForkSourceSnapshot, error)

CaptureForkSource captures the state needed to fork at one serialized boundary between commits (pi: captureForkSource).

func (*MemoryStorage) Close

func (m *MemoryStorage) Close(_ context.Context) error

func (*MemoryStorage) Commit

func (m *MemoryStorage) Commit(writes []Write, _ context.Context) (CommitResult, error)

Commit applies one transaction (pi: commit). Storage guards state access with its mutex; commit order equals mutex acquisition order.

func (*MemoryStorage) GetEntries

func (m *MemoryStorage) GetEntries(ids []string, _ context.Context) (map[string]Entry, error)

func (*MemoryStorage) GetStats

func (m *MemoryStorage) GetStats(_ context.Context) (SessionStats, error)

func (*MemoryStorage) GetValue

func (m *MemoryStorage) GetValue(address Value, _ context.Context) (*StoredValue, error)

func (*MemoryStorage) ReadList

func (m *MemoryStorage) ReadList(address ValueList, options *ListReadOptions, _ context.Context) ([]ListElement, error)

func (*MemoryStorage) ScanBranch

func (m *MemoryStorage) ScanBranch(query StorageBranchScan, _ context.Context) ([]Entry, error)

func (*MemoryStorage) ScanBranchStructure

func (m *MemoryStorage) ScanBranchStructure(query StorageBranchScan, _ context.Context) ([]EntryStructure, error)

func (*MemoryStorage) ScanEntries

func (m *MemoryStorage) ScanEntries(query EntryScan, _ context.Context) ([]Entry, error)

func (*MemoryStorage) ScanUsage

func (m *MemoryStorage) ScanUsage(query UsageScan, _ context.Context) ([]UsageRow, error)

func (*MemoryStorage) ScanValues

func (m *MemoryStorage) ScanValues(prefix Value, _ context.Context) ([]StoredValue, error)

type MemoryStorageOptions

type MemoryStorageOptions struct {
	// Now overrides the commit timestamp source.
	Now func() int64
}

MemoryStorageOptions parameterizes MemoryStorage (pi: MemoryStorageOptions).

type MessageEntry

type MessageEntry struct {
	EntryBase
	Message agent.AgentMessage `json:"message"`
	// Terminate is pi's `terminate?: true`: only ever true when present.
	Terminate *bool `json:"terminate,omitempty"`
}

func (MessageEntry) EntryType

func (e MessageEntry) EntryType() EntryType

type MutationLine

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

MutationLine serializes mutation jobs for one Session (pi: MutationLine).

func NewMutationLine

func NewMutationLine() *MutationLine

NewMutationLine builds an unsealed line.

func (*MutationLine) Run

func (l *MutationLine) Run(fn func() error) error

Run executes one job under the line; a sealed line rejects every job (pi: run).

func (*MutationLine) Seal

func (l *MutationLine) Seal(err error) <-chan struct{}

Seal records the terminal error and returns a channel closed once the in-flight job has drained (pi: seal returning this.tail). The first sealed error wins.

func (*MutationLine) SealAndWait

func (l *MutationLine) SealAndWait(err error)

SealAndWait blocks until the drained boundary (convenience for callers that need the promise await semantics inline).

type NavigationIntent struct {
	Kind               OperationIntentKind `json:"kind"`
	TargetID           *string             `json:"targetId"` // null allowed
	Summarize          bool                `json:"summarize"`
	Label              *string             `json:"label,omitempty"`
	CustomInstructions *string             `json:"customInstructions,omitempty"`
}
func (i NavigationIntent) OperationIntentKind() OperationIntentKind
type NavigationReadyToCommitOperation struct {
	OperationScope
	At string `json:"at"` // "navigation.ready_to_commit"
	// TargetID may target the branch root (null) for unsummarized
	// navigation.
	TargetID *string `json:"targetId"`
	Label    *string `json:"label,omitempty"`
}
func (s NavigationReadyToCommitOperation) OperationAt() string

type NormalizedRetryPolicy

type NormalizedRetryPolicy struct {
	MaxAttempts int `json:"maxAttempts"`
	BaseDelayMs int `json:"baseDelayMs"`
}

NormalizedRetryPolicy is the resolved retry configuration (pi: NormalizedRetryPolicy).

type Operation

type Operation struct {
	Meta  OperationMeta  `json:"meta"`
	State OperationState `json:"state"`
}

Operation pairs the durable meta with the durable state (pi: Operation).

type OperationError

type OperationError struct {
	Code    string    `json:"code"`
	Message string    `json:"message"`
	Details JsonValue `json:"details,omitempty"`
}

OperationError is the structured failure payload of a terminal operation (pi: OperationError).

type OperationIntent

type OperationIntent interface {
	OperationIntentKind() OperationIntentKind
}

OperationIntent is the intent union of OperationMeta (pi: inline union).

func DecodeOperationIntent

func DecodeOperationIntent(data json.RawMessage) (OperationIntent, error)

DecodeOperationIntent decodes one intent, dispatching on its "kind" field.

type OperationIntentKind

type OperationIntentKind string

OperationIntentKind discriminates the intent union (pi: inline union on `intent.kind`).

const (
	OperationIntentRun        OperationIntentKind = "run"
	OperationIntentCompaction OperationIntentKind = "compaction"
	OperationIntentNavigation OperationIntentKind = "navigation"
)

type OperationMeta

type OperationMeta struct {
	OperationID string          `json:"operationId"`
	Lane        string          `json:"lane"`
	SourceTipID *string         `json:"sourceTipId"`
	StartedAt   int64           `json:"startedAt"`
	Intent      OperationIntent `json:"intent"`
}

OperationMeta records why and from where one operation started (pi: OperationMeta).

type OperationResultRecord

type OperationResultRecord struct {
	OperationID string `json:"operationId"`
	// Kind mirrors OperationMeta.intent.kind ("run" | "compaction" |
	// "navigation").
	Kind      OperationIntentKind `json:"kind"`
	Status    TerminalStatus      `json:"status"`
	Error     *OperationError     `json:"error,omitempty"`
	FromTipID *string             `json:"fromTipId"`
	TipID     *string             `json:"tipId"`
	StartedAt int64               `json:"startedAt"`
	EndedAt   int64               `json:"endedAt"`
}

OperationResultRecord is an immutable lane-lived observation record written by one terminal transaction (pi: OperationResultRecord).

type OperationScope

type OperationScope struct {
	Control                Control     `json:"control"`
	Settings               RunSettings `json:"settings"`
	LatestAssistantEntryID *string     `json:"latestAssistantEntryId"`
}

OperationScope is the uniform scope carried by every operation leaf (pi: OperationScope).

func OperationScopeOf

func OperationScopeOf(state OperationState) OperationScope

OperationScopeOf copies only the uniform operation scope when constructing a successor leaf (pi: operationScopeOf).

type OperationState

type OperationState interface {
	OperationAt() string
}

OperationState is the flat durable operation-state union (pi: OperationState): exactly 13 family-neutral dispatcher leaves.

type PendingEntry

type PendingEntry struct {
	Kind    string             `json:"type"` // pi discriminates on "type"
	Message agent.AgentMessage `json:"message,omitempty"`
	// CustomType is set only for "custom".
	CustomType string    `json:"customType,omitempty"`
	Payload    JsonValue `json:"payload,omitempty"`
}

PendingEntry is a message or custom payload queued for a later commit (pi: PendingEntry). Kind: "message" | "custom".

type PreparedCommit

type PreparedCommit struct {
	Writes []CommittedWrite
	Result struct {
		FirstSeq  int64   `json:"firstSeq"`
		Seqs      []int64 `json:"seqs"`
		Timestamp int64   `json:"timestamp"`
	}
}

PreparedCommit pairs the materialized writes with their commit result minus stats (pi: PreparedCommit).

func PrepareStorageCommit

func PrepareStorageCommit(writes []Write, firstSeq int64, timestamp int64) (PreparedCommit, error)

PrepareStorageCommit assigns consecutive sequences starting at firstSeq to every write (pi: prepareStorageCommit).

type ResolvedListReadOptions

type ResolvedListReadOptions struct {
	Cursor *ListCursor
	Order  string
	Limit  int
}

ResolvedListReadOptions is ListReadOptions with defaults applied (pi: ResolvedListReadOptions).

func ResolveListReadOptions

func ResolveListReadOptions(options *ListReadOptions) (ResolvedListReadOptions, error)

ResolveListReadOptions applies the list-read defaults (pi: resolveListReadOptions): limit default 1000, capped at 10000; order default "asc".

type ResultBoundary

type ResultBoundary struct {
	Kind string `json:"kind"`
	// ResumeAfter is set only for "resume_checkpoint".
	ResumeAfter *CheckpointData `json:"resumeAfter,omitempty"`
	// TargetID is set only for "commit_navigation".
	TargetID *string `json:"targetId,omitempty"`
	// Label is set only for "commit_navigation".
	Label *string `json:"label,omitempty"`
}

ResultBoundary is the result-boundary union of a summary task (pi: ResultBoundary). Kind: "resume_checkpoint" | "finish" | "commit_navigation".

type RetryWait

type RetryWait struct {
	NextAttempt  int    `json:"nextAttempt"`
	NotBefore    int64  `json:"notBefore"`
	ErrorMessage string `json:"errorMessage"`
}

RetryWait is the shared backoff data for every retry-wait leaf (pi: RetryWait).

type RunIntent

type RunIntent struct {
	Kind           OperationIntentKind `json:"kind"`
	PromptEntryIDs []string            `json:"promptEntryIds"`
}

func (RunIntent) OperationIntentKind

func (i RunIntent) OperationIntentKind() OperationIntentKind

type RunSettings

type RunSettings struct {
	// Compaction mirrors harness/compaction's CompactionSettings; kept as
	// json.RawMessage to avoid the import cycle (the excluded runtime owns
	// the typed shape).
	Compaction    json.RawMessage `json:"compaction"`
	SteeringMode  string          `json:"steeringMode"`
	FollowUpMode  string          `json:"followUpMode"`
	ToolExecution string          `json:"toolExecution"`
}

RunSettings is the uniform settings snapshot carried by every operation leaf (pi: RunSettings).

type Session

type Session interface {
	SessionReader
	GetMetadata() SessionMetadata
	IdGenerator() IdGenerator
	GetEntry(id string, ctx context.Context) (Entry, error)
	GetName(ctx context.Context) (*string, error)
	GetLabel(targetID string, ctx context.Context) (*string, error)
	FindEntries(query *EntryQuery, ctx context.Context) ([]Entry, error)
	FindEntry(query *EntryQuery, ctx context.Context) (Entry, error)
	Branch(name string, ctx context.Context) (Branch, error)
	CreateBranch(name string, at *string, ctx context.Context) (Branch, error)
	BeginMutation(ctx context.Context) (SessionMutation, error)
	// Mutate runs the callback holding the exclusive mutation line. Calling
	// public Session writers from inside the callback queues them behind it;
	// awaiting that nested writer deadlocks. Use the supplied mutator for
	// the callback's sole commit.
	Mutate(mutation SessionMutationCallback, ctx context.Context) (any, error)
	SetValue(address Value, next any, ctx context.Context) error
	DeleteValue(address Value, ctx context.Context) error
	AppendList(address ValueList, element any, ctx context.Context) error
	DeleteList(address ValueList, ctx context.Context) error
	SetName(name *string, ctx context.Context) error
	SetLabel(targetID string, label *string, ctx context.Context) error
	Close(ctx context.Context) error
}

Session is the durable session handle (pi: Session).

type SessionBranchExistsError

type SessionBranchExistsError struct{ Branch string }

SessionBranchExistsError: a requested branch already exists (pi: SessionBranchExistsError).

func (*SessionBranchExistsError) Error

func (e *SessionBranchExistsError) Error() string

type SessionContextBuildOptions

type SessionContextBuildOptions struct {
	EntryProjectors map[string]EntryProjector
}

SessionContextBuildOptions parameterizes context assembly (pi: SessionContextBuildOptions).

type SessionCreateOptions

type SessionCreateOptions struct {
	ID              *string `json:"id,omitempty"`
	ParentSessionID *string `json:"parentSessionId,omitempty"`
}

SessionCreateOptions parameterizes session creation (pi: SessionCreateOptions).

type SessionInvalidBranchError

type SessionInvalidBranchError struct {
	Branch string
	Reason string
}

SessionInvalidBranchError: a requested Branch name is invalid (pi: SessionInvalidBranchError).

func (*SessionInvalidBranchError) Error

func (e *SessionInvalidBranchError) Error() string

type SessionInvariantError

type SessionInvariantError struct{ Message string }

SessionInvariantError: durable session state is internally inconsistent and cannot be safely advanced (pi: SessionInvariantError).

func (*SessionInvariantError) Error

func (e *SessionInvariantError) Error() string

type SessionMetadata

type SessionMetadata struct {
	ID              string  `json:"id"`
	CreatedAt       int64   `json:"createdAt"` // Unix ms
	StorageVersion  int     `json:"storageVersion"`
	Cwd             *string `json:"cwd,omitempty"`
	ParentSessionID *string `json:"parentSessionId,omitempty"`
	// LegacyParentSessionPath survives when the legacy v3 parent file could
	// not be resolved to an id.
	LegacyParentSessionPath *string `json:"legacyParentSessionPath,omitempty"`
}

SessionMetadata identifies one session (pi: SessionMetadata).

type SessionMutation

type SessionMutation interface {
	SessionReader
	Commit(writes []Write, ctx context.Context) (CommitResult, error)
	End(ctx context.Context) error
}

SessionMutation is the exclusive keyless mutation barrier for one Session (pi: SessionMutation). Exactly zero or one commit attempt; End waits for the commit, invalidates the capability, and releases the barrier.

type SessionMutationCallback

type SessionMutationCallback func(mutator SessionMutator, ctx context.Context) (any, error)

SessionMutationCallback is pi's SessionMutationCallback<T>; the generic result collapses to any (Go closures capture typed results directly).

type SessionMutator

type SessionMutator = SessionMutation

SessionMutator is the callback-scoped mutation capability without the authority to release the barrier (pi: SessionMutator).

type SessionPendingAssistantMessageError

type SessionPendingAssistantMessageError struct{}

SessionPendingAssistantMessageError: a pending assistant message cannot be persisted as a session entry (pi: SessionPendingAssistantMessageError).

func (*SessionPendingAssistantMessageError) Error

type SessionReader

type SessionReader interface {
	GetEntries(ids []string, ctx context.Context) (map[string]Entry, error)
	GetStats(ctx context.Context) (SessionStats, error)
	GetValue(address Value, ctx context.Context) (*StoredValue, error)
	ScanValues(prefix Value, ctx context.Context) ([]StoredValue, error)
	ReadList(address ValueList, options *ListReadOptions, ctx context.Context) ([]ListElement, error)
	// ScanBranch scans a branch from an explicit entry while the capability
	// remains valid.
	ScanBranch(query StorageBranchScan, ctx context.Context) ([]Entry, error)
}

SessionReader is the read capability shared by Session and SessionMutation (pi: SessionReader).

type SessionRepo

type SessionRepo[TMetadata any, TCreate any, TList any] interface {
	Create(options TCreate, ctx context.Context) (Session, error)
	Open(metadata TMetadata, ctx context.Context) (Session, error)
	List(options TList, ctx context.Context) ([]TMetadata, error)
	Delete(metadata TMetadata, ctx context.Context) error
	Fork(source TMetadata, options ForkOptions, ctx context.Context) (Session, error)
}

SessionRepo creates, opens, lists, deletes, and forks sessions (pi: SessionRepo<TMetadata, TCreateOptions, TListOptions>). Go generic interfaces carry the instantiation: the memory backend instantiates SessionRepo[SessionMetadata, SessionCreateOptions, any] and the JSONL backend SessionRepo[JsonlSessionMetadata, JsonlSessionCreateOptions, *JsonlSessionListOptions] — exactly pi's concrete TMetadata shapes. Session itself stays non-generic (see the Session interface note): the concrete metadata reaches consumers through the repo's typed List return and StorageBackedSession.TypedMetadata.

type SessionStats

type SessionStats struct {
	MessageCount int         `json:"messageCount"`
	Usage        types.Usage `json:"usage"`
}

SessionStats is the aggregate usage ledger (pi: SessionStats).

type SessionUnknownTargetError

type SessionUnknownTargetError struct{ TargetID string }

SessionUnknownTargetError: a requested session entry target does not exist (pi: SessionUnknownTargetError).

func (*SessionUnknownTargetError) Error

func (e *SessionUnknownTargetError) Error() string

type StartingOperation

type StartingOperation struct {
	OperationScope
	At string `json:"at"` // "starting"
}

func (StartingOperation) OperationAt

func (s StartingOperation) OperationAt() string

type Storage

type Storage interface {
	Commit(writes []Write, ctx context.Context) (CommitResult, error)
	GetEntries(ids []string, ctx context.Context) (map[string]Entry, error)
	GetValue(address Value, ctx context.Context) (*StoredValue, error)
	ScanValues(prefix Value, ctx context.Context) ([]StoredValue, error)
	ReadList(address ValueList, options *ListReadOptions, ctx context.Context) ([]ListElement, error)
	ScanBranch(query StorageBranchScan, ctx context.Context) ([]Entry, error)
	ScanBranchStructure(query StorageBranchScan, ctx context.Context) ([]EntryStructure, error)
	ScanEntries(query EntryScan, ctx context.Context) ([]Entry, error)
	ScanUsage(query UsageScan, ctx context.Context) ([]UsageRow, error)
	GetStats(ctx context.Context) (SessionStats, error)
	Close(ctx context.Context) error
}

Storage is the durable session-state interface (pi: Storage). All methods take ctx (pi's `context: Context`); single-entry lookups return (nil, nil) for "not found".

type StorageBackedSession

type StorageBackedSession struct {
	// Metadata is the session's metadata (pi: readonly metadata). JSONL
	// consumers read JsonlSessionMetadata through this field plus a type
	// assertion (generic-parameter drop, see types.go).
	Metadata SessionMetadata
	// contains filtered or unexported fields
}

StorageBackedSession is the package-internal typed boundary shared by concrete session repositories (pi: StorageBackedSession).

func NewStorageBackedSession

func NewStorageBackedSession(metadata SessionMetadata, storage Storage, options StorageBackedSessionOptions) *StorageBackedSession

NewStorageBackedSession builds one session handle (pi: constructor).

func (*StorageBackedSession) AppendList

func (s *StorageBackedSession) AppendList(address ValueList, element any, ctx context.Context) error

func (*StorageBackedSession) BeginMutation

func (s *StorageBackedSession) BeginMutation(ctx context.Context) (SessionMutation, error)

BeginMutation acquires the exclusive mutation barrier (pi: beginMutation).

func (*StorageBackedSession) Branch

func (s *StorageBackedSession) Branch(name string, ctx context.Context) (Branch, error)

func (*StorageBackedSession) Close

func (s *StorageBackedSession) Close(ctx context.Context) error

func (*StorageBackedSession) CreateBranch

func (s *StorageBackedSession) CreateBranch(name string, at *string, ctx context.Context) (Branch, error)

func (*StorageBackedSession) DeleteList

func (s *StorageBackedSession) DeleteList(address ValueList, ctx context.Context) error

func (*StorageBackedSession) DeleteValue

func (s *StorageBackedSession) DeleteValue(address Value, ctx context.Context) error

func (*StorageBackedSession) FindEntries

func (s *StorageBackedSession) FindEntries(query *EntryQuery, ctx context.Context) ([]Entry, error)

func (*StorageBackedSession) FindEntry

func (s *StorageBackedSession) FindEntry(query *EntryQuery, ctx context.Context) (Entry, error)

func (*StorageBackedSession) GetEntries

func (s *StorageBackedSession) GetEntries(ids []string, ctx context.Context) (map[string]Entry, error)

func (*StorageBackedSession) GetEntry

func (s *StorageBackedSession) GetEntry(id string, ctx context.Context) (Entry, error)

func (*StorageBackedSession) GetLabel

func (s *StorageBackedSession) GetLabel(targetID string, ctx context.Context) (*string, error)

func (*StorageBackedSession) GetMetadata

func (s *StorageBackedSession) GetMetadata() SessionMetadata

GetMetadata returns the session metadata (pi: metadata field).

func (*StorageBackedSession) GetName

func (s *StorageBackedSession) GetName(ctx context.Context) (*string, error)

func (*StorageBackedSession) GetStats

func (*StorageBackedSession) GetValue

func (s *StorageBackedSession) GetValue(address Value, ctx context.Context) (*StoredValue, error)

func (*StorageBackedSession) IdGenerator

func (s *StorageBackedSession) IdGenerator() IdGenerator

IdGenerator returns the session's id generator (pi: idGenerator field).

func (*StorageBackedSession) Mutate

Mutate runs the callback holding the exclusive mutation line (pi: mutate).

func (*StorageBackedSession) ReadList

func (s *StorageBackedSession) ReadList(address ValueList, options *ListReadOptions, ctx context.Context) ([]ListElement, error)

func (*StorageBackedSession) ScanBranch

func (s *StorageBackedSession) ScanBranch(query StorageBranchScan, ctx context.Context) ([]Entry, error)

func (*StorageBackedSession) ScanValues

func (s *StorageBackedSession) ScanValues(prefix Value, ctx context.Context) ([]StoredValue, error)

func (*StorageBackedSession) SetLabel

func (s *StorageBackedSession) SetLabel(targetID string, label *string, ctx context.Context) error

func (*StorageBackedSession) SetName

func (s *StorageBackedSession) SetName(name *string, ctx context.Context) error

func (*StorageBackedSession) SetTypedMetadata

func (s *StorageBackedSession) SetTypedMetadata(metadata any)

SetTypedMetadata attaches the concrete metadata (package-internal wiring).

func (*StorageBackedSession) SetValue

func (s *StorageBackedSession) SetValue(address Value, next any, ctx context.Context) error

func (*StorageBackedSession) TypedMetadata

func (s *StorageBackedSession) TypedMetadata() any

TypedMetadata returns the concrete metadata shape (JsonlSessionMetadata for JSONL-backed sessions; nil otherwise).

type StorageBackedSessionOptions

type StorageBackedSessionOptions struct {
	MutationLine *MutationLine
	IDGenerator  IdGenerator
	OnClose      func()
}

StorageBackedSessionOptions parameterizes StorageBackedSession (pi: StorageBackedSessionOptions).

type StorageBranchScan

type StorageBranchScan struct {
	BranchScan
	Start string
}

StorageBranchScan is BranchScan with a mandatory start (pi: StorageBranchScan).

type StoredValue

type StoredValue struct {
	Address Value `json:"address"`
	Value   any   `json:"value"`
	Seq     int64 `json:"seq"`
}

StoredValue is one stored scalar with its committing sequence (pi: StoredValue<T>).

type SummaryContext

type SummaryContext struct {
	ResultEntryID string                `json:"resultEntryId"`
	Configuration LaneConfiguration     `json:"configuration"`
	StreamOptions json.RawMessage       `json:"streamOptions"`
	RetryPolicy   NormalizedRetryPolicy `json:"retryPolicy"`
}

SummaryContext carries the summary-generation inputs (pi: SummaryContext).

type SummaryDecidingOperation

type SummaryDecidingOperation struct {
	OperationScope
	Task SummaryTask `json:"task"`
	At   string      `json:"at"` // "summary.deciding"
}

func (SummaryDecidingOperation) OperationAt

func (s SummaryDecidingOperation) OperationAt() string

type SummaryEffectPendingOperation

type SummaryEffectPendingOperation struct {
	OperationScope
	Task           SummaryTask    `json:"task"`
	SummaryContext SummaryContext `json:"summaryContext"`
	Attempt        int            `json:"attempt"`
	// Request is { index, usageId }; nil when absent.
	Request  *EffectPendingRequest `json:"request,omitempty"`
	UsageIDs []string              `json:"usageIds"`
	At       string                `json:"at"` // "summary.effect_pending"
}

func (SummaryEffectPendingOperation) OperationAt

func (s SummaryEffectPendingOperation) OperationAt() string

type SummaryReadyOperation

type SummaryReadyOperation struct {
	OperationScope
	Task           SummaryTask    `json:"task"`
	SummaryContext SummaryContext `json:"summaryContext"`
	NextAttempt    int            `json:"nextAttempt"`
	At             string         `json:"at"` // "summary.ready"
}

func (SummaryReadyOperation) OperationAt

func (s SummaryReadyOperation) OperationAt() string

type SummaryRetryWaitOperation

type SummaryRetryWaitOperation struct {
	OperationScope
	Task           SummaryTask    `json:"task"`
	SummaryContext SummaryContext `json:"summaryContext"`
	RetryWait
	At string `json:"at"` // "summary.retry_wait"
}

func (SummaryRetryWaitOperation) OperationAt

func (s SummaryRetryWaitOperation) OperationAt() string

type SummaryTask

type SummaryTask struct {
	TaskID             string         `json:"taskId"`
	Reason             *string        `json:"reason,omitempty"`
	CustomInstructions *string        `json:"customInstructions,omitempty"`
	Boundary           ResultBoundary `json:"boundary"`
}

SummaryTask identifies one pending summary (pi: SummaryTask). Reason vocabulary: "manual" | "threshold" | "overflow".

type TerminalStatus

type TerminalStatus string

TerminalStatus is the terminal operation outcome vocabulary (pi: TerminalStatus).

const (
	TerminalStatusCompleted TerminalStatus = "completed"
	TerminalStatusDeclined  TerminalStatus = "declined"
	TerminalStatusAborted   TerminalStatus = "aborted"
	TerminalStatusFailed    TerminalStatus = "failed"
)

type ToolBatch

type ToolBatch struct {
	AssistantEntryID string            `json:"assistantEntryId"`
	Configuration    LaneConfiguration `json:"configuration"`
	TurnID           string            `json:"turnId"`
	Calls            []ToolCall        `json:"calls"`
}

ToolBatch is the nested child collection state machine of the tools leaf (pi: ToolBatch).

type ToolCall

type ToolCall struct {
	ToolCallSource
	Status string `json:"status"`
	// Replay is set only for "effect_pending" ("never" | "safe").
	Replay *string `json:"replay,omitempty"`
	// Terminate is set for "outcome_ready" and "completed".
	Terminate *bool `json:"terminate,omitempty"`
}

ToolCall is one durable tool-call state (pi: ToolCall). Status vocabulary: "planned" | "effect_pending" | "outcome_ready" | "completed".

type ToolCallSource

type ToolCallSource struct {
	SourceIndex   int    `json:"sourceIndex"`
	ResultEntryID string `json:"resultEntryId"`
}

ToolCallSource locates one tool call in its assistant message (pi: ToolCallSource). SourceIndex is the zero-based index in the assistant message's complete content array, not a filtered tool-call ordinal.

type ToolsOperation

type ToolsOperation struct {
	OperationScope
	Batch ToolBatch `json:"batch"`
	At    string    `json:"at"` // "tools"
}

func (ToolsOperation) OperationAt

func (s ToolsOperation) OperationAt() string

type UsageRow

type UsageRow struct {
	ID         string      `json:"id"`
	Seq        int64       `json:"seq"` // storage-assigned; zero on UsageWrite input
	Usage      types.Usage `json:"usage"`
	EntryID    *string     `json:"entryId,omitempty"`
	Adjustment bool        `json:"adjustment"`
	Details    JsonValue   `json:"details,omitempty"`
}

UsageRow is one usage ledger row (pi: UsageRow).

type UsageScan

type UsageScan struct {
	FromSeq *int64 `json:"fromSeq,omitempty"`
	ToSeq   *int64 `json:"toSeq,omitempty"`
	Order   string `json:"order,omitempty"`
	Limit   *int   `json:"limit,omitempty"`
}

UsageScan queries usage rows by sequence window (pi: UsageScan).

type UsageWrite

type UsageWrite struct {
	Row UsageRow `json:"row"`
}

UsageWrite appends one usage row (pi: UsageWrite).

func InsertUsage

func InsertUsage(row UsageRow) UsageWrite

InsertUsage wraps one usage row (without seq) as a usage write (pi: insertUsage).

type Value

type Value struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	// contains filtered or unexported fields
}

Value is one scalar storage address (pi: Value<T>). Namespace + Key form the physical key; kind is always "value".

func BranchTip

func BranchTip(branch string) Value

BranchTip is the tip value of one branch (pi: branchTip; Value<string | null>).

func BranchTipPrefix

func BranchTipPrefix() Value

BranchTipPrefix is the branch-tip namespace prefix for scans (pi: branchTipInventoryPrefix).

func EntryLabel

func EntryLabel(entryID string) Value

EntryLabel is one entry's label (pi: entryLabel; Value<string>).

func LaneConfig

func LaneConfig(lane string) Value

LaneConfig is one lane's durable configuration (pi: laneConfig; Value<LaneConfiguration>).

func LaneStateAddress

func LaneStateAddress(lane string) Value

LaneState is one lane's idle/queueing state (pi: laneState; Value<LaneState>).

func MustValue

func MustValue(namespace, key string) Value

MustValue is NewValue panicking on invalid addresses; the well-known helpers below only receive compile-time-constant namespaces.

func NewValue

func NewValue(namespace, key string) (Value, error)

NewValue builds a scalar address (pi: value<T>(namespace, key)).

func OperationMetaAddress

func OperationMetaAddress(operationID string) Value

OperationMetaAddress is one operation's meta (pi: operationMeta; Value<OperationMeta>).

func OperationPreparation

func OperationPreparation(operationID, taskID string) Value

OperationPreparation is one structural task's preparation (pi: operationPreparation; Value<DurableStructuralPreparation>).

func OperationPreparationPrefix

func OperationPreparationPrefix(operationID string) Value

OperationPreparationPrefix is the preparation scan prefix (pi: operationPreparationPrefix).

func OperationResult

func OperationResult(operationID string) Value

OperationResult is one terminal operation record (pi: operationResult; Value<OperationResultRecord>).

func OperationStateAddress

func OperationStateAddress(operationID string) Value

OperationStateAddress is one operation's durable state (pi: operationState; Value<OperationState>).

func OperationToolArgs

func OperationToolArgs(operationID, stepID string, sourceIndex int) Value

OperationToolArgs is one tool call's effective arguments (pi: operationToolArgs; Value<Record<string, JsonValue>>).

func OperationToolArgsPrefix

func OperationToolArgsPrefix(operationID, stepID string) Value

OperationToolArgsPrefix is the tool-args scan prefix (pi: operationToolArgsPrefix).

func OperationToolMemo

func OperationToolMemo(operationID, invocationID, name string) Value

OperationToolMemo is one tool invocation's memo (pi: operationToolMemo; Value<JsonValue>).

func OperationToolMemoPrefix

func OperationToolMemoPrefix(operationID, invocationID string) Value

OperationToolMemoPrefix is the tool-memo scan prefix (pi: operationToolMemoPrefix).

func PendingEntryAddress

func PendingEntryAddress(entryID string) Value

PendingEntryAddress is one pending entry payload (pi: pendingEntry; Value<PendingEntry>).

func PendingToolOutput

func PendingToolOutput(operationID, invocationID string) Value

PendingToolOutput is one pending tool output (pi: pendingToolOutput; Value<AgentToolResult>).

func PendingToolOutputPrefix

func PendingToolOutputPrefix(operationID string) Value

PendingToolOutputPrefix is the pending-tool-output scan prefix (pi: pendingToolOutputPrefix).

func (Value) Kind

func (v Value) Kind() ValueKind

Kind reports the address kind.

type ValueDeleteWrite

type ValueDeleteWrite struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
}

ValueDeleteWrite deletes one scalar (pi: ValueDeleteWrite).

func DeleteValue

func DeleteValue(address Value) ValueDeleteWrite

DeleteValue builds a scalar delete write (pi: deleteValue).

func (ValueDeleteWrite) Op

func (w ValueDeleteWrite) Op() string

Op returns the value operation.

type ValueKind

type ValueKind string

ValueKind discriminates the two address kinds.

const (
	ValueKindValue ValueKind = "value"
	ValueKindList  ValueKind = "list"
)

type ValueList

type ValueList struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	// contains filtered or unexported fields
}

ValueList is one list storage address (pi: ValueList<T>).

func MustList

func MustList(namespace, key string) ValueList

MustList is NewList panicking on invalid addresses.

func NewList

func NewList(namespace, key string) (ValueList, error)

NewList builds a list address (pi: list<T>(namespace, key)).

func PendingAssistantFrames

func PendingAssistantFrames(operationID, responseEntryID string) ValueList

PendingAssistantFrames is one response's pending assistant frames (pi: pendingAssistantFrames; ValueList<AssistantMessageFrame>).

func (ValueList) Kind

func (v ValueList) Kind() ValueKind

Kind reports the address kind.

type ValueSetWrite

type ValueSetWrite struct {
	Namespace string `json:"namespace"`
	Key       string `json:"key"`
	Value     any    `json:"value"`
}

ValueSetWrite sets one scalar (pi: ValueSetWrite).

func SetValue

func SetValue(address Value, next any) ValueSetWrite

SetValue builds a scalar set write (pi: setValue).

func (ValueSetWrite) Op

func (w ValueSetWrite) Op() string

Op returns the value operation.

type Write

type Write interface {
	// contains filtered or unexported methods
}

Write is one mutation inside a transaction (pi: Write union). Concrete kinds: *EntryWrite, *UsageWrite, *ValueSetWrite, *ValueDeleteWrite, *ListAppendWrite, *ListDeleteWrite.

Directories

Path Synopsis
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header.
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header.
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination).
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination).

Jump to

Keyboard shortcuts

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