harness

package
v0.4.9 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 30 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 = `` /* 440-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 added in v0.1.2

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 ContextMessages

func ContextMessages(entries []SessionEntry) agent.AgentMessages

func EstimateTokens

func EstimateTokens(message agent.AgentMessage) int64

func FindTurnStartIndex

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

func FormatFileOperations

func FormatFileOperations(readFiles, modifiedFiles []string) string

func FormatPromptTemplateInvocation

func FormatPromptTemplateInvocation(template PromptTemplate, args []string) string

FormatPromptTemplateInvocation follows the harness's sequential replacement passes; unlike coding-agent templates, the harness treats default syntax as literal text and later passes can expand placeholders introduced earlier.

func FormatSkillInvocation

func FormatSkillInvocation(skill Skill, additionalInstructions string) string

FormatSkillInvocation embeds a loaded skill and optional explicit instructions.

func GenerateSummary

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

func GetLastAssistantUsage

func GetLastAssistantUsage(entries []SessionEntry) *ai.Usage

func LoadSourcedPromptTemplates

func LoadSourcedPromptTemplates[T any](env ResourceFileSystem, inputs []SourcedPromptTemplateInput[T], mapTemplate ...func(PromptTemplate, T) PromptTemplate) ([]SourcedPromptTemplate[T], []SourcedPromptTemplateDiagnostic[T])

func LoadSourcedSkills

func LoadSourcedSkills[T any](env ResourceFileSystem, inputs []SourcedSkillInput[T], mapSkill ...func(Skill, T) Skill) ([]SourcedSkill[T], []SourcedSkillDiagnostic[T])

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 added in v0.4.7

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

MarshalSessionTreeEntry serializes one entry with upstream field order.

func SerializeConversation

func SerializeConversation(messages agent.AgentMessages) string

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    agent.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)

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 agent.AgentMessages
	TurnPrefixMessages  agent.AgentMessages
	RetainedTail        agent.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 added in v0.4.7

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     agent.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 (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 CompleteFunc

func RetryingCompleteFunc added in v0.1.2

func RetryingCompleteFunc(complete CompleteFunc, retry *ai.RetryPolicy, callbacks *ai.RetryCallbacks) CompleteFunc

RetryingCompleteFunc decorates the existing compaction completion seam. It lets compaction retry each generated summary without changing its core API.

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 agent.AgentMessages) ContextUsageEstimate

type CustomEntryContextMessageProjector

type CustomEntryContextMessageProjector func(SessionTreeEntry, int, []SessionTreeEntry) agent.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
	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 HarnessPromptTemplatesResult

type HarnessPromptTemplatesResult struct {
	PromptTemplates []PromptTemplate
	Diagnostics     []PromptTemplateDiagnostic
}

func LoadPromptTemplates

func LoadPromptTemplates(env ResourceFileSystem, paths ...string) HarnessPromptTemplatesResult

LoadPromptTemplates loads explicit files or direct markdown children through the execution environment.

type HarnessSkillsResult

type HarnessSkillsResult struct {
	Skills      []Skill
	Diagnostics []SkillDiagnostic
}

func LoadSkills

func LoadSkills(env ResourceFileSystem, dirs ...string) HarnessSkillsResult

LoadSkills traverses one or more roots with upstream's SKILL.md stopping rule.

type InMemorySessionRepo

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

InMemorySessionRepo retains insertion ordering, matching upstream's Map.

func NewInMemorySessionRepo

func NewInMemorySessionRepo() *InMemorySessionRepo

func (*InMemorySessionRepo) Create

func (*InMemorySessionRepo) Delete

func (repo *InMemorySessionRepo) Delete(_ context.Context, metadata SessionMetadata) error

func (*InMemorySessionRepo) Fork

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

func (*InMemorySessionRepo) List

func (*InMemorySessionRepo) Open

func (repo *InMemorySessionRepo) Open(_ context.Context, metadata SessionMetadata) (*Session, error)

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 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)

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) ResourceCanonicalPath

func (env *NodeExecutionEnv) ResourceCanonicalPath(path string) (string, error)

func (*NodeExecutionEnv) ResourceFileInfo

func (env *NodeExecutionEnv) ResourceFileInfo(path string) (FileInfo, error)

func (*NodeExecutionEnv) ResourceListDir

func (env *NodeExecutionEnv) ResourceListDir(path string) ([]FileInfo, error)

func (*NodeExecutionEnv) ResourceReadTextFile

func (env *NodeExecutionEnv) ResourceReadTextFile(path string) (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 PromptTemplate

type PromptTemplate struct {
	Name        string
	Description string
	Content     string
}

PromptTemplate is the harness-level explicit prompt expansion resource.

type PromptTemplateDiagnostic

type PromptTemplateDiagnostic struct {
	Type    string
	Code    PromptTemplateDiagnosticCode
	Message string
	Path    string
}

type PromptTemplateDiagnosticCode

type PromptTemplateDiagnosticCode string
const (
	PromptTemplateDiagnosticFileInfoFailed PromptTemplateDiagnosticCode = "file_info_failed"
	PromptTemplateDiagnosticListFailed     PromptTemplateDiagnosticCode = "list_failed"
	PromptTemplateDiagnosticReadFailed     PromptTemplateDiagnosticCode = "read_failed"
	PromptTemplateDiagnosticParseFailed    PromptTemplateDiagnosticCode = "parse_failed"
)

type ResourceFileSystem

type ResourceFileSystem interface {
	ResourceFileInfo(path string) (FileInfo, error)
	ResourceListDir(path string) ([]FileInfo, error)
	ResourceReadTextFile(path string) (string, error)
	ResourceCanonicalPath(path string) (string, error)
}

ResourceFileSystem is the read-only filesystem slice used by resource discovery.

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 agent.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          agent.AgentMessage
	Summary          string
	FirstKeptEntryID string
	RetainedTail     agent.AgentMessages
	TokensBefore     float64
	Details          any
	Usage            *ai.Usage
	FromHook         bool
	FromID           string
	CustomType       string
	Content          any
	Display          bool
}

SessionEntry is the compaction-facing projection of a v3 session entry. Harness storage owns generic session persistence; codingagent/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"
)

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
	// 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 added in v0.4.7

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

ParseSessionTreeEntry decodes one upstream session entry while retaining unknown members for a later wire-compatible marshal.

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 Skill

type Skill struct {
	Name                   string
	Description            string
	Content                string
	FilePath               string
	DisableModelInvocation bool
}

Skill is the harness-level, execution-environment-neutral Agent Skills shape.

type SkillDiagnostic

type SkillDiagnostic struct {
	Type    string
	Code    SkillDiagnosticCode
	Message string
	Path    string
}

type SkillDiagnosticCode

type SkillDiagnosticCode string
const (
	SkillDiagnosticFileInfoFailed SkillDiagnosticCode = "file_info_failed"
	SkillDiagnosticListFailed     SkillDiagnosticCode = "list_failed"
	SkillDiagnosticReadFailed     SkillDiagnosticCode = "read_failed"
	SkillDiagnosticParseFailed    SkillDiagnosticCode = "parse_failed"
	SkillDiagnosticInvalidMeta    SkillDiagnosticCode = "invalid_metadata"
)

type SourcedPromptTemplate

type SourcedPromptTemplate[T any] struct {
	PromptTemplate PromptTemplate
	Source         T
}

type SourcedPromptTemplateDiagnostic

type SourcedPromptTemplateDiagnostic[T any] struct {
	PromptTemplateDiagnostic
	Source T
}

type SourcedPromptTemplateInput

type SourcedPromptTemplateInput[T any] struct {
	Path   string
	Source T
}

type SourcedSkill

type SourcedSkill[T any] struct {
	Skill  Skill
	Source T
}

type SourcedSkillDiagnostic

type SourcedSkillDiagnostic[T any] struct {
	SkillDiagnostic
	Source T
}

type SourcedSkillInput

type SourcedSkillInput[T any] struct {
	Path   string
	Source T
}

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 agent.AgentMessages,
	model *ai.Model,
	complete CompleteFunc,
	reserveTokens int64,
	customInstructions string,
	previousSummary *string,
	thinkingLevel ai.ModelThinkingLevel,
) (*SummaryResult, error)

Jump to

Keyboard shortcuts

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