transcript

package
v0.6.16 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package transcript defines the durable, append-only history of a coding session. The model-facing message list is a projection of these entries.

Index

Constants

View Source
const (
	// ToolNotStarted means no durable dispatch intent exists for an interrupted
	// assistant tool request.
	ToolNotStarted = "TOOL_NOT_STARTED"
	// ToolOutcomeUnknown means dispatch became possible but no terminal result
	// was durably recorded.
	ToolOutcomeUnknown = "TOOL_OUTCOME_UNKNOWN"
)
View Source
const (
	CurrentVersion = 8
)
View Source
const LifecycleInterruptedReason = "process_interrupted"
View Source
const ModelContextProjectionKey = "model-context"
View Source
const SessionProjectionKey = "session"

Variables

View Source
var (
	// ErrForkMessageNotFound means the requested message ID is not in the transcript.
	ErrForkMessageNotFound = errors.New("transcript: fork message not found")
	// ErrInvalidForkBoundary means the requested fork would produce invalid context.
	ErrInvalidForkBoundary = errors.New("transcript: invalid fork boundary")
)

Functions

func BuildContext

func BuildContext(entries []Entry) ([]agent.AgentMessage, error)

BuildContext projects the linear log into the messages sent to the model. Only the newest compaction boundary applies: its summary replaces the old prefix while original messages at and after FirstKeptEntryID remain verbatim.

func NewID

func NewID() string

func RecoverSession added in v0.6.14

func RecoverSession(entries []Entry) (*SessionValidator, []Entry, error)

RecoverSession validates one committed event prefix, synthesizes repairs for its interrupted tail, and returns a validator advanced through those repairs. The prefix is replayed once and is never mutated.

func RecoverSessionWithProjections added in v0.6.14

func RecoverSessionWithProjections(
	entries []Entry,
	projections *ProjectionRegistry,
) (*SessionValidator, []Entry, error)

RecoverSessionWithProjections performs the recovery replay while eagerly driving registered read models over the same committed prefix and repairs.

func SecurePrivatePermissions added in v0.6.8

func SecurePrivatePermissions(dir string) error

SecurePrivatePermissions enforces private modes for every transcript JSONL file in dir, including files that remain lazily unloaded.

Types

type Compaction

type Compaction struct {
	Summary           string    `json:"summary"`
	FirstKeptEntryID  string    `json:"firstKeptEntryId"`
	TokensBefore      int64     `json:"tokensBefore"`
	TokensAfter       int64     `json:"tokensAfter"`
	ReadFiles         []string  `json:"readFiles,omitempty"`
	ModifiedFiles     []string  `json:"modifiedFiles,omitempty"`
	Provider          string    `json:"provider,omitempty"`
	Model             string    `json:"model,omitempty"`
	ResponseModel     string    `json:"responseModel,omitempty"`
	ResponseID        string    `json:"responseId,omitempty"`
	Usage             llm.Usage `json:"usage,omitempty"`
	ResponseTimestamp time.Time `json:"responseTimestamp,omitempty"`
}

Compaction records a summary boundary without deleting the entries it summarizes. FirstKeptEntryID points at the first original message retained in the active model context.

type ContextAttachment

type ContextAttachment struct {
	AttachmentID string `json:"attachmentId"`
	Epoch        uint64 `json:"epoch"`
	Kind         string `json:"kind"`
	Placement    string `json:"placement"`
	Path         string `json:"path,omitempty"`
	Revision     string `json:"revision"`
	Rendered     string `json:"rendered"`
}

ContextAttachment records one product-generated model-context block without representing it as a user-authored conversation message. Epoch increments when a session process rebuilds its context snapshot. Placement describes how the model-input projector positions the rendered block.

type Entry

type Entry struct {
	Seq           int64
	ID            string
	Timestamp     time.Time
	Type          EntryType
	Message       agent.AgentMessage
	ToolCall      *ToolCall
	ToolOutcome   *ToolOutcome
	Context       *ContextAttachment
	Compaction    *Compaction
	Lifecycle     *Lifecycle
	RequestHeader *RequestHeader
	PlanMode      *PlanMode
}

Entry is one item in the session's linear, append-only history. Seq is -1 while an entry is being prepared and becomes contiguous when it commits.

func Fork added in v0.6.11

func Fork(entries []Entry, messageID string, mode ForkMode, replacementText string) ([]Entry, error)

Fork returns a transcript prefix at a visible message boundary without modifying the source entries. Editing replaces the selected user message with a newly identified message; branching after an assistant preserves the selected completed response.

func NewCompaction

func NewCompaction(compact Compaction) Entry

func NewContext

func NewContext(context ContextAttachment) Entry

func NewMessage

func NewMessage(message agent.AgentMessage) Entry

func NewPlanMode added in v0.6.15

func NewPlanMode(active bool) Entry

func NewRequestHeader added in v0.6.15

func NewRequestHeader(header RequestHeader) Entry

NewRequestHeader creates an unsequenced durable request definition. The sequencer assigns InputSeq to the immediately preceding committed entry.

func NewRunEnd added in v0.6.14

func NewRunEnd(runID string, status LifecycleStatus, reason string) Entry

func NewRunStart added in v0.6.14

func NewRunStart(runID string) Entry

func NewStepEnd added in v0.6.14

func NewStepEnd(
	runID, turnID, stepID string,
	status LifecycleStatus,
	reason string,
) Entry

func NewStepStart added in v0.6.14

func NewStepStart(runID, turnID, stepID string) Entry

func NewToolCall added in v0.6.14

func NewToolCall(call ToolCall) Entry

func NewToolOutcome added in v0.6.8

func NewToolOutcome(outcome ToolOutcome) Entry

func NewTurnEnd added in v0.6.14

func NewTurnEnd(runID, turnID string, status LifecycleStatus, reason string) Entry

func NewTurnStart added in v0.6.14

func NewTurnStart(runID, turnID string) Entry

func SequenceEntries added in v0.6.14

func SequenceEntries(entries []Entry, firstSeq int64) ([]Entry, error)

SequenceEntries returns a detached batch numbered from firstSeq.

func (Entry) MarshalJSON

func (e Entry) MarshalJSON() ([]byte, error)

func (*Entry) UnmarshalJSON

func (e *Entry) UnmarshalJSON(data []byte) error

func (Entry) Validate

func (e Entry) Validate() error

type EntryType

type EntryType string
const (
	MessageEntry       EntryType = "message"
	ToolCallEntry      EntryType = "tool_call"
	ToolOutcomeEntry   EntryType = "tool_outcome"
	ContextEntry       EntryType = "context"
	CompactionEntry    EntryType = "compaction"
	RunStartEntry      EntryType = "run/start"
	RunEndEntry        EntryType = "run/end"
	TurnStartEntry     EntryType = "turn/start"
	TurnEndEntry       EntryType = "turn/end"
	StepStartEntry     EntryType = "step/start"
	StepEndEntry       EntryType = "step/end"
	RequestHeaderEntry EntryType = "request/header"
	PlanModeEntry      EntryType = "plan/mode"
)

type ForkMode added in v0.6.11

type ForkMode string

ForkMode selects the visible message boundary retained in a fork.

const (
	// ForkBeforeUser replaces the selected user message and drops later entries.
	ForkBeforeUser ForkMode = "before_user"
	// ForkAfterAssistant keeps the selected completed assistant response.
	ForkAfterAssistant ForkMode = "after_assistant"
)
type Header struct {
	Type    string `json:"type"`
	Version int    `json:"version"`
}

Header is the first line of a session log.

func NewHeader

func NewHeader() Header

type JSONL

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

JSONL persists a session log: one header followed by typed append-only entries.

func NewJSONL

func NewJSONL(path string) *JSONL

func (*JSONL) Append

func (s *JSONL) Append(_ context.Context, entries ...Entry) error

func (*JSONL) Load

func (s *JSONL) Load(_ context.Context) ([]Entry, error)

func (*JSONL) Replace added in v0.6.11

func (s *JSONL) Replace(_ context.Context, entries []Entry) error

Replace atomically installs entries as the complete session log. It is used for explicit history rewrites while the owning session is idle.

type Lifecycle added in v0.6.14

type Lifecycle struct {
	RunID  string          `json:"runId"`
	TurnID string          `json:"turnId,omitempty"`
	StepID string          `json:"stepId,omitempty"`
	Status LifecycleStatus `json:"status,omitempty"`
	Reason string          `json:"reason,omitempty"`
}

Lifecycle identifies one durable Run, Turn, or Step boundary. Entry.Type supplies the boundary kind; parent IDs make ownership explicit and stable.

type LifecycleStatus added in v0.6.14

type LifecycleStatus string
const (
	LifecycleCompleted   LifecycleStatus = "completed"
	LifecycleFailed      LifecycleStatus = "failed"
	LifecycleCancelled   LifecycleStatus = "cancelled"
	LifecycleInterrupted LifecycleStatus = "interrupted"
)

type Memory

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

Memory is an in-process Store useful for tests and ephemeral sessions.

func (*Memory) Append

func (m *Memory) Append(_ context.Context, entries ...Entry) error

func (*Memory) Load

func (m *Memory) Load(context.Context) ([]Entry, error)

type ModelContextProjection added in v0.6.15

type ModelContextProjection struct {
	AppliedEntries          int
	AsOfSeq                 int64
	Messages                []agent.AgentMessage
	ActiveCompactionEntryID string
	FirstKeptEntryID        string
}

ModelContextProjection is the active canonical message context at one committed transcript sequence. Product-generated context attachments are projected separately by the engine at provider-request time.

func ProjectModelContext added in v0.6.15

func ProjectModelContext(entries []Entry) (*ModelContextProjection, error)

ProjectModelContext replays a complete committed transcript through the same projection unit used by live sessions.

type ModelContextProjectionUnit added in v0.6.15

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

ModelContextProjectionUnit incrementally maintains the same canonical message view produced by BuildContext. It retains original messages so a later compaction can select any validated preceding message as its boundary.

func NewModelContextProjectionUnit added in v0.6.15

func NewModelContextProjectionUnit() *ModelContextProjectionUnit

func (*ModelContextProjectionUnit) ApplyProjection added in v0.6.15

func (u *ModelContextProjectionUnit) ApplyProjection(event ProjectionEvent)

func (*ModelContextProjectionUnit) ProjectionKey added in v0.6.15

func (*ModelContextProjectionUnit) ProjectionKey() string

func (*ModelContextProjectionUnit) Snapshot added in v0.6.15

func (*ModelContextProjectionUnit) SnapshotProjection added in v0.6.15

func (u *ModelContextProjectionUnit) SnapshotProjection() (any, error)

type PlanMode added in v0.6.15

type PlanMode struct {
	Active bool `json:"active"`
}

PlanMode records whether planning policy applies to subsequent model requests. The latest value wins across resume and fork.

type PreparedAppend added in v0.6.14

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

PreparedAppend is a validated batch-local reducer delta. Commit installs it into its originating SessionValidator and must be called at most once.

func (*PreparedAppend) Commit added in v0.6.14

func (p *PreparedAppend) Commit()

Commit installs a prepared delta. A stale or repeated commit is a caller programming error; journal serialization keeps production commits ordered.

type ProjectedCompaction added in v0.6.14

type ProjectedCompaction struct {
	EntryID    string
	EntryIndex int
	RunID      string
	TurnID     string
	StepID     string
	Compaction Compaction
}

ProjectedCompaction records a durable summary boundary and its lifecycle ownership without applying model-context presentation rules.

type ProjectedContext added in v0.6.14

type ProjectedContext struct {
	EntryID    string
	EntryIndex int
	RunID      string
	TurnID     string
	StepID     string
	Attachment ContextAttachment
}

ProjectedContext associates one durable hidden context attachment with the lifecycle boundaries open when it was committed.

type ProjectedLifecycle added in v0.6.14

type ProjectedLifecycle struct {
	RunID  string
	TurnID string
	StepID string
}

ProjectedLifecycle identifies the currently open durable boundaries. An empty value means the committed prefix is at a clean session boundary.

type ProjectedMessage added in v0.6.14

type ProjectedMessage struct {
	EntryID    string
	EntryIndex int
	Timestamp  time.Time
	RunID      string
	TurnID     string
	StepID     string
	Message    agent.AgentMessage
}

ProjectedMessage associates a durable model message with the lifecycle boundaries open at its position. User and steering messages may have no StepID.

type ProjectedProviderRequest added in v0.6.15

type ProjectedProviderRequest struct {
	EntryID    string
	EntryIndex int
	EntrySeq   int64
	Header     RequestHeader
}

ProjectedProviderRequest associates one complete durable request definition with its checkpoint sequence and open lifecycle scope.

type ProjectedRun added in v0.6.14

type ProjectedRun struct {
	ID              string
	StartEntryID    string
	EndEntryID      string
	StartEntryIndex int
	EndEntryIndex   int
	StartedAt       time.Time
	CompletedAt     time.Time
	Status          LifecycleStatus
	Reason          string
	Turns           []ProjectedTurn
}

ProjectedRun is one run reconstructed from explicit lifecycle boundaries.

type ProjectedStep added in v0.6.14

type ProjectedStep struct {
	ID              string
	RunID           string
	TurnID          string
	StartEntryID    string
	EndEntryID      string
	StartEntryIndex int
	EndEntryIndex   int
	StartedAt       time.Time
	CompletedAt     time.Time
	Status          LifecycleStatus
	Reason          string
}

ProjectedStep is one assistant request-and-tools cycle inside a turn.

type ProjectedToolCall added in v0.6.14

type ProjectedToolCall struct {
	ToolCallID string
	ToolName   string
	Arguments  json.RawMessage
	RunID      string
	TurnID     string
	StepID     string

	AssistantMessageEntryID    string
	AssistantMessageEntryIndex int
	DispatchEntryID            string
	DispatchEntryIndex         int
	ResultMessageEntryID       string
	ResultEntryIndex           int
	OutcomeEntryID             string
	OutcomeEntryIndex          int
	Outcome                    *ToolOutcome
}

ProjectedToolCall joins the assistant request, optional durable dispatch intent, model-facing result, and optional product-facing outcome.

type ProjectedTurn added in v0.6.14

type ProjectedTurn struct {
	ID              string
	RunID           string
	StartEntryID    string
	EndEntryID      string
	StartEntryIndex int
	EndEntryIndex   int
	StartedAt       time.Time
	CompletedAt     time.Time
	Status          LifecycleStatus
	Reason          string
	Steps           []ProjectedStep
}

ProjectedTurn is one claimed unit of user or follow-up intent inside a run.

type ProjectionEvent added in v0.6.14

type ProjectionEvent struct {
	Entry      Entry
	EntryIndex int
	Scope      ProjectedLifecycle
	// contains filtered or unexported fields
}

ProjectionEvent is one validated event at its committed transcript position. Entry and Scope are immutable inputs to registered projections.

type ProjectionRegistry added in v0.6.14

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

ProjectionRegistry eagerly drives registered units over committed events. It is intentionally lock-free; the owning session journal serializes commit and snapshot access.

func NewProjectionRegistry added in v0.6.14

func NewProjectionRegistry() *ProjectionRegistry

func (*ProjectionRegistry) Register added in v0.6.14

func (r *ProjectionRegistry) Register(unit ProjectionUnit) error

Register adds a unit before replay or live events begin.

func (*ProjectionRegistry) Snapshot added in v0.6.14

func (r *ProjectionRegistry) Snapshot() (ProjectionSnapshot, error)

Snapshot returns detached values from the same committed sequence.

func (*ProjectionRegistry) SnapshotKey added in v0.6.15

func (r *ProjectionRegistry) SnapshotKey(key string) (ProjectionSnapshot, error)

SnapshotKey returns one detached projection at the registry's committed watermark without forcing unrelated units to clone their state.

type ProjectionSnapshot added in v0.6.14

type ProjectionSnapshot struct {
	AsOfSeq int64
	Values  map[string]any
}

ProjectionSnapshot is one consistent read cut across all registered units.

type ProjectionUnit added in v0.6.14

type ProjectionUnit interface {
	ProjectionKey() string
	ApplyProjection(ProjectionEvent)
	SnapshotProjection() (any, error)
}

ProjectionUnit is one synchronous read model driven by every committed session event. ApplyProjection must be total: all fallible preparation is completed before persistence and the commit boundary. SnapshotProjection must return a value detached from the unit's live state.

type ProviderRequest added in v0.6.15

type ProviderRequest struct {
	HeaderEntryID  string
	HeaderEntrySeq int64
	Header         RequestHeader
	Input          llm.Context
	Options        llm.StreamOptions
}

ProviderRequest is a request reconstructed only from committed transcript facts. HeaderEntrySeq is the checkpoint watermark; InputSeq is the prefix from which Input.Messages was derived.

func ReconstructCommittedProviderRequest added in v0.6.15

func ReconstructCommittedProviderRequest(
	session *SessionProjection,
	modelContext *ModelContextProjection,
	providerRequestID string,
) (ProviderRequest, error)

ReconstructCommittedProviderRequest rebuilds the request at the current shared projection watermark. It is the online counterpart to the complete replay API and does not scan transcript entries.

func ReconstructProviderRequest added in v0.6.15

func ReconstructProviderRequest(
	entries []Entry,
	providerRequestID string,
) (ProviderRequest, error)

ReconstructProviderRequest rebuilds one provider-neutral request using only the committed transcript. Diagnostic snapshots and live agent state are not consulted.

func ReconstructProviderRequestFromProjection added in v0.6.16

func ReconstructProviderRequestFromProjection(
	entries []Entry,
	projection *SessionProjection,
	providerRequestID string,
) (ProviderRequest, error)

ReconstructProviderRequestFromProjection rebuilds one historical request while reusing a SessionProjection produced from the same committed entries. This avoids replaying the complete session for every request in a diagnostic trace.

type RequestAttachment added in v0.6.15

type RequestAttachment struct {
	AttachmentID string `json:"attachmentId"`
	MessageIndex int    `json:"messageIndex"`
}

RequestAttachment places one previously committed context attachment in the final provider message list. MessageIndex is counted after all attachments have been inserted.

type RequestHeader added in v0.6.15

type RequestHeader struct {
	ProviderRequestID       string                 `json:"providerRequestId"`
	RunID                   string                 `json:"runId"`
	TurnID                  string                 `json:"turnId"`
	StepID                  string                 `json:"stepId"`
	Provider                string                 `json:"provider"`
	Model                   string                 `json:"model"`
	Protocol                llm.Protocol           `json:"protocol"`
	ThinkingLevel           llm.ModelThinkingLevel `json:"thinkingLevel,omitempty"`
	SystemPrompt            string                 `json:"systemPrompt,omitempty"`
	Tools                   []llm.ToolDefinition   `json:"tools,omitempty"`
	Options                 RequestOptions         `json:"options,omitempty"`
	InputSeq                int64                  `json:"inputSeq"`
	ActiveCompactionEntryID string                 `json:"activeCompactionEntryId,omitempty"`
	Attachments             []RequestAttachment    `json:"attachments,omitempty"`
}

RequestHeader is the complete provider-neutral definition of one model request. Transport credentials, endpoints, headers, callbacks, and retry policy are deliberately absent.

func (RequestHeader) StreamOptions added in v0.6.15

func (header RequestHeader) StreamOptions() (llm.StreamOptions, error)

StreamOptions restores the semantic options represented by this header. All transport and observer fields remain empty by construction.

type RequestOptions added in v0.6.15

type RequestOptions struct {
	Temperature     *float64                `json:"temperature,omitempty"`
	MaxTokens       int64                   `json:"maxTokens,omitempty"`
	ProtocolOptions *RequestProtocolOptions `json:"protocolOptions,omitempty"`
}

RequestOptions contains only settings that affect the provider-neutral logical request. Attempt policy and transport configuration are not durable conversation facts.

func CaptureRequestOptions added in v0.6.15

func CaptureRequestOptions(
	protocol llm.Protocol,
	tools []llm.ToolDefinition,
	options llm.StreamOptions,
) (RequestOptions, error)

CaptureRequestOptions extracts the semantic, serializable subset of stream options. RewriteRequest is rejected because it can change the logical body after the durable request has been reconstructed.

type RequestProtocolOptions added in v0.6.15

type RequestProtocolOptions struct {
	ThinkingDisplay llm.ThinkingDisplay `json:"thinkingDisplay,omitempty"`
	ToolChoice      *RequestToolChoice  `json:"toolChoice,omitempty"`
}

RequestProtocolOptions is the closed, secret-free durable form of the built-in protocol extensions.

type RequestToolChoice added in v0.6.15

type RequestToolChoice struct {
	Mode string `json:"mode,omitempty"`
	Name string `json:"name,omitempty"`
}

RequestToolChoice represents either a protocol-native mode or one named tool. Exactly one of Mode and Name may be set.

type SessionProjection added in v0.6.14

type SessionProjection struct {
	AppliedEntries   int
	AsOfSeq          int64
	Runs             []ProjectedRun
	Messages         []ProjectedMessage
	ToolCalls        []ProjectedToolCall
	Contexts         []ProjectedContext
	Compactions      []ProjectedCompaction
	ProviderRequests []ProjectedProviderRequest
	Open             ProjectedLifecycle
}

SessionProjection is a deterministic snapshot of one committed transcript prefix. AsOfSeq identifies the last event included in the view.

func ProjectSession added in v0.6.14

func ProjectSession(entries []Entry) (*SessionProjection, error)

ProjectSession folds entries once, in committed order, through the same registered projection used by live sessions. It remains the deterministic replay entry point for offline diagnostics and tests.

type SessionProjectionUnit added in v0.6.14

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

SessionProjectionUnit is the registered, incrementally maintained session read model.

func NewSessionProjectionUnit added in v0.6.14

func NewSessionProjectionUnit() *SessionProjectionUnit

func (*SessionProjectionUnit) ApplyProjection added in v0.6.14

func (u *SessionProjectionUnit) ApplyProjection(event ProjectionEvent)

func (*SessionProjectionUnit) ProjectionKey added in v0.6.14

func (*SessionProjectionUnit) ProjectionKey() string

func (*SessionProjectionUnit) Snapshot added in v0.6.14

func (u *SessionProjectionUnit) Snapshot() (*SessionProjection, error)

func (*SessionProjectionUnit) SnapshotProjection added in v0.6.14

func (u *SessionProjectionUnit) SnapshotProjection() (any, error)

type SessionValidator added in v0.6.14

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

SessionValidator owns the canonical reducer for one committed event prefix. PrepareAppend validates against a batch-local delta that callers commit only after the same entries are durable.

func ValidateSession added in v0.6.14

func ValidateSession(entries []Entry) (*SessionValidator, error)

ValidateSession replays a complete committed event prefix.

func (*SessionValidator) NextSeq added in v0.6.14

func (v *SessionValidator) NextSeq() int64

NextSeq is the sequence required for the next committed entry.

func (*SessionValidator) PrepareAppend added in v0.6.14

func (v *SessionValidator) PrepareAppend(entries []Entry) (*PreparedAppend, error)

PrepareAppend validates entries without changing the committed cursor.

type Store

type Store interface {
	Load(ctx context.Context) ([]Entry, error)
	Append(ctx context.Context, entries ...Entry) error
}

Store persists typed transcript entries. Compaction is an appended entry; it never replaces or removes original messages. A nil Store disables persistence.

type ToolCall added in v0.6.14

type ToolCall struct {
	ToolCallID string          `json:"toolCallId"`
	ToolName   string          `json:"toolName"`
	Arguments  json.RawMessage `json:"arguments"`
}

ToolCall is a durable dispatch intent. Its presence means validation and authorization completed and the tool body may have started. Arguments are the normalized JSON value passed to the tool, not a presentation summary.

type ToolOutcome added in v0.6.8

type ToolOutcome struct {
	ToolCallID string                  `json:"toolCallId"`
	Status     agent.ToolOutcomeStatus `json:"status"`
	ErrorCode  string                  `json:"errorCode,omitempty"`
	ExitCode   *int                    `json:"exitCode,omitempty"`
	DataKind   string                  `json:"dataKind,omitempty"`
	Data       json.RawMessage         `json:"data,omitempty"`
}

ToolOutcome records the product-facing result associated with one model- visible tool result. Data stays provider-neutral and is decoded by the engine according to DataKind.

Jump to

Keyboard shortcuts

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