Help us shape the future of Go! Take the 2026 Go Developer Survey

harness

package
v0.19.3 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const BranchSummaryPreamble = `The user explored a different conversation branch before returning here.
Summary of that exploration:

`
View Source
const BranchSummaryPrompt = `` /* 689-byte string literal not displayed */
View Source
const SummarizationPrompt = `` /* 879-byte string literal not displayed */
View Source
const SummarizationSystemPrompt = `` /* 310-byte string literal not displayed */
View Source
const TurnPrefixSummarizationPrompt = `` /* 664-byte string literal not displayed */
View Source
const UpdateSummarizationPrompt = `` /* 1257-byte string literal not displayed */

Variables

View Source
var DefaultCompactionSettings = CompactionSettings{
	Enabled:          true,
	ReserveTokens:    16384,
	KeepRecentTokens: 20000,
}

Functions

func CalculateContextTokens

func CalculateContextTokens(usage ai.Usage) int64

func CompleteSimpleWithRetries

func CompleteSimpleWithRetries(
	ctx context.Context,
	complete CompleteFunc,
	model *ai.Model,
	request ai.Context,
	options *ai.SimpleStreamOptions,
	retry *ai.RetryPolicy,
	callbacks *ai.RetryCallbacks,
) (*ai.AssistantMessage, error)

CompleteSimpleWithRetries applies the shared assistant retry policy to one harness completion request.

func EstimateTokens

func EstimateTokens(message engine.AgentMessage) int64

func FindTurnStartIndex

func FindTurnStartIndex(entries []SessionEntry, entryIndex, startIndex int) int

func FormatFileOperations

func FormatFileOperations(readFiles, modifiedFiles []string) string

func FormatTimestamp added in v0.19.1

func FormatTimestamp(value time.Time) string

FormatTimestamp writes value as Date.toISOString does.

func GenerateSummary

func GenerateSummary(
	ctx context.Context,
	messages engine.AgentMessages,
	model *ai.Model,
	complete CompleteFunc,
	reserveTokens int64,
	customInstructions string,
	previousSummary *string,
	thinkingLevel ai.ModelThinkingLevel,
) (string, error)

func MarshalSessionJSONL

func MarshalSessionJSONL(storage SessionStorage, cwd string) ([]byte, error)

MarshalSessionJSONL serializes a non-byte-backed session using the harness object insertion order. cwd supplies the coding-session context omitted by generic in-memory harness metadata.

func MarshalSessionTreeEntry

func MarshalSessionTreeEntry(entry SessionTreeEntry) ([]byte, error)

MarshalSessionTreeEntry serializes one entry with upstream field order. Exported for module embedders; not referenced inside this repo.

func MessageRole added in v0.19.1

func MessageRole(message engine.AgentMessage) string

MessageRole is engine.MessageRole without encoding this package's messages.

func SanitizeSessionName added in v0.19.1

func SanitizeSessionName(name string) string

SanitizeSessionName folds each run of line breaks into one space and trims.

func SerializeConversation

func SerializeConversation(messages engine.AgentMessages) string

func SessionDirName added in v0.19.1

func SessionDirName(cwd string) string

SessionDirName is the directory name of the sessions run in cwd.

func SessionFileName added in v0.19.1

func SessionFileName(createdAt, id string) string

SessionFileName is the file name of a session created at createdAt.

func ShouldCompact

func ShouldCompact(contextTokens int64, contextWindow float64, settings CompactionSettings) bool

Types

type BashExecutionMessage

type BashExecutionMessage struct {
	Role               string  `json:"role"`
	Command            string  `json:"command"`
	Output             string  `json:"output"`
	ExitCode           *int    `json:"exitCode"`
	Cancelled          bool    `json:"cancelled"`
	Truncated          bool    `json:"truncated"`
	FullOutputPath     *string `json:"fullOutputPath,omitempty"`
	Timestamp          int64   `json:"timestamp"`
	ExcludeFromContext *bool   `json:"excludeFromContext,omitempty"`
}

type BranchPreparation

type BranchPreparation struct {
	Messages    engine.AgentMessages
	FileOps     FileOperations
	TotalTokens int64
}

func PrepareBranchEntries

func PrepareBranchEntries(entries []SessionEntry, tokenBudget float64) BranchPreparation

type BranchSummary

type BranchSummary struct {
	Summary  string
	Details  any
	Usage    *ai.Usage
	FromHook *bool
}

type BranchSummaryDetails

type BranchSummaryDetails struct {
	ReadFiles     []string `json:"readFiles"`
	ModifiedFiles []string `json:"modifiedFiles"`
}

type BranchSummaryResult

type BranchSummaryResult struct {
	Summary       string
	Usage         *ai.Usage
	ReadFiles     []string
	ModifiedFiles []string
}

func GenerateBranchSummary

func GenerateBranchSummary(ctx context.Context, entries []SessionEntry, options GenerateBranchSummaryOptions) (*BranchSummaryResult, error)

func GenerateProductBranchSummary added in v0.6.0

func GenerateProductBranchSummary(ctx context.Context, entries []SessionEntry, options GenerateBranchSummaryOptions) (*BranchSummaryResult, error)

GenerateProductBranchSummary follows coding-agent response limits and rejects incomplete summaries.

type ByteSessionStorage

type ByteSessionStorage interface {
	SessionStorage
	Bytes() ([]byte, error)
	HeaderJSON() []byte
}

ByteSessionStorage exposes the exact serialized representation of a byte-backed session.

type CollectEntriesResult

type CollectEntriesResult struct {
	Entries          []SessionEntry
	CommonAncestorID *string
}

func CollectEntriesForBranchSummary

func CollectEntriesForBranchSummary(entries []SessionEntry, oldLeafID *string, targetID string) (CollectEntriesResult, error)

type CompactionDetails

type CompactionDetails struct {
	ReadFiles     []string `json:"readFiles"`
	ModifiedFiles []string `json:"modifiedFiles"`
}

type CompactionPreparation

type CompactionPreparation struct {
	FirstKeptEntryID    string
	MessagesToSummarize engine.AgentMessages
	TurnPrefixMessages  engine.AgentMessages
	RetainedTail        engine.AgentMessages
	IsSplitTurn         bool
	TokensBefore        int64
	PreviousSummary     *string
	FileOps             FileOperations
	Settings            CompactionSettings
}

func PrepareCompaction

func PrepareCompaction(pathEntries []SessionEntry, settings CompactionSettings) (*CompactionPreparation, error)

func PrepareLegacyCompaction

func PrepareLegacyCompaction(pathEntries []SessionEntry, settings CompactionSettings) (*CompactionPreparation, error)

PrepareLegacyCompaction retains the coding-agent compaction behavior, whose persisted session format has not adopted harness retained-tail checkpoints.

func PrepareTreeCompaction

func PrepareTreeCompaction(pathEntries []SessionTreeEntry, settings CompactionSettings) (*CompactionPreparation, error)

PrepareTreeCompaction prepares the canonical persisted session entries.

type CompactionResult

type CompactionResult struct {
	Summary          string
	FirstKeptEntryID string
	TokensBefore     int64
	Usage            *ai.Usage
	RetainedTail     engine.AgentMessages
	Details          any
}

func Compact

func Compact(
	ctx context.Context,
	preparation *CompactionPreparation,
	model *ai.Model,
	complete CompleteFunc,
	customInstructions string,
	thinkingLevel ai.ModelThinkingLevel,
) (*CompactionResult, error)

func CompactProduct added in v0.6.0

func CompactProduct(ctx context.Context, preparation *CompactionPreparation, model *ai.Model, complete CompleteFunc, customInstructions string, thinkingLevel ai.ModelThinkingLevel, sessionID *string) (*CompactionResult, error)

CompactProduct follows the coding-agent summary policy; Compact retains the standalone harness contract.

func (CompactionResult) MarshalJSON

func (result CompactionResult) MarshalJSON() ([]byte, error)

type CompactionSettings

type CompactionSettings struct {
	Enabled          bool  `json:"enabled"`
	ReserveTokens    int64 `json:"reserveTokens"`
	KeepRecentTokens int64 `json:"keepRecentTokens"`
}

type ContextEntryTransform

type ContextEntryTransform func([]SessionTreeEntry) []SessionTreeEntry

type ContextUsage

type ContextUsage struct {
	Tokens        *int64   `json:"tokens"`
	ContextWindow float64  `json:"contextWindow"`
	Percent       *float64 `json:"percent"`
}

type ContextUsageEstimate

type ContextUsageEstimate struct {
	Tokens         int64 `json:"tokens"`
	UsageTokens    int64 `json:"usageTokens"`
	TrailingTokens int64 `json:"trailingTokens"`
	LastUsageIndex *int  `json:"lastUsageIndex"`
}

func EstimateContextTokens

func EstimateContextTokens(messages engine.AgentMessages) ContextUsageEstimate

func EstimateProjectedContextTokens added in v0.14.0

func EstimateProjectedContextTokens(entries []SessionEntry) ContextUsageEstimate

EstimateProjectedContextTokens estimates a branch's projected context without trusting usage recorded before a later context edit or compaction.

type CustomEntryContextMessageProjector

type CustomEntryContextMessageProjector func(SessionTreeEntry, int, []SessionTreeEntry) engine.AgentMessages

type CustomMessage

type CustomMessage struct {
	Role       string `json:"role"`
	CustomType string `json:"customType"`
	Content    any    `json:"content"`
	Display    bool   `json:"display"`
	Details    any    `json:"details,omitempty"`
	Timestamp  int64  `json:"timestamp"`
}

type CutPointResult

type CutPointResult struct {
	FirstKeptEntryIndex int  `json:"firstKeptEntryIndex"`
	TurnStartIndex      int  `json:"turnStartIndex"`
	IsSplitTurn         bool `json:"isSplitTurn"`
}

func FindCutPoint

func FindCutPoint(entries []SessionEntry, startIndex, endIndex int, keepRecentTokens int64) CutPointResult

type ExecOptions

type ExecOptions struct {
	CWD string
	// Env overrides inherited defaults when the environment is inherited, and
	// is the entire child environment otherwise.
	Env map[string]string
	// InheritEnv controls whether the execution environment's default
	// variables are inherited. Nil defaults to true.
	InheritEnv     *bool
	TimeoutSeconds *float64
	OnStdout       func(string) error
	OnStderr       func(string) error
}

type ExecResult

type ExecResult struct {
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	ExitCode int    `json:"exitCode"`
}

type ExecutionEnv

type ExecutionEnv interface {
	FileSystem
	Shell
}

type ExecutionError

type ExecutionError struct {
	Code ExecutionErrorCode
	Err  error
}

ExecutionError keeps expected shell failures stable across execution backends.

func (*ExecutionError) Error

func (err *ExecutionError) Error() string

func (*ExecutionError) Unwrap

func (err *ExecutionError) Unwrap() error

type ExecutionErrorCode

type ExecutionErrorCode string
const (
	ExecutionErrorAborted          ExecutionErrorCode = "aborted"
	ExecutionErrorTimeout          ExecutionErrorCode = "timeout"
	ExecutionErrorShellUnavailable ExecutionErrorCode = "shell_unavailable"
	ExecutionErrorSpawn            ExecutionErrorCode = "spawn_error"
	ExecutionErrorCallback         ExecutionErrorCode = "callback_error"
	ExecutionErrorUnknown          ExecutionErrorCode = "unknown"
)

type FileError

type FileError struct {
	Code FileErrorCode
	Path string
	Err  error
}

FileError keeps expected filesystem failures typed across local and remote environments.

func (*FileError) Error

func (err *FileError) Error() string

func (*FileError) Unwrap

func (err *FileError) Unwrap() error

type FileErrorCode

type FileErrorCode string
const (
	FileErrorAborted          FileErrorCode = "aborted"
	FileErrorNotFound         FileErrorCode = "not_found"
	FileErrorPermissionDenied FileErrorCode = "permission_denied"
	FileErrorNotDirectory     FileErrorCode = "not_directory"
	FileErrorIsDirectory      FileErrorCode = "is_directory"
	FileErrorInvalid          FileErrorCode = "invalid"
	FileErrorNotSupported     FileErrorCode = "not_supported"
	FileErrorUnknown          FileErrorCode = "unknown"
)

type FileInfo

type FileInfo struct {
	Name    string
	Path    string
	Kind    FileKind
	Size    int64
	MTimeMS float64
}

type FileKind

type FileKind string
const (
	FileKindFile      FileKind = "file"
	FileKindDirectory FileKind = "directory"
	FileKindSymlink   FileKind = "symlink"
)

type FileOperations

type FileOperations struct {
	Read    map[string]struct{}
	Written map[string]struct{}
	Edited  map[string]struct{}
}

type FileSystem

type FileSystem interface {
	WorkingDirectory() string
	AbsolutePath(context.Context, string) (string, error)
	JoinPath(context.Context, ...string) (string, error)
	ReadTextFile(context.Context, string) (string, error)
	ReadTextLines(context.Context, string, int) ([]string, error)
	ReadBinaryFile(context.Context, string) ([]byte, error)
	WriteFile(context.Context, string, []byte) error
	AppendFile(context.Context, string, []byte) error
	RenameFile(context.Context, string, string) error
	FileInfo(context.Context, string) (FileInfo, error)
	ListDir(context.Context, string) ([]FileInfo, error)
	CanonicalPath(context.Context, string) (string, error)
	Exists(context.Context, string) (bool, error)
	CreateDir(context.Context, string, bool) error
	Remove(context.Context, string, bool, bool) error
	CreateTempDir(context.Context, string) (string, error)
	CreateTempFile(context.Context, string, string) (string, error)
	Cleanup() error
}

FileSystem is the harness filesystem seam. Context cancellation maps to FileErrorAborted.

type ForkPosition

type ForkPosition string
const (
	ForkBefore ForkPosition = "before"
	ForkAt     ForkPosition = "at"
)

type GenerateBranchSummaryOptions

type GenerateBranchSummaryOptions struct {
	Model               *ai.Model
	Complete            CompleteFunc
	CustomInstructions  string
	ReplaceInstructions bool
	ReserveTokens       *int64
	Retry               *ai.RetryPolicy
	Callbacks           *ai.RetryCallbacks
}

type InMemorySessionStorage

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

InMemorySessionStorage stores the complete physical entry log in memory.

func NewInMemorySessionStorage

func NewInMemorySessionStorage(entries []SessionTreeEntry, metadata SessionMetadata) (*InMemorySessionStorage, error)

func (*InMemorySessionStorage) AppendEntry

func (storage *InMemorySessionStorage) AppendEntry(entry SessionTreeEntry) error

func (*InMemorySessionStorage) CreateEntryID

func (storage *InMemorySessionStorage) CreateEntryID() (string, error)

func (*InMemorySessionStorage) Entries

func (storage *InMemorySessionStorage) Entries(options ...SessionEntryCursorOptions) []SessionTreeEntry

func (*InMemorySessionStorage) EntriesByType

func (storage *InMemorySessionStorage) EntriesByType(entryType string) []SessionTreeEntry

func (*InMemorySessionStorage) Entry

func (storage *InMemorySessionStorage) Entry(id string) (*SessionTreeEntry, bool)

func (*InMemorySessionStorage) Label

func (storage *InMemorySessionStorage) Label(id string) (string, bool)

func (*InMemorySessionStorage) LeafID

func (storage *InMemorySessionStorage) LeafID() (*string, error)

func (*InMemorySessionStorage) Metadata

func (storage *InMemorySessionStorage) Metadata() SessionMetadata

func (*InMemorySessionStorage) PathToRootOrCompaction

func (storage *InMemorySessionStorage) PathToRootOrCompaction(leafID *string) ([]SessionTreeEntry, error)

func (*InMemorySessionStorage) SessionName

func (storage *InMemorySessionStorage) SessionName() (string, bool)

func (*InMemorySessionStorage) SessionStats

func (storage *InMemorySessionStorage) SessionStats() SessionStats

func (*InMemorySessionStorage) SetLeafID

func (storage *InMemorySessionStorage) SetLeafID(leafID *string) error

type JSONLSessionRepo

type JSONLSessionRepo struct {
	FS           FileSystem
	SessionsRoot string
	// contains filtered or unexported fields
}

func NewJSONLSessionRepo

func NewJSONLSessionRepo(fileSystem FileSystem, sessionsRoot string) *JSONLSessionRepo

func (*JSONLSessionRepo) Create

func (repo *JSONLSessionRepo) Create(ctx context.Context, options SessionCreateOptions) (*Session, error)

func (*JSONLSessionRepo) Delete

func (repo *JSONLSessionRepo) Delete(ctx context.Context, metadata SessionMetadata) error

func (*JSONLSessionRepo) Fork

func (repo *JSONLSessionRepo) Fork(ctx context.Context, sourceMetadata SessionMetadata, options SessionForkOptions) (*Session, error)

func (*JSONLSessionRepo) ImportJSONL

func (repo *JSONLSessionRepo) ImportJSONL(ctx context.Context, content []byte) (*Session, error)

ImportJSONL installs exact upstream bytes into this repository and returns a storage whose later appends remain durable.

func (*JSONLSessionRepo) ImportJSONLAt

func (repo *JSONLSessionRepo) ImportJSONLAt(ctx context.Context, content []byte, path string) (*Session, error)

ImportJSONLAt installs exact upstream bytes at the runtime-selected import destination and keeps later appends bound to that file.

func (*JSONLSessionRepo) List

func (*JSONLSessionRepo) Open

func (repo *JSONLSessionRepo) Open(ctx context.Context, metadata SessionMetadata) (*Session, error)

func (*JSONLSessionRepo) OpenPath

func (repo *JSONLSessionRepo) OpenPath(ctx context.Context, path string) (*Session, error)

OpenPath resolves and opens one explicit JSONL path without filtering it through List, so malformed sessions remain observable to callers.

func (*JSONLSessionRepo) OpenRuntimeBytes

func (repo *JSONLSessionRepo) OpenRuntimeBytes(ctx context.Context, path string, content []byte) (*Session, error)

OpenRuntimeBytes binds an unmaterialized coding-session snapshot to a path. The bytes remain pending until the first assistant message, matching the coding runtime's delayed persistence.

func (*JSONLSessionRepo) OpenRuntimePath

func (repo *JSONLSessionRepo) OpenRuntimePath(ctx context.Context, path, cwd string) (*Session, error)

OpenRuntimePath composes the harness repository with coding-session resume semantics for missing and zero-byte explicit files.

type JSONLSessionStorage

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

JSONLSessionStorage retains the exact input bytes until a mutation appends the same JSON line that upstream would append.

func OpenSessionJournal added in v0.8.0

func OpenSessionJournal(content []byte, appendLine func([]byte) error) (*JSONLSessionStorage, error)

OpenSessionJournal binds a pathless v3 journal to an explicit durable writer. The writer must commit each line before returning; errors leave memory unchanged.

func RehydrateJSONLSession

func RehydrateJSONLSession(content []byte, filePath string) (*JSONLSessionStorage, error)

RehydrateJSONLSession opens an upstream v3 JSONL session directly from bytes without first materializing a temporary file.

func (*JSONLSessionStorage) AppendEntry

func (storage *JSONLSessionStorage) AppendEntry(entry SessionTreeEntry) error

func (*JSONLSessionStorage) Bytes

func (storage *JSONLSessionStorage) Bytes() ([]byte, error)

func (*JSONLSessionStorage) CreateEntryID

func (storage *JSONLSessionStorage) CreateEntryID() (string, error)

func (*JSONLSessionStorage) Entries

func (storage *JSONLSessionStorage) Entries(options ...SessionEntryCursorOptions) []SessionTreeEntry

func (*JSONLSessionStorage) EntriesByType

func (storage *JSONLSessionStorage) EntriesByType(entryType string) []SessionTreeEntry

func (*JSONLSessionStorage) Entry

func (storage *JSONLSessionStorage) Entry(id string) (*SessionTreeEntry, bool)

func (*JSONLSessionStorage) HeaderJSON

func (storage *JSONLSessionStorage) HeaderJSON() []byte

func (*JSONLSessionStorage) IsPersistent

func (storage *JSONLSessionStorage) IsPersistent() bool

func (*JSONLSessionStorage) Label

func (storage *JSONLSessionStorage) Label(id string) (string, bool)

func (*JSONLSessionStorage) LeafID

func (storage *JSONLSessionStorage) LeafID() (*string, error)

func (*JSONLSessionStorage) Metadata

func (storage *JSONLSessionStorage) Metadata() SessionMetadata

func (*JSONLSessionStorage) PathToRootOrCompaction

func (storage *JSONLSessionStorage) PathToRootOrCompaction(leafID *string) ([]SessionTreeEntry, error)

func (*JSONLSessionStorage) SessionName

func (storage *JSONLSessionStorage) SessionName() (string, bool)

func (*JSONLSessionStorage) SessionStats

func (storage *JSONLSessionStorage) SessionStats() SessionStats

func (*JSONLSessionStorage) SessionVersion

func (storage *JSONLSessionStorage) SessionVersion() float64

SessionVersion exposes the original byte-backed header version to adapters.

func (*JSONLSessionStorage) SetLeafID

func (storage *JSONLSessionStorage) SetLeafID(leafID *string) error

type LocalExecutionEnv

type LocalExecutionEnv = NodeExecutionEnv

LocalExecutionEnv is the platform-neutral Go name for NodeExecutionEnv.

type NodeExecutionEnv

type NodeExecutionEnv struct {
	CWD       string
	ShellPath string
	ShellEnv  map[string]string
	// contains filtered or unexported fields
}

NodeExecutionEnv is the pure-Go local filesystem and shell backend.

func (*NodeExecutionEnv) AbsolutePath

func (env *NodeExecutionEnv) AbsolutePath(ctx context.Context, path string) (string, error)

func (*NodeExecutionEnv) AppendFile

func (env *NodeExecutionEnv) AppendFile(ctx context.Context, path string, content []byte) error

func (*NodeExecutionEnv) CanonicalPath

func (env *NodeExecutionEnv) CanonicalPath(ctx context.Context, path string) (string, error)

func (*NodeExecutionEnv) Cleanup

func (env *NodeExecutionEnv) Cleanup() error

func (*NodeExecutionEnv) CreateDir

func (env *NodeExecutionEnv) CreateDir(ctx context.Context, path string, recursive bool) error

func (*NodeExecutionEnv) CreateTempDir

func (env *NodeExecutionEnv) CreateTempDir(ctx context.Context, prefix string) (string, error)

func (*NodeExecutionEnv) CreateTempFile

func (env *NodeExecutionEnv) CreateTempFile(ctx context.Context, prefix, suffix string) (string, error)

func (*NodeExecutionEnv) Exec

func (env *NodeExecutionEnv) Exec(ctx context.Context, command string, options ExecOptions) (ExecResult, error)

Exec runs command through the shared shell executor; its failures become typed ExecutionErrors.

func (*NodeExecutionEnv) Exists

func (env *NodeExecutionEnv) Exists(ctx context.Context, path string) (bool, error)

func (*NodeExecutionEnv) FileInfo

func (env *NodeExecutionEnv) FileInfo(ctx context.Context, path string) (FileInfo, error)

func (*NodeExecutionEnv) JoinPath

func (env *NodeExecutionEnv) JoinPath(ctx context.Context, parts ...string) (string, error)

func (*NodeExecutionEnv) ListDir

func (env *NodeExecutionEnv) ListDir(ctx context.Context, path string) ([]FileInfo, error)

func (*NodeExecutionEnv) ReadBinaryFile

func (env *NodeExecutionEnv) ReadBinaryFile(ctx context.Context, path string) ([]byte, error)

func (*NodeExecutionEnv) ReadTextFile

func (env *NodeExecutionEnv) ReadTextFile(ctx context.Context, path string) (string, error)

func (*NodeExecutionEnv) ReadTextLines

func (env *NodeExecutionEnv) ReadTextLines(ctx context.Context, path string, maxLines int) ([]string, error)

func (*NodeExecutionEnv) Remove

func (env *NodeExecutionEnv) Remove(ctx context.Context, path string, recursive, force bool) error

func (*NodeExecutionEnv) RenameFile

func (env *NodeExecutionEnv) RenameFile(ctx context.Context, from, to string) error

func (*NodeExecutionEnv) WorkingDirectory

func (env *NodeExecutionEnv) WorkingDirectory() string

func (*NodeExecutionEnv) WriteFile

func (env *NodeExecutionEnv) WriteFile(ctx context.Context, path string, content []byte) error

func (*NodeExecutionEnv) WriteFileExclusive

func (env *NodeExecutionEnv) WriteFileExclusive(ctx context.Context, path string, content []byte) error

WriteFileExclusive creates a new file without replacing a concurrent writer.

type Session

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

Session is the storage-backed facade used by embedders and repositories.

func NewSession

func NewSession(storage SessionStorage, options ...SessionContextBuildOptions) *Session

func (*Session) AppendActiveToolsChange

func (session *Session) AppendActiveToolsChange(toolNames []string) (string, error)

func (*Session) AppendCompaction

func (session *Session) AppendCompaction(summary, firstKeptEntryID string, tokensBefore float64, details any, fromHook *bool, usage ...*ai.Usage) (string, error)

func (*Session) AppendCompactionWithTail

func (session *Session) AppendCompactionWithTail(
	summary, firstKeptEntryID string,
	tokensBefore float64,
	details any,
	fromHook *bool,
	usage *ai.Usage,
	retainedTail engine.AgentMessages,
) (string, error)

AppendCompactionWithTail persists the v0.81 checkpoint form. A non-nil retained tail, including an empty one, marks the compaction as a complete ancestry checkpoint.

func (*Session) AppendCustom

func (session *Session) AppendCustom(customType string, data ...any) (string, error)

func (*Session) AppendCustomMessage

func (session *Session) AppendCustomMessage(customType string, content any, display bool, details ...any) (string, error)

func (*Session) AppendLabel

func (session *Session) AppendLabel(targetID string, label *string) (string, error)

func (*Session) AppendMessage

func (session *Session) AppendMessage(message any) (string, error)

func (*Session) AppendModelChange

func (session *Session) AppendModelChange(provider, modelID string) (string, error)

func (*Session) AppendName

func (session *Session) AppendName(name string) (string, error)

func (*Session) AppendThinkingLevelChange

func (session *Session) AppendThinkingLevelChange(level string) (string, error)

func (*Session) Branch

func (session *Session) Branch(fromID ...string) ([]SessionTreeEntry, error)

func (*Session) Context

func (session *Session) Context(options ...SessionContextBuildOptions) (SessionContext, error)

func (*Session) ContextEntries

func (session *Session) ContextEntries(options ...SessionContextBuildOptions) ([]SessionTreeEntry, error)

func (*Session) Entries

func (session *Session) Entries(options ...SessionEntryCursorOptions) []SessionTreeEntry

func (*Session) Entry

func (session *Session) Entry(id string) (*SessionTreeEntry, bool)

func (*Session) Label

func (session *Session) Label(id string) (string, bool)

func (*Session) LeafID

func (session *Session) LeafID() (*string, error)

func (*Session) Metadata

func (session *Session) Metadata() SessionMetadata

func (*Session) MoveTo

func (session *Session) MoveTo(entryID *string, summary *BranchSummary) (string, error)

func (*Session) Name

func (session *Session) Name() (string, bool, error)

func (*Session) Stats

func (session *Session) Stats() SessionStats

func (*Session) Storage

func (session *Session) Storage() SessionStorage

type SessionContext

type SessionContext struct {
	ThinkingLevel   string        `json:"thinkingLevel"`
	Model           *SessionModel `json:"model"`
	ActiveToolNames []string      `json:"activeToolNames"`
	Messages        []any         `json:"messages"`
}

func BuildSessionContext

func BuildSessionContext(entries []SessionTreeEntry, options ...SessionContextBuildOptions) SessionContext

BuildSessionContext reduces one active path using the same state and latest compaction rules as upstream's harness Session.

type SessionContextBuildOptions

type SessionContextBuildOptions struct {
	EntryTransforms []ContextEntryTransform
	EntryProjectors map[string]CustomEntryContextMessageProjector
}

type SessionCreateOptions

type SessionCreateOptions struct {
	ID                string
	CWD               string
	ParentSessionPath *string
	Metadata          json.RawMessage
}

type SessionEntry

type SessionEntry struct {
	Type             string
	ID               string
	ParentID         *string
	Timestamp        string
	Message          engine.AgentMessage
	Summary          string
	FirstKeptEntryID string
	RetainedTail     engine.AgentMessages
	TokensBefore     float64
	Details          any
	Usage            *ai.Usage
	FromHook         bool
	FromID           string
	CustomType       string
	Content          any
	Display          bool
	// Omitted marks an entry a context edit removed from model context.
	Omitted bool
	// TargetID and Replaces describe a context_edit: its target, and whether it
	// replaces the target's content rather than omitting it.
	TargetID string
	Replaces bool
}

SessionEntry is the compaction-facing projection of a v3 session entry. Harness storage owns generic session persistence; agent/session remains an upper-layer wire manager.

type SessionEntryCursorOptions

type SessionEntryCursorOptions struct {
	AfterEntrySeq int
	Limit         *int
}

SessionEntryCursorOptions follows Array.slice semantics for the ordinary non-negative cursors emitted by upstream consumers.

type SessionError

type SessionError struct {
	Code SessionErrorCode
	Err  error
}

SessionError preserves upstream's machine-readable error code.

func (*SessionError) Error

func (failure *SessionError) Error() string

func (*SessionError) Unwrap

func (failure *SessionError) Unwrap() error

type SessionErrorCode

type SessionErrorCode string

SessionErrorCode is the stable failure classification used by harness storage, repositories, and tree operations.

const (
	SessionErrorNotFound       SessionErrorCode = "not_found"
	SessionErrorInvalidSession SessionErrorCode = "invalid_session"
	SessionErrorInvalidEntry   SessionErrorCode = "invalid_entry"
	SessionErrorInvalidFork    SessionErrorCode = "invalid_fork_target"
	SessionErrorStorage        SessionErrorCode = "storage"
	SessionErrorUnknown        SessionErrorCode = "unknown"
	SessionErrorAlreadyExists  SessionErrorCode = "already_exists"
	SessionErrorInvalidPayload SessionErrorCode = "invalid_payload"
	SessionErrorInvalidLane    SessionErrorCode = "invalid_lane"
	SessionErrorInvalidQuery   SessionErrorCode = "invalid_query"
)

type SessionForkOptions

type SessionForkOptions struct {
	SessionCreateOptions
	EntryID  string
	Position ForkPosition
}

type SessionListOptions

type SessionListOptions struct {
	CWD string
}

type SessionMetadata

type SessionMetadata struct {
	ID                string          `json:"id"`
	CreatedAt         string          `json:"createdAt"`
	CWD               string          `json:"cwd,omitempty"`
	Path              string          `json:"path,omitempty"`
	ParentSessionPath *string         `json:"parentSessionPath,omitempty"`
	Metadata          json.RawMessage `json:"metadata,omitempty"`
}

SessionMetadata is shared by memory and JSONL repositories. JSONL-only fields are omitted for memory sessions.

type SessionModel

type SessionModel struct {
	Provider string `json:"provider"`
	ModelID  string `json:"modelId"`
}

type SessionStats

type SessionStats struct {
	MessageCount   int     `json:"messageCount"`
	CachedTokens   float64 `json:"cachedTokens"`
	UncachedTokens float64 `json:"uncachedTokens"`
	TotalTokens    float64 `json:"totalTokens"`
	CostTotal      float64 `json:"costTotal"`
}

SessionStats accounts for all physical session entries, including summary entries outside the active branch.

type SessionStorage

type SessionStorage interface {
	Metadata() SessionMetadata
	LeafID() (*string, error)
	SetLeafID(*string) error
	CreateEntryID() (string, error)
	AppendEntry(SessionTreeEntry) error
	Entry(string) (*SessionTreeEntry, bool)
	EntriesByType(string) []SessionTreeEntry
	Label(string) (string, bool)
	SessionName() (string, bool)
	SessionStats() SessionStats
	PathToRootOrCompaction(*string) ([]SessionTreeEntry, error)
	Entries(...SessionEntryCursorOptions) []SessionTreeEntry
}

SessionStorage is the backend-neutral session tree contract.

type SessionTreeEntry

type SessionTreeEntry struct {
	Type      string
	ID        string
	ParentID  *string
	Timestamp string

	Message          json.RawMessage
	ThinkingLevel    string
	Provider         string
	ModelID          string
	ActiveToolNames  []string
	Summary          string
	FirstKeptEntryID string
	RetainedTail     []json.RawMessage
	TokensBefore     float64
	Details          json.RawMessage
	Usage            *ai.Usage
	FromHook         *bool
	FromID           string
	CustomType       string
	Data             json.RawMessage
	Content          json.RawMessage
	Display          bool
	TargetID         *string
	HasTargetID      bool
	Label            *string
	Name             string
	// Replacement is a context_edit's replacement; JSON null omits the target.
	Replacement json.RawMessage
	// contains filtered or unexported fields
}

SessionTreeEntry is the v3 harness session union. Raw JSON members stay opaque so unknown application data can round-trip without coercion.

func BuildContextEntries

func BuildContextEntries(entries []SessionTreeEntry, options ...SessionContextBuildOptions) []SessionTreeEntry

func DefaultContextEntryTransform

func DefaultContextEntryTransform(entries []SessionTreeEntry) []SessionTreeEntry

func EntriesToFork

func EntriesToFork(storage SessionStorage, entryID string, position ForkPosition) ([]SessionTreeEntry, error)

EntriesToFork selects the source entries copied by repository fork.

func ParseSessionTreeEntry

func ParseSessionTreeEntry(data []byte) (SessionTreeEntry, error)

ParseSessionTreeEntry decodes one upstream session entry while retaining unknown members for a later wire-compatible marshal. Exported for module embedders with external session stores; not referenced inside this repo.

func (SessionTreeEntry) RawJSON

func (entry SessionTreeEntry) RawJSON() json.RawMessage

RawJSON returns the original object for entries rehydrated from JSONL.

type Shell

type Shell interface {
	Exec(context.Context, string, ExecOptions) (ExecResult, error)
	Cleanup() error
}

type SummaryMessage

type SummaryMessage struct {
	Role         string  `json:"role"`
	Summary      string  `json:"summary"`
	FromID       string  `json:"fromId,omitempty"`
	TokensBefore float64 `json:"tokensBefore,omitempty"`
	Timestamp    int64   `json:"timestamp"`
}

type SummaryResult

type SummaryResult struct {
	Text  string
	Usage ai.Usage
}

func GenerateSummaryWithUsage

func GenerateSummaryWithUsage(
	ctx context.Context,
	messages engine.AgentMessages,
	model *ai.Model,
	complete CompleteFunc,
	reserveTokens int64,
	customInstructions string,
	previousSummary *string,
	thinkingLevel ai.ModelThinkingLevel,
) (*SummaryResult, error)

Directories

Path Synopsis
Package envtest is the shared conformance suite for harness.FileSystem port implementations (DECISIONS.md P10).
Package envtest is the shared conformance suite for harness.FileSystem port implementations (DECISIONS.md P10).

Jump to

Keyboard shortcuts

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