harness

package
v0.82.0 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AgentHarnessPhaseIdle          = "idle"
	AgentHarnessPhaseTurn          = "turn"
	AgentHarnessPhaseCompaction    = "compaction"
	AgentHarnessPhaseBranchSummary = "branch_summary"
)
View Source
const (
	FileKindFile      = harnessenv.FileKindFile
	FileKindDirectory = harnessenv.FileKindDirectory
	FileKindSymlink   = harnessenv.FileKindSymlink

	FileErrorAborted          = harnessenv.FileErrorAborted
	FileErrorNotFound         = harnessenv.FileErrorNotFound
	FileErrorPermissionDenied = harnessenv.FileErrorPermissionDenied
	FileErrorNotDirectory     = harnessenv.FileErrorNotDirectory
	FileErrorIsDirectory      = harnessenv.FileErrorIsDirectory
	FileErrorInvalid          = harnessenv.FileErrorInvalid
	FileErrorNotSupported     = harnessenv.FileErrorNotSupported
	FileErrorUnknown          = harnessenv.FileErrorUnknown

	ExecutionErrorAborted          = harnessenv.ExecutionErrorAborted
	ExecutionErrorTimeout          = harnessenv.ExecutionErrorTimeout
	ExecutionErrorShellUnavailable = harnessenv.ExecutionErrorShellUnavailable
	ExecutionErrorSpawnError       = harnessenv.ExecutionErrorSpawnError
	ExecutionErrorCallbackError    = harnessenv.ExecutionErrorCallbackError
	ExecutionErrorUnknown          = harnessenv.ExecutionErrorUnknown
)
View Source
const (
	DefaultMaxLines    = utils.DefaultMaxLines
	DefaultMaxBytes    = utils.DefaultMaxBytes
	GrepMaxLineLength  = utils.GrepMaxLineLength
	TruncatedByLines   = utils.TruncatedByLines
	TruncatedByBytes   = utils.TruncatedByBytes
	TruncatedByNothing = utils.TruncatedByNothing
)
View Source
const (
	CompactionErrorAborted             = "aborted"
	CompactionErrorSummarizationFailed = "summarization_failed"
	CompactionErrorInvalidSession      = "invalid_session"
	CompactionErrorUnknown             = "unknown"

	BranchSummaryErrorAborted             = "aborted"
	BranchSummaryErrorSummarizationFailed = "summarization_failed"
	BranchSummaryErrorInvalidSession      = "invalid_session"
	BranchSummaryErrorUnknown             = "unknown"
)
View Source
const BranchSummaryPrefix = `The following is a summary of a branch that this conversation came back from:

<summary>
`
View Source
const BranchSummarySuffix = `</summary>`
View Source
const CompactionSummaryPrefix = `The conversation history before this point was compacted into the following summary:

<summary>
`
View Source
const CompactionSummarySuffix = `
</summary>`

Variables

View Source
var DefaultCompactionSettings = CompactionSettings{Enabled: true, ReserveTokens: 16_384, KeepRecentTokens: 20_000}

Functions

func BashExecutionText

func BashExecutionText(command string, options BashExecutionTextOptions) string

func BranchSummaryText

func BranchSummaryText(summary string) string

func CalculateContextTokens

func CalculateContextTokens(usage llm.Usage) int

func CompactionSummaryText

func CompactionSummaryText(summary string) string

func CompleteSimpleWithRetries added in v0.82.0

func CompleteSimpleWithRetries(
	ctx context.Context,
	runtime SimpleCompletionRuntime,
	model llm.Model,
	llmContext llm.Context,
	options llm.ModelsStreamOptions,
	retry llm.RetryPolicy,
	callbacks llm.RetryCallbacks,
) (llm.Message, error)

CompleteSimpleWithRetries is the single request boundary for generated summaries. Every attempt reuses one isolated session ID and disables prompt cache retention because summary requests are never continued.

func ConvertToLLM

func ConvertToLLM(messages []llm.Message) []llm.Message

func EstimateTokens

func EstimateTokens(message llm.Message) int

func FindTurnStartIndex

func FindTurnStartIndex(entries []Entry, index, minIndex int) int

func FormatPromptTemplateInvocation

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

func FormatSkillInvocation

func FormatSkillInvocation(skill Skill, additionalInstructions string) string

func FormatSkillsForSystemPrompt

func FormatSkillsForSystemPrompt(skills []Skill) string

func GenerateSummary

func GenerateSummary(ctx context.Context, messages []llm.Message, model llm.Model, maxTokens int, apiKey string, previousSummary, focus, thinkingLevel string) (string, error)

func GenerateTurnPrefixSummary

func GenerateTurnPrefixSummary(ctx context.Context, messages []llm.Message, model llm.Model, reserveTokens int, apiKey string, thinkingLevel string) (string, error)

func GetLastAssistantUsage

func GetLastAssistantUsage(entries []Entry) *llm.Usage

func MessageExcludedFromContext

func MessageExcludedFromContext(message llm.Message) bool

func ParseCommandArgs

func ParseCommandArgs(input string) []string

func ResetUUIDv7ForTest

func ResetUUIDv7ForTest()

func SanitizeBinaryOutput

func SanitizeBinaryOutput(str string) string

func SerializeConversation

func SerializeConversation(messages []llm.Message) string

func SessionEntryToContextMessages added in v0.82.0

func SessionEntryToContextMessages(entry Entry, index int, entries []Entry, options ...SessionContextBuildOptions) []llm.Message

func ShouldCompact

func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool

func SubstituteArgs

func SubstituteArgs(content string, args []string) string

func TruncateLine

func TruncateLine(line string, maxChars int) (string, bool)

func UUIDv7

func UUIDv7() string

func UUIDv7With

func UUIDv7With(randomBytes RandomBytesFunc, nowMillis NowMillisFunc) string

Types

type AgentHarness

type AgentHarness struct {
	Env any
	// contains filtered or unexported fields
}

func MustNewAgentHarness

func MustNewAgentHarness(options AgentHarnessOptions) *AgentHarness

func NewAgentHarness

func NewAgentHarness(options AgentHarnessOptions) (*AgentHarness, error)

func (*AgentHarness) Abort

func (h *AgentHarness) Abort(ctx context.Context) (clearedSteer, clearedFollowUp []llm.Message, err error)

func (*AgentHarness) AppendMessage

func (h *AgentHarness) AppendMessage(message llm.Message) error

func (*AgentHarness) Compact

func (h *AgentHarness) Compact(ctx context.Context, customInstructions string) (CompactionResult, error)

func (*AgentHarness) FollowUp

func (h *AgentHarness) FollowUp(ctx context.Context, text string, images ...llm.ContentPart) error

func (*AgentHarness) GetFollowUpMode

func (h *AgentHarness) GetFollowUpMode() string

func (*AgentHarness) GetModel

func (h *AgentHarness) GetModel() llm.Model

func (*AgentHarness) GetResources

func (h *AgentHarness) GetResources() AgentHarnessResources

func (*AgentHarness) GetSteeringMode

func (h *AgentHarness) GetSteeringMode() string

func (*AgentHarness) GetStreamOptions

func (h *AgentHarness) GetStreamOptions() AgentHarnessStreamOptions

func (*AgentHarness) GetThinkingLevel

func (h *AgentHarness) GetThinkingLevel() string

func (*AgentHarness) NavigateTree

func (h *AgentHarness) NavigateTree(ctx context.Context, targetID string, options NavigateTreeOptions) (NavigateTreeResult, error)

func (*AgentHarness) NextTurn

func (h *AgentHarness) NextTurn(ctx context.Context, text string, images ...llm.ContentPart) error

func (*AgentHarness) On

func (h *AgentHarness) On(eventType string, handler AgentHarnessHandler) func()

func (*AgentHarness) Phase

func (h *AgentHarness) Phase() string

func (*AgentHarness) Prompt

func (h *AgentHarness) Prompt(ctx context.Context, text string, images ...llm.ContentPart) (llm.Message, error)

func (*AgentHarness) PromptFromTemplate

func (h *AgentHarness) PromptFromTemplate(ctx context.Context, name string, args []string) (llm.Message, error)

func (*AgentHarness) Session

func (h *AgentHarness) Session() *Session

func (*AgentHarness) SetActiveTools

func (h *AgentHarness) SetActiveTools(toolNames []string) error

func (*AgentHarness) SetFollowUpMode

func (h *AgentHarness) SetFollowUpMode(mode string)

func (*AgentHarness) SetHarnessTools added in v0.82.0

func (h *AgentHarness) SetHarnessTools(tools []AgentHarnessTool, activeToolNames ...string) error

SetHarnessTools replaces the registered context-aware tools.

func (*AgentHarness) SetModel

func (h *AgentHarness) SetModel(ctx context.Context, model llm.Model) error

func (*AgentHarness) SetResources

func (h *AgentHarness) SetResources(ctx context.Context, resources AgentHarnessResources) error

func (*AgentHarness) SetSteeringMode

func (h *AgentHarness) SetSteeringMode(mode string)

func (*AgentHarness) SetStreamOptions

func (h *AgentHarness) SetStreamOptions(options AgentHarnessStreamOptions)

func (*AgentHarness) SetThinkingLevel

func (h *AgentHarness) SetThinkingLevel(ctx context.Context, level string) error

func (*AgentHarness) SetTools

func (h *AgentHarness) SetTools(tools []core.AgentTool, activeToolNames ...string) error

func (*AgentHarness) Skill

func (h *AgentHarness) Skill(ctx context.Context, name, additionalInstructions string) (llm.Message, error)

func (*AgentHarness) Steer

func (h *AgentHarness) Steer(ctx context.Context, text string, images ...llm.ContentPart) error

func (*AgentHarness) Subscribe

func (h *AgentHarness) Subscribe(listener AgentHarnessSubscriber) func()

func (*AgentHarness) WaitForIdle

func (h *AgentHarness) WaitForIdle(ctx context.Context) error

type AgentHarnessAuth

type AgentHarnessAuth struct {
	APIKey  string
	Headers map[string]string
}

type AgentHarnessError

type AgentHarnessError struct {
	Code string
	Err  error
}

func (*AgentHarnessError) Error

func (e *AgentHarnessError) Error() string

func (*AgentHarnessError) Unwrap

func (e *AgentHarnessError) Unwrap() error

type AgentHarnessEvent

type AgentHarnessEvent struct {
	Type string

	Message     llm.Message
	Messages    []llm.Message
	ToolResults []llm.Message

	ToolCallID string
	ToolName   string
	Input      map[string]any
	Content    []llm.ContentPart
	Details    any
	IsError    bool

	Steer    []llm.Message
	FollowUp []llm.Message
	NextTurn []llm.Message

	HadPendingMutations bool
	NextTurnCount       int

	Model         llm.Model
	PreviousModel *llm.Model
	Source        string

	Level         string
	PreviousLevel string

	Resources         AgentHarnessResources
	PreviousResources AgentHarnessResources

	Prompt       string
	Images       []llm.ContentPart
	SystemPrompt string

	SessionID     string
	StreamOptions AgentHarnessStreamOptions
	Payload       any

	Status  int
	Headers map[string]string

	ClearedSteer    []llm.Message
	ClearedFollowUp []llm.Message

	Preparation        *CompactionPreparation
	BranchEntries      []Entry
	CustomInstructions string
	Compaction         CompactionResult
	CompactionEntry    Entry
	FromHook           bool
	TargetID           string
	OldLeafID          *string
	NewLeafID          *string
	CommonAncestorID   *string
	BranchSummary      BranchSummaryResult
	SummaryEntry       *Entry
	Operation          string
	Attempt            int
	MaxAttempts        int
	DelayMs            int
	ErrorMessage       string

	AgentEvent core.AgentEvent
}

type AgentHarnessHookResult

type AgentHarnessHookResult struct {
	Messages    []llm.Message
	HasMessages bool

	SystemPrompt    string
	HasSystemPrompt bool

	StreamOptions *AgentHarnessStreamOptionsPatch

	Payload    any
	HasPayload bool

	Block    bool
	HasBlock bool
	Reason   string

	Content      []llm.ContentPart
	HasContent   bool
	Details      any
	HasDetails   bool
	IsError      bool
	HasIsError   bool
	Terminate    bool
	HasTerminate bool

	Cancel                 bool
	Compaction             CompactionResult
	HasCompaction          bool
	BranchSummary          BranchSummaryResult
	HasBranchSummary       bool
	CustomInstructions     string
	HasCustomInstructions  bool
	ReplaceInstructions    bool
	HasReplaceInstructions bool
}

type AgentHarnessOptions

type AgentHarnessOptions struct {
	Env                 any
	ToolContext         AgentHarnessToolContextSource
	Session             *Session
	Models              SimpleCompletionRuntime
	Model               llm.Model
	ThinkingLevel       string
	SystemPrompt        string
	BuildSystemPrompt   func(context.Context, SystemPromptContext) (string, error)
	GetAPIKeyAndHeaders func(context.Context, llm.Model) (AgentHarnessAuth, bool, error)
	Retry               llm.RetryPolicy
	Resources           AgentHarnessResources
	Tools               []core.AgentTool
	HarnessTools        []AgentHarnessTool
	ActiveToolNames     []string
	StreamOptions       AgentHarnessStreamOptions
	SteeringMode        string
	FollowUpMode        string
	ToolExecution       string
}

type AgentHarnessResources

type AgentHarnessResources struct {
	Skills          []Skill
	PromptTemplates []PromptTemplate
}

func (AgentHarnessResources) Clone

type AgentHarnessStreamOptions

type AgentHarnessStreamOptions struct {
	Transport       string
	TimeoutMillis   int
	MaxRetries      int
	MaxRetryDelayMs int
	Headers         map[string]string
	Metadata        map[string]any
	CacheRetention  string
}

type AgentHarnessStreamOptionsPatch

type AgentHarnessStreamOptionsPatch struct {
	Transport       Optional[string]
	TimeoutMillis   Optional[int]
	MaxRetries      Optional[int]
	MaxRetryDelayMs Optional[int]
	CacheRetention  Optional[string]
	Headers         map[string]*string
	ClearHeaders    bool
	Metadata        map[string]Optional[any]
	ClearMetadata   bool
}

type AgentHarnessSubscriber

type AgentHarnessSubscriber func(context.Context, AgentHarnessEvent) error

type AgentHarnessTool added in v0.82.0

type AgentHarnessTool struct {
	Name        string
	Label       string
	Description string
	Parameters  llm.Schema

	PrepareArguments func(args any) (map[string]any, error)
	Execute          func(ctx context.Context, toolCallID string, params map[string]any, onUpdate core.AgentToolUpdateCallback, toolContext any) (core.AgentToolResult, error)
	ExecutionMode    string
}

AgentHarnessTool is a tool whose execution receives the context snapshot resolved by AgentHarness for the current turn.

The harness keeps context resolution outside the agent loop. This lets the loop operate on ordinary core.AgentTool values while tools still receive application-owned dependencies such as an ExecutionEnv.

func ContextFreeAgentHarnessTool added in v0.82.0

func ContextFreeAgentHarnessTool(tool core.AgentTool) AgentHarnessTool

ContextFreeAgentHarnessTool adapts an ordinary agent-loop tool for use by an AgentHarness. Its executor ignores the harness tool context.

type AgentHarnessToolContextSource added in v0.82.0

type AgentHarnessToolContextSource func(context.Context) (any, error)

AgentHarnessToolContextSource resolves the application-defined tool context once for each turn snapshot.

func StaticToolContext added in v0.82.0

func StaticToolContext(value any) AgentHarnessToolContextSource

StaticToolContext adapts a stable value to an AgentHarnessToolContextSource.

type BashExecutionTextOptions

type BashExecutionTextOptions struct {
	Output         string
	ExitCode       *int
	Cancelled      bool
	Truncated      bool
	FullOutputPath string
}

type BranchPreparation

type BranchPreparation struct {
	Messages    []llm.Message
	FileOps     FileOps
	TotalTokens int
}

func PrepareBranchEntries

func PrepareBranchEntries(entries []Entry, tokenBudget int) BranchPreparation

type BranchSummaryError

type BranchSummaryError struct {
	Code string
	Err  error
}

func (*BranchSummaryError) Error

func (e *BranchSummaryError) Error() string

func (*BranchSummaryError) Unwrap

func (e *BranchSummaryError) Unwrap() error

type BranchSummaryOptions

type BranchSummaryOptions struct {
	APIKey              string
	CustomInstructions  string
	ReplaceInstructions bool
	ReserveTokens       int
	Runtime             SimpleCompletionRuntime
	RequestOptions      llm.ModelsStreamOptions
	Retry               llm.RetryPolicy
	RetryCallbacks      llm.RetryCallbacks
}

type BranchSummaryResult

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

func GenerateBranchSummary

func GenerateBranchSummary(ctx context.Context, entries []Entry, model llm.Model, options BranchSummaryOptions) (BranchSummaryResult, error)

type CapturedShellResult

type CapturedShellResult = harnessenv.CapturedShellResult

func ExecuteShellWithCapture

func ExecuteShellWithCapture(ctx context.Context, env *LocalExecutionEnv, command string, maxInlineBytes int) (CapturedShellResult, error)

type CollectEntriesResult

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

func CollectEntriesForBranchSummary

func CollectEntriesForBranchSummary(session *Session, oldLeafID *string, targetID string) (CollectEntriesResult, error)

type CompactOptions

type CompactOptions struct {
	APIKey             string
	ThinkingLevel      string
	CustomInstructions string
	Runtime            SimpleCompletionRuntime
	RequestOptions     llm.ModelsStreamOptions
	Retry              llm.RetryPolicy
	RetryCallbacks     llm.RetryCallbacks
}

type CompactionError

type CompactionError struct {
	Code string
	Err  error
}

func (*CompactionError) Error

func (e *CompactionError) Error() string

func (*CompactionError) Unwrap

func (e *CompactionError) Unwrap() error

type CompactionPreparation

type CompactionPreparation struct {
	FirstKeptEntryID    string             `json:"firstKeptEntryId"`
	MessagesToSummarize []llm.Message      `json:"messagesToSummarize"`
	TurnPrefixMessages  []llm.Message      `json:"turnPrefixMessages"`
	RetainedTail        []llm.Message      `json:"retainedTail"`
	IsSplitTurn         bool               `json:"isSplitTurn"`
	TokensBefore        int                `json:"tokensBefore"`
	PreviousSummary     string             `json:"previousSummary,omitempty"`
	FileOps             FileOps            `json:"fileOps"`
	Settings            CompactionSettings `json:"settings"`
}

func PrepareCompaction

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

type CompactionResult

type CompactionResult struct {
	Summary              string         `json:"summary"`
	FirstKeptEntryID     string         `json:"firstKeptEntryId"`
	TokensBefore         int            `json:"tokensBefore"`
	RetainedTail         []llm.Message  `json:"retainedTail,omitempty"`
	EstimatedTokensAfter int            `json:"estimatedTokensAfter,omitempty"`
	Usage                *llm.Usage     `json:"usage,omitempty"`
	Details              map[string]any `json:"details,omitempty"`
}

func Compact

func Compact(ctx context.Context, prep CompactionPreparation, model llm.Model, apiKey string, thinkingLevel string) (CompactionResult, error)

func CompactWithOptions

func CompactWithOptions(ctx context.Context, prep CompactionPreparation, model llm.Model, options CompactOptions) (CompactionResult, error)

type CompactionSettings

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

type ContextEntryTransform added in v0.82.0

type ContextEntryTransform func(entries []Entry) []Entry

type ContextTokenEstimate

type ContextTokenEstimate = llm.ContextUsageEstimate

func EstimateContextTokens

func EstimateContextTokens(messages []llm.Message) ContextTokenEstimate

type CreateDirOptions

type CreateDirOptions = harnessenv.CreateDirOptions

type CustomEntryContextMessageProjector added in v0.82.0

type CustomEntryContextMessageProjector func(entry Entry, index int, entries []Entry) []llm.Message

type CutPoint

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

func FindCutPoint

func FindCutPoint(entries []Entry, start, end, keepRecentTokens int) CutPoint

type Entry

type Entry struct {
	Type             string        `json:"type"`
	ID               string        `json:"id,omitempty"`
	ParentID         *string       `json:"parentId,omitempty"`
	Timestamp        string        `json:"timestamp,omitempty"`
	Message          llm.Message   `json:"message,omitempty"`
	TargetID         *string       `json:"targetId,omitempty"`
	Label            *string       `json:"label,omitempty"`
	ThinkingLevel    string        `json:"thinkingLevel,omitempty"`
	Provider         string        `json:"provider,omitempty"`
	ModelID          string        `json:"modelId,omitempty"`
	ActiveToolNames  []string      `json:"activeToolNames,omitempty"`
	Summary          string        `json:"summary,omitempty"`
	FirstKeptEntryID string        `json:"firstKeptEntryId,omitempty"`
	TokensBefore     int           `json:"tokensBefore,omitempty"`
	RetainedTail     []llm.Message `json:"retainedTail,omitempty"`
	FromID           string        `json:"fromId,omitempty"`
	CustomType       string        `json:"customType,omitempty"`
	Data             any           `json:"data,omitempty"`
	Content          any           `json:"content,omitempty"`
	Display          bool          `json:"display,omitempty"`
	Details          any           `json:"details,omitempty"`
	FromHook         bool          `json:"fromHook,omitempty"`
	Usage            *llm.Usage    `json:"usage,omitempty"`
	Name             string        `json:"name,omitempty"`
}

func BuildContextEntries added in v0.82.0

func BuildContextEntries(pathEntries []Entry, options ...SessionContextBuildOptions) []Entry

func DefaultContextEntryTransform added in v0.82.0

func DefaultContextEntryTransform(pathEntries []Entry) []Entry

type ExecOptions

type ExecOptions = harnessenv.ExecOptions

type ExecResult

type ExecResult = harnessenv.ExecResult

type ExecutionEnv

type ExecutionEnv = harnessenv.ExecutionEnv

type ExecutionError

type ExecutionError = harnessenv.ExecutionError

type FileError

type FileError = harnessenv.FileError

type FileInfo

type FileInfo = harnessenv.FileInfo

type FileOps

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

type FileSystem

type FileSystem = harnessenv.FileSystem

type InMemorySessionRepo

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

func NewInMemorySessionRepo

func NewInMemorySessionRepo() *InMemorySessionRepo

func (*InMemorySessionRepo) Create

func (r *InMemorySessionRepo) Create(id string, options ...SessionCreateOptions) (*Session, error)

func (*InMemorySessionRepo) Delete

func (r *InMemorySessionRepo) Delete(metadata SessionMetadata)

func (*InMemorySessionRepo) Fork

func (r *InMemorySessionRepo) Fork(sourceMetadata SessionMetadata, id string, entryID *string, includeEntry bool, options ...SessionForkOptions) (*Session, error)

func (*InMemorySessionRepo) List

func (*InMemorySessionRepo) Open

func (r *InMemorySessionRepo) Open(metadata SessionMetadata) (*Session, error)

type InMemorySessionStorage

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

func MustInMemorySessionStorage

func MustInMemorySessionStorage() *InMemorySessionStorage

func NewInMemorySessionStorage

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

func (*InMemorySessionStorage) AppendEntry

func (s *InMemorySessionStorage) AppendEntry(entry Entry) error

func (*InMemorySessionStorage) CreateEntryID

func (s *InMemorySessionStorage) CreateEntryID() string

func (*InMemorySessionStorage) Entries

func (s *InMemorySessionStorage) Entries(options ...SessionEntryCursorOptions) []Entry

func (*InMemorySessionStorage) Entry

func (s *InMemorySessionStorage) Entry(id string) (Entry, bool)

func (*InMemorySessionStorage) FindEntries

func (s *InMemorySessionStorage) FindEntries(entryType string) []Entry

func (*InMemorySessionStorage) Label

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

func (*InMemorySessionStorage) LeafID

func (s *InMemorySessionStorage) LeafID() (string, bool, error)

func (*InMemorySessionStorage) Metadata

func (*InMemorySessionStorage) PathToRoot

func (s *InMemorySessionStorage) PathToRoot(leafID *string) ([]Entry, error)

func (*InMemorySessionStorage) PathToRootOrCompaction added in v0.82.0

func (s *InMemorySessionStorage) PathToRootOrCompaction(leafID *string) ([]Entry, error)

func (*InMemorySessionStorage) SessionName added in v0.82.0

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

func (*InMemorySessionStorage) SessionStats added in v0.82.0

func (s *InMemorySessionStorage) SessionStats() SessionStats

func (*InMemorySessionStorage) SetLeafID

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

type JsonlSessionRepo

type JsonlSessionRepo struct {
	SessionsRoot string
}

func NewJsonlSessionRepo

func NewJsonlSessionRepo(root string) *JsonlSessionRepo

func (*JsonlSessionRepo) Create

func (r *JsonlSessionRepo) Create(cwd, id string, options ...SessionCreateOptions) (*Session, error)

func (*JsonlSessionRepo) Delete

func (r *JsonlSessionRepo) Delete(metadata SessionMetadata) error

func (*JsonlSessionRepo) Fork

func (r *JsonlSessionRepo) Fork(sourceMetadata SessionMetadata, cwd, id string, entryID *string, includeEntry bool, options ...SessionForkOptions) (*Session, error)

func (*JsonlSessionRepo) List

func (r *JsonlSessionRepo) List(cwd string) ([]SessionMetadata, error)

func (*JsonlSessionRepo) Open

func (r *JsonlSessionRepo) Open(metadata SessionMetadata) (*Session, error)

type JsonlSessionStorage

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

func CreateJsonlSessionStorage

func CreateJsonlSessionStorage(filePath string, metadata SessionMetadata) (*JsonlSessionStorage, error)

func OpenJsonlSessionStorage

func OpenJsonlSessionStorage(filePath string) (*JsonlSessionStorage, error)

func (*JsonlSessionStorage) AppendEntry

func (s *JsonlSessionStorage) AppendEntry(entry Entry) error

func (*JsonlSessionStorage) CreateEntryID

func (s *JsonlSessionStorage) CreateEntryID() string

func (*JsonlSessionStorage) Entries

func (s *JsonlSessionStorage) Entries(options ...SessionEntryCursorOptions) []Entry

func (*JsonlSessionStorage) Entry

func (s *JsonlSessionStorage) Entry(id string) (Entry, bool)

func (*JsonlSessionStorage) FindEntries

func (s *JsonlSessionStorage) FindEntries(entryType string) []Entry

func (*JsonlSessionStorage) Label

func (s *JsonlSessionStorage) Label(id string) (string, bool)

func (*JsonlSessionStorage) LeafID

func (s *JsonlSessionStorage) LeafID() (string, bool, error)

func (*JsonlSessionStorage) Metadata

func (s *JsonlSessionStorage) Metadata() SessionMetadata

func (*JsonlSessionStorage) PathToRoot

func (s *JsonlSessionStorage) PathToRoot(leafID *string) ([]Entry, error)

func (*JsonlSessionStorage) PathToRootOrCompaction added in v0.82.0

func (s *JsonlSessionStorage) PathToRootOrCompaction(leafID *string) ([]Entry, error)

func (*JsonlSessionStorage) SessionName added in v0.82.0

func (s *JsonlSessionStorage) SessionName() (string, bool)

func (*JsonlSessionStorage) SessionStats added in v0.82.0

func (s *JsonlSessionStorage) SessionStats() SessionStats

func (*JsonlSessionStorage) SetLeafID

func (s *JsonlSessionStorage) SetLeafID(leafID *string) error

type LoadSkillsOptions

type LoadSkillsOptions struct {
	IncludeRootMarkdownFiles bool
	RespectGitignore         bool
}

type LocalExecutionEnv

type LocalExecutionEnv = harnessenv.LocalExecutionEnv

func MustLocalExecutionEnv

func MustLocalExecutionEnv(cwd string, options ...LocalExecutionOption) *LocalExecutionEnv

func NewLocalExecutionEnv

func NewLocalExecutionEnv(cwd string, options ...LocalExecutionOption) (*LocalExecutionEnv, error)

type LocalExecutionOption

type LocalExecutionOption = harnessenv.LocalExecutionOption

func WithShellPath

func WithShellPath(path string) LocalExecutionOption
type NavigateTreeOptions struct {
	Summarize           bool
	CustomInstructions  string
	ReplaceInstructions bool
	Label               string
}
type NavigateTreeResult struct {
	Cancelled    bool
	EditorText   string
	SummaryEntry *Entry
}

type NowMillisFunc

type NowMillisFunc = sessionid.NowMillisFunc

type Optional

type Optional[T any] struct {
	Set   bool
	Value T
}

func Some

func Some[T any](value T) Optional[T]

type PromptTemplate

type PromptTemplate struct {
	Name        string
	Description string
	Content     string
}

type PromptTemplateDiagnostic

type PromptTemplateDiagnostic struct {
	Type    string
	Code    string
	Message string
	Path    string
	Source  any
}

type PromptTemplateResult

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

func LoadPromptTemplates

func LoadPromptTemplates(paths ...string) PromptTemplateResult

type RandomBytesFunc

type RandomBytesFunc = sessionid.RandomBytesFunc

type RemoveOptions

type RemoveOptions = harnessenv.RemoveOptions

type Session

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

func NewSession

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

func (*Session) AppendActiveToolsChange added in v0.82.0

func (s *Session) AppendActiveToolsChange(activeToolNames []string) (string, error)

func (*Session) AppendCompaction

func (s *Session) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int, details ...any) (string, error)

func (*Session) AppendCompactionWithOptions

func (s *Session) AppendCompactionWithOptions(summary, firstKeptEntryID string, tokensBefore int, options SessionEntryOptions) (string, error)

func (*Session) AppendCustomEntry added in v0.82.0

func (s *Session) AppendCustomEntry(customType string, data any) (string, error)

func (*Session) AppendCustomMessageEntry

func (s *Session) AppendCustomMessageEntry(customType string, content any, display bool, details any) (string, error)

func (*Session) AppendLabel

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

func (*Session) AppendMessage

func (s *Session) AppendMessage(message llm.Message) (string, error)

func (*Session) AppendModelChange

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

func (*Session) AppendSessionName

func (s *Session) AppendSessionName(name string) (string, error)

func (*Session) AppendThinkingLevelChange

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

func (*Session) Branch

func (s *Session) Branch(fromID *string) ([]Entry, error)

func (*Session) BuildContext

func (s *Session) BuildContext(options ...SessionContextBuildOptions) (SessionContext, error)

func (*Session) BuildContextEntries added in v0.82.0

func (s *Session) BuildContextEntries(options ...SessionContextBuildOptions) ([]Entry, error)

func (*Session) Entries

func (s *Session) Entries(options ...SessionEntryCursorOptions) []Entry

func (*Session) Entry

func (s *Session) Entry(id string) (Entry, bool)

func (*Session) Label

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

func (*Session) LeafID

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

func (*Session) Metadata

func (s *Session) Metadata() SessionMetadata

func (*Session) MoveTo

func (s *Session) MoveTo(entryID *string, summary string, details ...any) (*string, error)

func (*Session) MoveToWithOptions

func (s *Session) MoveToWithOptions(entryID *string, summary string, options SessionEntryOptions) (*string, error)

func (*Session) SessionName

func (s *Session) SessionName() (string, bool)

func (*Session) Stats added in v0.82.0

func (s *Session) Stats() SessionStats

func (*Session) Storage

func (s *Session) Storage() SessionStorage

type SessionContext

type SessionContext struct {
	Messages        []llm.Message
	ThinkingLevel   string
	Model           *SessionModel
	ActiveToolNames []string

	// ModelProvider and ModelID are kept as compatibility mirrors. Model is the
	// canonical representation for new callers.
	ModelProvider string
	ModelID       string
}

func BuildSessionContext

func BuildSessionContext(pathEntries []Entry, options ...SessionContextBuildOptions) SessionContext

type SessionContextBuildOptions added in v0.82.0

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

type SessionCreateOptions added in v0.82.0

type SessionCreateOptions struct {
	ParentSessionPath string
	Metadata          map[string]any
}

type SessionEntryCursorOptions added in v0.82.0

type SessionEntryCursorOptions struct {
	AfterEntrySeq int
	Limit         int
}

type SessionEntryOptions

type SessionEntryOptions struct {
	Details      any
	FromHook     bool
	Usage        *llm.Usage
	RetainedTail []llm.Message
}

type SessionError

type SessionError struct {
	Code string
	Err  error
}

func (*SessionError) Error

func (e *SessionError) Error() string

func (*SessionError) Unwrap

func (e *SessionError) Unwrap() error

type SessionForkOptions added in v0.82.0

type SessionForkOptions struct {
	ParentSessionPath string
	Metadata          map[string]any
}

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          map[string]any `json:"metadata,omitempty"`
}

func LoadJsonlSessionMetadata

func LoadJsonlSessionMetadata(filePath string) (SessionMetadata, error)

type SessionModel added in v0.82.0

type SessionModel struct {
	Provider string
	ModelID  string
}

type SessionStats added in v0.82.0

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

type SessionStorage

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

type Shell

type Shell = harnessenv.Shell

type SimpleCompletionRuntime added in v0.82.0

type SimpleCompletionRuntime interface {
	CompleteSimple(context.Context, llm.Model, llm.Context, llm.ModelsStreamOptions) (llm.Message, error)
}

SimpleCompletionRuntime is the minimal model-runtime contract required by generated summaries. Both llm.Models and coding-agent's ModelRuntime satisfy this interface, so the harness owns summary policy without owning provider registration or credentials.

type Skill

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

type SkillDiagnostic

type SkillDiagnostic struct {
	Type    string
	Code    string
	Message string
	Path    string
	Source  any
}

type SkillResult

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

func LoadSkills

func LoadSkills(paths ...string) SkillResult

func LoadSkillsWithOptions

func LoadSkillsWithOptions(options LoadSkillsOptions, paths ...string) SkillResult

type SourcedPromptTemplate

type SourcedPromptTemplate struct {
	PromptTemplate PromptTemplate
	Source         any
}

type SourcedPromptTemplateResult

type SourcedPromptTemplateResult struct {
	PromptTemplates []SourcedPromptTemplate
	Diagnostics     []PromptTemplateDiagnostic
}

func LoadSourcedPromptTemplates

func LoadSourcedPromptTemplates(inputs map[string]any) SourcedPromptTemplateResult

type SourcedSkill

type SourcedSkill struct {
	Skill  Skill
	Source any
}

type SourcedSkillResult

type SourcedSkillResult struct {
	Skills      []SourcedSkill
	Diagnostics []SkillDiagnostic
}

func LoadSourcedSkills

func LoadSourcedSkills(inputs map[string]any) SourcedSkillResult

type SummaryWithUsage added in v0.82.0

type SummaryWithUsage struct {
	Text  string
	Usage llm.Usage
}

SummaryWithUsage is the generated text and provider usage for one summary request.

func GenerateSummaryWithUsage added in v0.82.0

func GenerateSummaryWithUsage(
	ctx context.Context,
	messages []llm.Message,
	model llm.Model,
	maxTokens int,
	previousSummary string,
	focus string,
	options CompactOptions,
) (SummaryWithUsage, error)

GenerateSummaryWithUsage generates or updates a conversation summary while preserving the provider usage from the successful terminal attempt.

type SystemPromptContext

type SystemPromptContext struct {
	Env           any
	Session       *Session
	Model         llm.Model
	ThinkingLevel string
	ActiveTools   []core.AgentTool
	Resources     AgentHarnessResources
}

type TempFileOptions

type TempFileOptions = harnessenv.TempFileOptions

type TruncationOptions

type TruncationOptions = utils.TruncationOptions

type TruncationResult

type TruncationResult = utils.TruncationResult

func TruncateHead

func TruncateHead(content string, options TruncationOptions) TruncationResult

func TruncateTail

func TruncateTail(content string, options TruncationOptions) TruncationResult

Directories

Path Synopsis
Package tools provides reusable filesystem and shell tools for AgentHarness.
Package tools provides reusable filesystem and shell tools for AgentHarness.

Jump to

Keyboard shortcuts

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