agent

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDepthLimitExceeded   = errors.New("sub-turn depth limit exceeded")
	ErrInvalidSubTurnConfig = errors.New("invalid sub-turn config")
	ErrConcurrencyTimeout   = errors.New("timeout waiting for concurrency slot")
)

Functions

func EstimateMessageTokens added in v0.2.6

func EstimateMessageTokens(msg providers.Message) int

EstimateMessageTokens estimates the token count for a single message. Delegates to the shared tokenizer package for consistency across agent and seahorse.

func EstimateToolDefsTokens added in v0.2.6

func EstimateToolDefsTokens(defs []providers.ToolDefinition) int

EstimateToolDefsTokens estimates the total token cost of tool definitions as they appear in the LLM request. Delegates to the shared tokenizer package.

func RegisterBuiltinHook added in v0.2.4

func RegisterBuiltinHook(name string, factory BuiltinHookFactory) error

RegisterBuiltinHook registers a named in-process hook factory for config-driven mounting.

func RegisterContextManager added in v0.2.5

func RegisterContextManager(name string, factory ContextManagerFactory) error

RegisterContextManager registers a named ContextManager factory.

func SpawnSubTurn added in v0.2.4

func SpawnSubTurn(ctx context.Context, cfg SubTurnConfig) (*tools.ToolResult, error)

SpawnSubTurn is the exported entry point for tools to spawn sub-turns. It retrieves AgentLoop and parent turnState from context and delegates to spawnSubTurn.

func TurnStateFromContext added in v0.2.4

func TurnStateFromContext(ctx context.Context) *turnState

TurnStateFromContext retrieves turnState from context (exported for tools)

func WithAgentLoop added in v0.2.4

func WithAgentLoop(ctx context.Context, al *AgentLoop) context.Context

WithAgentLoop injects AgentLoop into context for tool access

Types

type ActiveTurnInfo added in v0.2.4

type ActiveTurnInfo struct {
	TurnID       string
	AgentID      string
	SessionKey   string
	Channel      string
	ChatID       string
	UserMessage  string
	Phase        TurnPhase
	Iteration    int
	StartedAt    time.Time
	Depth        int
	ParentTurnID string
	ChildTurnIDs []string
}

type AgentContextDefinition added in v0.2.4

type AgentContextDefinition struct {
	Source AgentDefinitionSource  `json:"source,omitempty"`
	Agent  *AgentPromptDefinition `json:"agent,omitempty"`
	Soul   *SoulDefinition        `json:"soul,omitempty"`
	User   *UserDefinition        `json:"user,omitempty"`
}

AgentContextDefinition captures the workspace agent definition in a runtime-friendly shape.

type AgentDefinitionSource added in v0.2.4

type AgentDefinitionSource string

AgentDefinitionSource identifies which agent bootstrap file produced the definition.

const (
	// AgentDefinitionSourceAgent indicates the new AGENT.md format.
	AgentDefinitionSourceAgent AgentDefinitionSource = "AGENT.md"
	// AgentDefinitionSourceAgents indicates the legacy AGENTS.md format.
	AgentDefinitionSourceAgents AgentDefinitionSource = "AGENTS.md"
)

type AgentFrontmatter added in v0.2.4

type AgentFrontmatter struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Tools       []string       `json:"tools,omitempty"`
	Model       string         `json:"model,omitempty"`
	MaxTurns    *int           `json:"maxTurns,omitempty"`
	Skills      []string       `json:"skills,omitempty"`
	MCPServers  []string       `json:"mcpServers,omitempty"`
	Fields      map[string]any `json:"fields,omitempty"`
}

AgentFrontmatter holds machine-readable AGENT.md configuration.

Known fields are exposed directly for convenience. Fields keeps the full parsed frontmatter so future refactors can read additional keys without changing the loader contract again.

type AgentInstance added in v0.2.0

type AgentInstance struct {
	ID                        string
	Name                      string
	Model                     string
	Fallbacks                 []string
	Workspace                 string
	MaxIterations             int
	MaxTokens                 int
	Temperature               float64
	ThinkingLevel             ThinkingLevel
	ContextWindow             int
	SummarizeMessageThreshold int
	SummarizeTokenPercent     int
	Provider                  providers.LLMProvider
	Sessions                  session.SessionStore
	ContextBuilder            *ContextBuilder
	Tools                     *tools.ToolRegistry
	Subagents                 *config.SubagentsConfig
	SkillsFilter              []string
	Candidates                []providers.FallbackCandidate

	// Router is non-nil when model routing is configured and the light model
	// was successfully resolved. It scores each incoming message and decides
	// whether to route to LightCandidates or stay with Candidates.
	Router *routing.Router
	// LightCandidates holds the resolved provider candidates for the light model.
	// Pre-computed at agent creation to avoid repeated model_list lookups at runtime.
	LightCandidates []providers.FallbackCandidate
	// LightProvider is the concrete provider instance for the configured light model.
	// It is only used when routing selects the light tier for a turn.
	LightProvider providers.LLMProvider
	// CandidateProviders maps "provider/model" keys to per-candidate LLMProvider
	// instances. This allows each fallback model to use its own api_base and api_key
	// from model_list, instead of inheriting the primary model's provider config.
	CandidateProviders map[string]providers.LLMProvider
}

AgentInstance represents a fully configured agent with its own workspace, session manager, context builder, and tool registry.

func NewAgentInstance added in v0.2.0

func NewAgentInstance(
	agentCfg *config.AgentConfig,
	defaults *config.AgentDefaults,
	cfg *config.Config,
	provider providers.LLMProvider,
) *AgentInstance

NewAgentInstance creates an agent instance from config.

func (*AgentInstance) Close added in v0.2.2

func (a *AgentInstance) Close() error

Close releases resources held by the agent's session store.

type AgentLoop

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

func AgentLoopFromContext added in v0.2.4

func AgentLoopFromContext(ctx context.Context) *AgentLoop

AgentLoopFromContext retrieves AgentLoop from context

func NewAgentLoop

func NewAgentLoop(
	cfg *config.Config,
	msgBus *bus.MessageBus,
	provider providers.LLMProvider,
) *AgentLoop

func (*AgentLoop) Close added in v0.2.2

func (al *AgentLoop) Close()

Close releases resources held by agent session stores. Call after Stop.

func (*AgentLoop) Continue added in v0.2.4

func (al *AgentLoop) Continue(ctx context.Context, sessionKey, channel, chatID string) (string, error)

Continue resumes an idle agent by dequeuing any pending steering messages and running them through the agent loop. This is used when the agent's last message was from the assistant (i.e., it has stopped processing) and the user has since enqueued steering messages.

If no steering messages are pending, it returns an empty string.

func (*AgentLoop) EventDrops added in v0.2.4

func (al *AgentLoop) EventDrops(kind EventKind) int64

EventDrops returns the number of dropped events for the given kind.

func (*AgentLoop) GetActiveTurn added in v0.2.4

func (al *AgentLoop) GetActiveTurn() *ActiveTurnInfo

func (*AgentLoop) GetActiveTurnBySession added in v0.2.4

func (al *AgentLoop) GetActiveTurnBySession(sessionKey string) *ActiveTurnInfo

func (*AgentLoop) GetConfig added in v0.2.3

func (al *AgentLoop) GetConfig() *config.Config

func (*AgentLoop) GetRegistry added in v0.2.3

func (al *AgentLoop) GetRegistry() *AgentRegistry

func (*AgentLoop) GetStartupInfo added in v0.1.1

func (al *AgentLoop) GetStartupInfo() map[string]any

func (*AgentLoop) HardAbort added in v0.2.4

func (al *AgentLoop) HardAbort(sessionKey string) error

HardAbort immediately cancels the running agent loop for the given session, cascading the cancellation to all child SubTurns. This is a destructive operation that terminates execution without waiting for graceful cleanup.

Use this when the user explicitly requests immediate termination (e.g., "stop now", "abort"). For graceful interruption that allows the agent to finish the current tool and summarize, use Steer() instead.

func (*AgentLoop) InjectFollowUp added in v0.2.4

func (al *AgentLoop) InjectFollowUp(msg providers.Message) error

InjectFollowUp enqueues a message to be automatically processed after the current turn completes. Unlike Steer(), which interrupts the current execution, InjectFollowUp waits for the current turn to finish naturally before processing the message.

This is useful for: - Automated workflows that need to chain multiple turns - Background tasks that should run after the main task completes - Scheduled follow-up actions

The message will be processed via Continue() when the agent becomes idle.

func (*AgentLoop) InjectSteering added in v0.2.4

func (al *AgentLoop) InjectSteering(msg providers.Message) error

InjectSteering is an alias for Steer() to match the design document naming. It injects a steering message into the currently running agent loop.

func (*AgentLoop) InterruptGraceful added in v0.2.4

func (al *AgentLoop) InterruptGraceful(hint string) error

func (*AgentLoop) InterruptHard deprecated added in v0.2.4

func (al *AgentLoop) InterruptHard() error

InterruptHard aborts an arbitrary active turn. In parallel mode this may target the wrong session. Prefer HardAbort(sessionKey) instead.

Deprecated: Use HardAbort(sessionKey) for session-safe aborts.

func (*AgentLoop) MountHook added in v0.2.4

func (al *AgentLoop) MountHook(reg HookRegistration) error

MountHook registers an in-process hook on the agent loop.

func (*AgentLoop) MountProcessHook added in v0.2.4

func (al *AgentLoop) MountProcessHook(ctx context.Context, name string, opts ProcessHookOptions) error

func (*AgentLoop) ProcessDirect

func (al *AgentLoop) ProcessDirect(
	ctx context.Context,
	content, sessionKey string,
) (string, error)

func (*AgentLoop) ProcessDirectWithChannel added in v0.1.1

func (al *AgentLoop) ProcessDirectWithChannel(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
) (string, error)

func (*AgentLoop) ProcessHeartbeat added in v0.1.2

func (al *AgentLoop) ProcessHeartbeat(
	ctx context.Context,
	content, channel, chatID string,
) (string, error)

func (*AgentLoop) PublishResponseIfNeeded added in v0.2.5

func (al *AgentLoop) PublishResponseIfNeeded(ctx context.Context, channel, chatID, sessionKey, response string)

func (*AgentLoop) RecordLastChannel added in v0.1.2

func (al *AgentLoop) RecordLastChannel(channel string) error

func (*AgentLoop) RecordLastChatID added in v0.1.2

func (al *AgentLoop) RecordLastChatID(chatID string) error

func (*AgentLoop) RegisterTool added in v0.1.1

func (al *AgentLoop) RegisterTool(tool tools.Tool)

func (*AgentLoop) ReloadProviderAndConfig added in v0.2.3

func (al *AgentLoop) ReloadProviderAndConfig(
	ctx context.Context,
	provider providers.LLMProvider,
	cfg *config.Config,
) error

ReloadProviderAndConfig atomically swaps the provider and config with proper synchronization. It uses a context to allow timeout control from the caller. Returns an error if the reload fails or context is canceled.

func (*AgentLoop) Run

func (al *AgentLoop) Run(ctx context.Context) error

func (*AgentLoop) SetChannelManager added in v0.1.2

func (al *AgentLoop) SetChannelManager(cm *channels.Manager)

func (*AgentLoop) SetMediaStore added in v0.2.0

func (al *AgentLoop) SetMediaStore(s media.MediaStore)

func (*AgentLoop) SetReloadFunc added in v0.2.4

func (al *AgentLoop) SetReloadFunc(fn func() error)

func (*AgentLoop) SetSteeringMode added in v0.2.4

func (al *AgentLoop) SetSteeringMode(mode SteeringMode)

SetSteeringMode updates the steering mode.

func (*AgentLoop) SetTranscriber added in v0.2.1

func (al *AgentLoop) SetTranscriber(t asr.Transcriber)

func (*AgentLoop) Steer added in v0.2.4

func (al *AgentLoop) Steer(msg providers.Message) error

Steer enqueues a user message to be injected into the currently running agent loop. The message will be picked up after the current tool finishes executing, causing any remaining tool calls in the batch to be skipped.

func (*AgentLoop) SteeringMode added in v0.2.4

func (al *AgentLoop) SteeringMode() SteeringMode

SteeringMode returns the current steering mode.

func (*AgentLoop) Stop

func (al *AgentLoop) Stop()

func (*AgentLoop) SubscribeEvents added in v0.2.4

func (al *AgentLoop) SubscribeEvents(buffer int) EventSubscription

SubscribeEvents registers a subscriber for agent-loop events.

func (*AgentLoop) UnmountHook added in v0.2.4

func (al *AgentLoop) UnmountHook(name string)

UnmountHook removes a previously registered in-process hook.

func (*AgentLoop) UnsubscribeEvents added in v0.2.4

func (al *AgentLoop) UnsubscribeEvents(id uint64)

UnsubscribeEvents removes a previously registered event subscriber.

type AgentLoopSpawner added in v0.2.4

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

AgentLoopSpawner implements tools.SubTurnSpawner interface. This allows tools to spawn sub-turns without circular dependency.

func NewSubTurnSpawner added in v0.2.4

func NewSubTurnSpawner(al *AgentLoop) *AgentLoopSpawner

NewSubTurnSpawner creates a SubTurnSpawner for the given AgentLoop.

func (*AgentLoopSpawner) SpawnSubTurn added in v0.2.4

func (s *AgentLoopSpawner) SpawnSubTurn(
	ctx context.Context,
	cfg tools.SubTurnConfig,
) (*tools.ToolResult, error)

SpawnSubTurn implements tools.SubTurnSpawner interface.

type AgentPromptDefinition added in v0.2.4

type AgentPromptDefinition struct {
	Path           string           `json:"path"`
	Raw            string           `json:"raw"`
	Body           string           `json:"body"`
	RawFrontmatter string           `json:"raw_frontmatter,omitempty"`
	Frontmatter    AgentFrontmatter `json:"frontmatter"`
}

AgentPromptDefinition represents the parsed AGENT.md or AGENTS.md prompt file.

type AgentRegistry added in v0.2.0

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

AgentRegistry manages multiple agent instances and routes messages to them.

func NewAgentRegistry added in v0.2.0

func NewAgentRegistry(
	cfg *config.Config,
	provider providers.LLMProvider,
) *AgentRegistry

NewAgentRegistry creates a registry from config, instantiating all agents.

func (*AgentRegistry) CanSpawnSubagent added in v0.2.0

func (r *AgentRegistry) CanSpawnSubagent(parentAgentID, targetAgentID string) bool

CanSpawnSubagent checks if parentAgentID is allowed to spawn targetAgentID.

func (*AgentRegistry) Close added in v0.2.2

func (r *AgentRegistry) Close()

Close releases resources held by all registered agents.

func (*AgentRegistry) ForEachTool added in v0.2.1

func (r *AgentRegistry) ForEachTool(name string, fn func(tools.Tool))

ForEachTool calls fn for every tool registered under the given name across all agents. This is useful for propagating dependencies (e.g. MediaStore) to tools after registry construction.

func (*AgentRegistry) GetAgent added in v0.2.0

func (r *AgentRegistry) GetAgent(agentID string) (*AgentInstance, bool)

GetAgent returns the agent instance for a given ID.

func (*AgentRegistry) GetDefaultAgent added in v0.2.0

func (r *AgentRegistry) GetDefaultAgent() *AgentInstance

GetDefaultAgent returns the default agent instance.

func (*AgentRegistry) ListAgentIDs added in v0.2.0

func (r *AgentRegistry) ListAgentIDs() []string

ListAgentIDs returns all registered agent IDs.

func (*AgentRegistry) ResolveRoute added in v0.2.0

func (r *AgentRegistry) ResolveRoute(inbound bus.InboundContext) routing.ResolvedRoute

ResolveRoute determines which agent handles the normalized inbound context.

type ApprovalDecision added in v0.2.4

type ApprovalDecision struct {
	Approved bool   `json:"approved"`
	Reason   string `json:"reason,omitempty"`
}

type AssembleRequest added in v0.2.5

type AssembleRequest struct {
	SessionKey string // session identifier
	Budget     int    // context window in tokens
	MaxTokens  int    // max response tokens
}

AssembleRequest is the input to Assemble.

type AssembleResponse added in v0.2.5

type AssembleResponse struct {
	History []providers.Message // assembled conversation history for BuildMessages
	Summary string              // conversation summary embedded into system prompt by BuildMessages
}

AssembleResponse is the output of Assemble.

type BuiltinHookFactory added in v0.2.4

type BuiltinHookFactory func(ctx context.Context, spec config.BuiltinHookConfig) (any, error)

BuiltinHookFactory constructs an in-process hook from config.

type CompactRequest added in v0.2.5

type CompactRequest struct {
	SessionKey string                // session identifier
	Reason     ContextCompressReason // proactive_budget | llm_retry | summarize
	Budget     int                   // context window budget (used for retry aggressive compaction)
}

CompactRequest is the input to Compact.

type ContextBuilder

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

func NewContextBuilder

func NewContextBuilder(workspace string) *ContextBuilder

func (*ContextBuilder) AddAssistantMessage

func (cb *ContextBuilder) AddAssistantMessage(
	messages []providers.Message,
	content string,
	toolCalls []map[string]any,
) []providers.Message

func (*ContextBuilder) AddToolResult

func (cb *ContextBuilder) AddToolResult(
	messages []providers.Message,
	toolCallID, toolName, result string,
) []providers.Message

func (*ContextBuilder) BuildMessages

func (cb *ContextBuilder) BuildMessages(
	history []providers.Message,
	summary string,
	currentMessage string,
	media []string,
	channel, chatID, senderID, senderDisplayName string,
	activeSkills ...string,
) []providers.Message

func (*ContextBuilder) BuildSystemPrompt

func (cb *ContextBuilder) BuildSystemPrompt() string

func (*ContextBuilder) BuildSystemPromptWithCache added in v0.2.0

func (cb *ContextBuilder) BuildSystemPromptWithCache() string

BuildSystemPromptWithCache returns the cached system prompt if available and source files haven't changed, otherwise builds and caches it. Source file changes are detected via mtime checks (cheap stat calls).

func (*ContextBuilder) EstimateSystemTokens added in v0.2.7

func (cb *ContextBuilder) EstimateSystemTokens(summary string, activeSkills []string) int

EstimateSystemTokens estimates the token count of the full system message that would be sent to the LLM, mirroring the composition logic in BuildMessages. It includes: static prompt, dynamic context, active skills, and summary with wrapping prefixes and separators. This avoids needing all per-request parameters that BuildMessages requires (media, channel, chatID, sender, etc.).

func (*ContextBuilder) GetSkillsInfo added in v0.1.1

func (cb *ContextBuilder) GetSkillsInfo() map[string]any

GetSkillsInfo returns information about loaded skills.

func (*ContextBuilder) InvalidateCache added in v0.2.0

func (cb *ContextBuilder) InvalidateCache()

InvalidateCache clears the cached system prompt. Normally not needed because the cache auto-invalidates via mtime checks, but this is useful for tests or explicit reload commands.

func (*ContextBuilder) ListSkillNames added in v0.2.4

func (cb *ContextBuilder) ListSkillNames() []string

func (*ContextBuilder) LoadAgentDefinition added in v0.2.4

func (cb *ContextBuilder) LoadAgentDefinition() AgentContextDefinition

LoadAgentDefinition parses the workspace agent bootstrap files.

It prefers the new AGENT.md format and its paired SOUL.md file. When the structured files are absent, it falls back to the legacy AGENTS.md layout so the current runtime can transition incrementally.

func (*ContextBuilder) LoadBootstrapFiles

func (cb *ContextBuilder) LoadBootstrapFiles() string

func (*ContextBuilder) ResolveSkillName added in v0.2.4

func (cb *ContextBuilder) ResolveSkillName(name string) (string, bool)

func (*ContextBuilder) WithSplitOnMarker added in v0.2.5

func (cb *ContextBuilder) WithSplitOnMarker(enabled bool) *ContextBuilder

func (*ContextBuilder) WithToolDiscovery added in v0.2.2

func (cb *ContextBuilder) WithToolDiscovery(useBM25, useRegex bool) *ContextBuilder

type ContextCompressPayload added in v0.2.4

type ContextCompressPayload struct {
	Reason            ContextCompressReason
	DroppedMessages   int
	RemainingMessages int
}

ContextCompressPayload describes a forced history compression.

type ContextCompressReason added in v0.2.4

type ContextCompressReason string

ContextCompressReason identifies why emergency compression ran.

const (
	// ContextCompressReasonProactive indicates compression before the first LLM call.
	ContextCompressReasonProactive ContextCompressReason = "proactive_budget"
	// ContextCompressReasonRetry indicates compression during context-error retry handling.
	ContextCompressReasonRetry ContextCompressReason = "llm_retry"
	// ContextCompressReasonSummarize indicates post-turn async summarization.
	ContextCompressReasonSummarize ContextCompressReason = "summarize"
)

type ContextManager added in v0.2.5

type ContextManager interface {
	// Assemble builds budget-aware context from the ContextManager's own storage.
	// Called before BuildMessages. Returns assembled messages ready for LLM.
	Assemble(ctx context.Context, req *AssembleRequest) (*AssembleResponse, error)

	// Compact compresses conversation history.
	// Called after turn completes (may be async internally) and on context overflow (sync).
	Compact(ctx context.Context, req *CompactRequest) error

	// Ingest records a message into the ContextManager's own storage.
	// Called after each message is persisted to session JSONL.
	Ingest(ctx context.Context, req *IngestRequest) error

	// Clear removes all stored context for a session (messages, summaries, etc.).
	// Called when the user issues /clear or /reset.
	Clear(ctx context.Context, sessionKey string) error
}

ContextManager manages conversation context via a pluggable strategy. Exactly ONE ContextManager is active per AgentLoop, selected by config. The default ("legacy") preserves current summarization behavior.

type ContextManagerFactory added in v0.2.5

type ContextManagerFactory func(cfg json.RawMessage, al *AgentLoop) (ContextManager, error)

ContextManagerFactory constructs a ContextManager from config. al provides access to the AgentLoop's runtime resources (provider, model, workspace, etc.) cfg is the raw JSON configuration from config.json (may be nil).

type Control added in v0.2.7

type Control int
const (
	// ControlContinue tells the coordinator to jump back to the top of the turn loop
	// (equivalent to the original "goto turnLoop").
	ControlContinue Control = iota
	// ControlBreak tells the coordinator to exit the turn loop and proceed to Finalize.
	ControlBreak
	// ControlToolLoop tells the coordinator to execute the tool loop.
	ControlToolLoop
)

type DispatchRequest added in v0.2.7

type DispatchRequest struct {
	SessionKey     string
	SessionAliases []string
	InboundContext *bus.InboundContext
	RouteResult    *routing.ResolvedRoute
	SessionScope   *session.SessionScope
	UserMessage    string
	Media          []string
}

DispatchRequest is the normalized runtime input passed into the agent loop after routing and session allocation have completed.

func (DispatchRequest) Channel added in v0.2.7

func (r DispatchRequest) Channel() string

func (DispatchRequest) ChatID added in v0.2.7

func (r DispatchRequest) ChatID() string

func (DispatchRequest) MessageID added in v0.2.7

func (r DispatchRequest) MessageID() string

func (DispatchRequest) ReplyToMessageID added in v0.2.7

func (r DispatchRequest) ReplyToMessageID() string

func (DispatchRequest) SenderID added in v0.2.7

func (r DispatchRequest) SenderID() string

type ErrorPayload added in v0.2.4

type ErrorPayload struct {
	Stage   string
	Message string
}

ErrorPayload describes an execution error inside the agent loop.

type Event added in v0.2.4

type Event struct {
	Kind    EventKind
	Time    time.Time
	Meta    EventMeta
	Context *TurnContext
	Payload any
}

Event is the structured envelope broadcast by the agent EventBus.

type EventBus added in v0.2.4

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

EventBus is a lightweight multi-subscriber broadcaster for agent-loop events.

func NewEventBus added in v0.2.4

func NewEventBus() *EventBus

NewEventBus creates a new in-process event broadcaster.

func (*EventBus) Close added in v0.2.4

func (b *EventBus) Close()

Close closes all subscriber channels and stops future broadcasts.

func (*EventBus) Dropped added in v0.2.4

func (b *EventBus) Dropped(kind EventKind) int64

Dropped returns the number of dropped events for a given kind.

func (*EventBus) Emit added in v0.2.4

func (b *EventBus) Emit(evt Event)

Emit broadcasts an event to all current subscribers without blocking. When a subscriber channel is full, the event is dropped for that subscriber.

func (*EventBus) Subscribe added in v0.2.4

func (b *EventBus) Subscribe(buffer int) EventSubscription

Subscribe registers a new subscriber with the requested channel buffer size. A non-positive buffer uses the default size.

func (*EventBus) Unsubscribe added in v0.2.4

func (b *EventBus) Unsubscribe(id uint64)

Unsubscribe removes a subscriber and closes its channel.

type EventKind added in v0.2.4

type EventKind uint8

EventKind identifies a structured agent-loop event.

const (
	// EventKindTurnStart is emitted when a turn begins processing.
	EventKindTurnStart EventKind = iota
	// EventKindTurnEnd is emitted when a turn finishes, successfully or with an error.
	EventKindTurnEnd
	// EventKindLLMRequest is emitted before a provider chat request is made.
	EventKindLLMRequest
	// EventKindLLMDelta is emitted when a streaming provider yields a partial delta.
	EventKindLLMDelta
	// EventKindLLMResponse is emitted after a provider chat response is received.
	EventKindLLMResponse
	// EventKindLLMRetry is emitted when an LLM request is retried.
	EventKindLLMRetry
	// EventKindContextCompress is emitted when session history is forcibly compressed.
	EventKindContextCompress
	// EventKindSessionSummarize is emitted when asynchronous summarization completes.
	EventKindSessionSummarize
	// EventKindToolExecStart is emitted immediately before a tool executes.
	EventKindToolExecStart
	// EventKindToolExecEnd is emitted immediately after a tool finishes executing.
	EventKindToolExecEnd
	// EventKindToolExecSkipped is emitted when a queued tool call is skipped.
	EventKindToolExecSkipped
	// EventKindSteeringInjected is emitted when queued steering is injected into context.
	EventKindSteeringInjected
	// EventKindFollowUpQueued is emitted when an async tool queues a follow-up system message.
	EventKindFollowUpQueued
	// EventKindInterruptReceived is emitted when a soft interrupt message is accepted.
	EventKindInterruptReceived
	// EventKindSubTurnSpawn is emitted when a sub-turn is spawned.
	EventKindSubTurnSpawn
	// EventKindSubTurnEnd is emitted when a sub-turn finishes.
	EventKindSubTurnEnd
	// EventKindSubTurnResultDelivered is emitted when a sub-turn result is delivered.
	EventKindSubTurnResultDelivered
	// EventKindSubTurnOrphan is emitted when a sub-turn result cannot be delivered.
	EventKindSubTurnOrphan
	// EventKindError is emitted when a turn encounters an execution error.
	EventKindError
)

func (EventKind) String added in v0.2.4

func (k EventKind) String() string

String returns the stable string form of an EventKind.

type EventMeta added in v0.2.4

type EventMeta struct {
	AgentID      string
	TurnID       string
	ParentTurnID string
	SessionKey   string
	Iteration    int
	TracePath    string
	Source       string
	// contains filtered or unexported fields
}

EventMeta contains correlation fields shared by all agent-loop events.

type EventObserver added in v0.2.4

type EventObserver interface {
	OnEvent(ctx context.Context, evt Event) error
}

type EventSubscription added in v0.2.4

type EventSubscription struct {
	ID uint64
	C  <-chan Event
}

EventSubscription identifies a subscriber channel returned by EventBus.Subscribe.

type FollowUpQueuedPayload added in v0.2.4

type FollowUpQueuedPayload struct {
	SourceTool string
	ContentLen int
}

FollowUpQueuedPayload describes an async follow-up queued back into the inbound bus.

type HookAction added in v0.2.4

type HookAction string
const (
	HookActionContinue  HookAction = "continue"
	HookActionModify    HookAction = "modify"
	HookActionRespond   HookAction = "respond" // Return result directly, skip tool execution. SECURITY: This bypasses ApproveTool checks, allowing hooks to return results for any tool (including sensitive ones like bash) without approval. Use with caution.
	HookActionDenyTool  HookAction = "deny_tool"
	HookActionAbortTurn HookAction = "abort_turn"
	HookActionHardAbort HookAction = "hard_abort"
)

type HookDecision added in v0.2.4

type HookDecision struct {
	Action HookAction `json:"action"`
	Reason string     `json:"reason,omitempty"`
}

type HookManager added in v0.2.4

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

func NewHookManager added in v0.2.4

func NewHookManager(eventBus *EventBus) *HookManager

func (*HookManager) AfterLLM added in v0.2.4

func (*HookManager) AfterTool added in v0.2.4

func (*HookManager) ApproveTool added in v0.2.4

func (hm *HookManager) ApproveTool(ctx context.Context, req *ToolApprovalRequest) ApprovalDecision

func (*HookManager) BeforeLLM added in v0.2.4

func (*HookManager) BeforeTool added in v0.2.4

func (*HookManager) Close added in v0.2.4

func (hm *HookManager) Close()

func (*HookManager) ConfigureTimeouts added in v0.2.4

func (hm *HookManager) ConfigureTimeouts(observer, interceptor, approval time.Duration)

func (*HookManager) Mount added in v0.2.4

func (hm *HookManager) Mount(reg HookRegistration) error

func (*HookManager) Unmount added in v0.2.4

func (hm *HookManager) Unmount(name string)

type HookRegistration added in v0.2.4

type HookRegistration struct {
	Name     string
	Priority int
	Source   HookSource
	Hook     any
}

func NamedHook added in v0.2.4

func NamedHook(name string, hook any) HookRegistration

type HookSource added in v0.2.4

type HookSource uint8
const (
	HookSourceInProcess HookSource = iota
	HookSourceProcess
)

type IngestRequest added in v0.2.5

type IngestRequest struct {
	SessionKey string            // session identifier
	Message    providers.Message // the message just persisted
}

IngestRequest is the input to Ingest.

type InterruptKind added in v0.2.4

type InterruptKind string
const (
	InterruptKindSteering InterruptKind = "steering"
	InterruptKindGraceful InterruptKind = "graceful"
	InterruptKindHard     InterruptKind = "hard_abort"
)

type InterruptReceivedPayload added in v0.2.4

type InterruptReceivedPayload struct {
	Kind       InterruptKind
	Role       string
	ContentLen int
	QueueDepth int
	HintLen    int
}

InterruptReceivedPayload describes accepted turn-control input.

type LLMDeltaPayload added in v0.2.4

type LLMDeltaPayload struct {
	ContentDeltaLen   int
	ReasoningDeltaLen int
}

LLMDeltaPayload describes a streamed LLM delta.

type LLMHookRequest added in v0.2.4

type LLMHookRequest struct {
	Meta             EventMeta                  `json:"meta"`
	Context          *TurnContext               `json:"context,omitempty"`
	Model            string                     `json:"model"`
	Messages         []providers.Message        `json:"messages,omitempty"`
	Tools            []providers.ToolDefinition `json:"tools,omitempty"`
	Options          map[string]any             `json:"options,omitempty"`
	GracefulTerminal bool                       `json:"graceful_terminal,omitempty"`
}

func (*LLMHookRequest) Clone added in v0.2.4

func (r *LLMHookRequest) Clone() *LLMHookRequest

type LLMHookResponse added in v0.2.4

type LLMHookResponse struct {
	Meta     EventMeta              `json:"meta"`
	Context  *TurnContext           `json:"context,omitempty"`
	Model    string                 `json:"model"`
	Response *providers.LLMResponse `json:"response,omitempty"`
}

func (*LLMHookResponse) Clone added in v0.2.4

func (r *LLMHookResponse) Clone() *LLMHookResponse

type LLMInterceptor added in v0.2.4

type LLMInterceptor interface {
	BeforeLLM(ctx context.Context, req *LLMHookRequest) (*LLMHookRequest, HookDecision, error)
	AfterLLM(ctx context.Context, resp *LLMHookResponse) (*LLMHookResponse, HookDecision, error)
}

type LLMPhase added in v0.2.7

type LLMPhase int

LLMPhase indicates which phase the turn is executing in.

const (
	LLMPhaseSetup LLMPhase = iota
	LLMPhasePreLLM
	LLMPhaseLLMCall
	LLMPhaseProcessing
	LLMPhaseToolLoop
	LLMPhaseTools
	LLMPhaseFinalizing
	LLMPhaseCompleted
	LLMPhaseAborted
)

type LLMRequestPayload added in v0.2.4

type LLMRequestPayload struct {
	Model         string
	MessagesCount int
	ToolsCount    int
	MaxTokens     int
	Temperature   float64
}

LLMRequestPayload describes an outbound LLM request.

type LLMResponsePayload added in v0.2.4

type LLMResponsePayload struct {
	ContentLen   int
	ToolCalls    int
	HasReasoning bool
}

LLMResponsePayload describes an inbound LLM response.

type LLMRetryPayload added in v0.2.4

type LLMRetryPayload struct {
	Attempt    int
	MaxRetries int
	Reason     string
	Error      string
	Backoff    time.Duration
}

LLMRetryPayload describes a retry of an LLM request.

type MemoryStore added in v0.1.1

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

MemoryStore manages persistent memory for the agent. - Long-term memory: memory/MEMORY.md - Daily notes: memory/YYYYMM/YYYYMMDD.md

func NewMemoryStore added in v0.1.1

func NewMemoryStore(workspace string) *MemoryStore

NewMemoryStore creates a new MemoryStore with the given workspace path. It ensures the memory directory exists.

func (*MemoryStore) AppendToday added in v0.1.1

func (ms *MemoryStore) AppendToday(content string) error

AppendToday appends content to today's daily note. If the file doesn't exist, it creates a new file with a date header.

func (*MemoryStore) GetMemoryContext added in v0.1.1

func (ms *MemoryStore) GetMemoryContext() string

GetMemoryContext returns formatted memory context for the agent prompt. Includes long-term memory and recent daily notes.

func (*MemoryStore) GetRecentDailyNotes added in v0.1.1

func (ms *MemoryStore) GetRecentDailyNotes(days int) string

GetRecentDailyNotes returns daily notes from the last N days. Contents are joined with "---" separator.

func (*MemoryStore) ReadLongTerm added in v0.1.1

func (ms *MemoryStore) ReadLongTerm() string

ReadLongTerm reads the long-term memory (MEMORY.md). Returns empty string if the file doesn't exist.

func (*MemoryStore) ReadToday added in v0.1.1

func (ms *MemoryStore) ReadToday() string

ReadToday reads today's daily note. Returns empty string if the file doesn't exist.

func (*MemoryStore) WriteLongTerm added in v0.1.1

func (ms *MemoryStore) WriteLongTerm(content string) error

WriteLongTerm writes content to the long-term memory file (MEMORY.md).

type Pipeline added in v0.2.7

type Pipeline struct {
	Bus            interfaces.MessageBus
	Cfg            *config.Config
	ContextManager ContextManager
	Hooks          *HookManager
	Fallback       *providers.FallbackChain
	ChannelManager interfaces.ChannelManager
	MediaStore     media.MediaStore
	Steering       any // TODO: *Steering
	// contains filtered or unexported fields
}

Pipeline holds the runtime dependencies used by Pipeline methods. It is constructed by runTurn via NewPipeline and passed to sub-methods so that the coordinator can delegate phase execution.

func NewPipeline added in v0.2.7

func NewPipeline(al *AgentLoop) *Pipeline

NewPipeline creates a Pipeline from an AgentLoop instance.

func (*Pipeline) CallLLM added in v0.2.7

func (p *Pipeline) CallLLM(
	ctx context.Context,
	turnCtx context.Context,
	ts *turnState,
	exec *turnExecution,
	iteration int,
) (Control, error)

CallLLM performs an LLM call with fallback support, hook invocation, and retry logic. It handles PreLLM setup, the actual LLM invocation with retry, and AfterLLM processing. Returns Control indicating what the coordinator should do next.

func (*Pipeline) ExecuteTools added in v0.2.7

func (p *Pipeline) ExecuteTools(
	ctx context.Context,
	turnCtx context.Context,
	ts *turnState,
	exec *turnExecution,
	iteration int,
) ToolControl

ExecuteTools executes the tool loop, handling BeforeTool/ApproveTool/AfterTool hooks, tool execution with async callbacks, media delivery, and steering injection. Returns ToolControl indicating what the coordinator should do next:

  • ToolControlContinue: all tool results handled, pendingMessages or steering exists, continue turn
  • ToolControlBreak: tool loop exited, proceed to coordinator's hardAbort/finalContent/finalize

func (*Pipeline) Finalize added in v0.2.7

func (p *Pipeline) Finalize(
	ctx context.Context,
	turnCtx context.Context,
	ts *turnState,
	exec *turnExecution,
	turnStatus TurnEndStatus,
	finalContent string,
) (turnResult, error)

Finalize handles turn finalization, either: - Early return when allResponsesHandled=true (ExecuteTools already finalized) - Normal finalization for allResponsesHandled=false (sets finalContent, saves session, compact)

func (*Pipeline) SetupTurn added in v0.2.7

func (p *Pipeline) SetupTurn(ctx context.Context, ts *turnState) (*turnExecution, error)

SetupTurn extracts the one-time initialization phase, returning a turnExecution populated with history, messages, and candidate selection. It replaces lines 56-145 of the original runTurn.

type ProcessHook added in v0.2.4

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

func NewProcessHook added in v0.2.4

func NewProcessHook(ctx context.Context, name string, opts ProcessHookOptions) (*ProcessHook, error)

func (*ProcessHook) AfterLLM added in v0.2.4

func (ph *ProcessHook) AfterLLM(
	ctx context.Context,
	resp *LLMHookResponse,
) (*LLMHookResponse, HookDecision, error)

func (*ProcessHook) AfterTool added in v0.2.4

func (*ProcessHook) ApproveTool added in v0.2.4

func (ph *ProcessHook) ApproveTool(ctx context.Context, req *ToolApprovalRequest) (ApprovalDecision, error)

func (*ProcessHook) BeforeLLM added in v0.2.4

func (ph *ProcessHook) BeforeLLM(
	ctx context.Context,
	req *LLMHookRequest,
) (*LLMHookRequest, HookDecision, error)

func (*ProcessHook) BeforeTool added in v0.2.4

func (*ProcessHook) Close added in v0.2.4

func (ph *ProcessHook) Close() error

func (*ProcessHook) OnEvent added in v0.2.4

func (ph *ProcessHook) OnEvent(ctx context.Context, evt Event) error

type ProcessHookOptions added in v0.2.4

type ProcessHookOptions struct {
	Command       []string
	Dir           string
	Env           []string
	Observe       bool
	ObserveKinds  []string
	InterceptLLM  bool
	InterceptTool bool
	ApproveTool   bool
}

type SessionSummarizePayload added in v0.2.4

type SessionSummarizePayload struct {
	SummarizedMessages int
	KeptMessages       int
	SummaryLen         int
	OmittedOversized   bool
}

SessionSummarizePayload describes a completed async session summarization.

type SoulDefinition added in v0.2.4

type SoulDefinition struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

SoulDefinition represents the resolved SOUL.md file linked to the agent.

type SteeringInjectedPayload added in v0.2.4

type SteeringInjectedPayload struct {
	Count           int
	TotalContentLen int
}

SteeringInjectedPayload describes steering messages appended before the next LLM call.

type SteeringMode added in v0.2.4

type SteeringMode string

SteeringMode controls how queued steering messages are dequeued.

const (
	// SteeringOneAtATime dequeues only the first queued message per poll.
	SteeringOneAtATime SteeringMode = "one-at-a-time"
	// SteeringAll drains the entire queue in a single poll.
	SteeringAll SteeringMode = "all"
	// MaxQueueSize number of possible messages in the Steering Queue
	MaxQueueSize = 10
)

type SubTurnConfig added in v0.2.4

type SubTurnConfig struct {
	Model        string
	Tools        []tools.Tool
	SystemPrompt string
	MaxTokens    int

	// Async controls the result delivery mechanism:
	//
	// When Async = false (synchronous sub-turn):
	//   - The caller blocks until the sub-turn completes
	//   - The result is ONLY returned via the function return value
	//   - The result is NOT delivered to the parent's pendingResults channel
	//   - This prevents double delivery: caller gets result immediately, no need for channel
	//   - Use case: When the caller needs the result immediately to continue execution
	//   - Example: A tool that needs to process the sub-turn result before returning
	//
	// When Async = true (asynchronous sub-turn):
	//   - The sub-turn runs in the background (still blocks the caller, but semantically async)
	//   - The result is delivered to the parent's pendingResults channel
	//   - The result is ALSO returned via the function return value (for consistency)
	//   - The parent turn can poll pendingResults in later iterations to process results
	//   - Use case: Fire-and-forget operations, or when results are processed in batches
	//   - Example: Spawning multiple sub-turns in parallel and collecting results later
	//
	// IMPORTANT: The Async flag does NOT make the call non-blocking. It only controls
	// whether the result is delivered via the channel. For true non-blocking execution,
	// the caller must spawn the sub-turn in a separate goroutine.
	Async bool

	// Critical indicates this SubTurn's result is important and should continue
	// running even after the parent turn finishes gracefully.
	//
	// When parent finishes gracefully (Finish(false)):
	//   - Critical=true: SubTurn continues running, delivers result as orphan
	//   - Critical=false: SubTurn exits gracefully without error
	//
	// When parent finishes with hard abort (Finish(true)):
	//   - All SubTurns are canceled regardless of Critical flag
	Critical bool

	// Timeout is the maximum duration for this SubTurn.
	// If the SubTurn runs longer than this, it will be canceled.
	// Default is 5 minutes (defaultSubTurnTimeout) if not specified.
	Timeout time.Duration

	// MaxContextRunes limits the context size (in runes) passed to the SubTurn.
	// This prevents context window overflow by truncating message history before LLM calls.
	//
	// Values:
	//   0  = Auto-calculate based on model's ContextWindow * 0.75 (default, recommended)
	//   -1 = No limit (disable soft truncation, rely only on hard context errors)
	//   >0 = Use specified rune limit
	//
	// The soft limit acts as a first line of defense before hitting the provider's
	// hard context window limit. When exceeded, older messages are intelligently
	// truncated while preserving system messages and recent context.
	MaxContextRunes int

	// ActualSystemPrompt is injected as the true 'system' role message for the childAgent.
	// The legacy SystemPrompt field is actually used as the first 'user' message (task description).
	ActualSystemPrompt string

	// InitialMessages preloads the ephemeral session history before the agent loop starts.
	// Used by evaluator-optimizer patterns to pass the full worker context across multiple iterations.
	InitialMessages []providers.Message

	// InitialTokenBudget is a shared atomic counter for tracking remaining tokens.
	// If set, the SubTurn will inherit this budget and deduct tokens after each LLM call.
	// If nil, the SubTurn will inherit the parent's tokenBudget (if any).
	// Used by team tool to enforce token limits across all team members.
	InitialTokenBudget *atomic.Int64
}

SubTurnConfig configures the execution of a child sub-turn.

Usage Examples:

Synchronous sub-turn (Async=false):

cfg := SubTurnConfig{
    Model: "gpt-4o-mini",
    SystemPrompt: "Analyze this code",
    Async: false,  // Result returned immediately
}
result, err := SpawnSubTurn(ctx, cfg)
// Use result directly here
processResult(result)

Asynchronous sub-turn (Async=true):

cfg := SubTurnConfig{
    Model: "gpt-4o-mini",
    SystemPrompt: "Background analysis",
    Async: true,  // Result delivered to channel
}
result, err := SpawnSubTurn(ctx, cfg)
// Result also available in parent's pendingResults channel
// Parent turn will poll and process it in a later iteration

type SubTurnEndPayload added in v0.2.4

type SubTurnEndPayload struct {
	AgentID string
	Status  string
}

SubTurnEndPayload describes the completion of a child turn.

type SubTurnOrphanPayload added in v0.2.4

type SubTurnOrphanPayload struct {
	ParentTurnID string
	ChildTurnID  string
	Reason       string
}

SubTurnOrphanPayload describes a sub-turn result that could not be delivered.

type SubTurnResultDeliveredPayload added in v0.2.4

type SubTurnResultDeliveredPayload struct {
	TargetChannel string
	TargetChatID  string
	ContentLen    int
}

SubTurnResultDeliveredPayload describes delivery of a sub-turn result.

type SubTurnSpawnPayload added in v0.2.4

type SubTurnSpawnPayload struct {
	AgentID      string
	Label        string
	ParentTurnID string
}

SubTurnSpawnPayload describes the creation of a child turn.

type ThinkingLevel added in v0.2.1

type ThinkingLevel string

ThinkingLevel controls how the provider sends thinking parameters.

  • "adaptive": sends {thinking: {type: "adaptive"}} + output_config.effort (Claude 4.6+)
  • "low"/"medium"/"high"/"xhigh": sends {thinking: {type: "enabled", budget_tokens: N}} (all models)
  • "off": disables thinking
const (
	ThinkingOff      ThinkingLevel = "off"
	ThinkingLow      ThinkingLevel = "low"
	ThinkingMedium   ThinkingLevel = "medium"
	ThinkingHigh     ThinkingLevel = "high"
	ThinkingXHigh    ThinkingLevel = "xhigh"
	ThinkingAdaptive ThinkingLevel = "adaptive"
)

type ToolApprovalRequest added in v0.2.4

type ToolApprovalRequest struct {
	Meta      EventMeta      `json:"meta"`
	Context   *TurnContext   `json:"context,omitempty"`
	Tool      string         `json:"tool"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

func (*ToolApprovalRequest) Clone added in v0.2.4

type ToolApprover added in v0.2.4

type ToolApprover interface {
	ApproveTool(ctx context.Context, req *ToolApprovalRequest) (ApprovalDecision, error)
}

type ToolCallHookRequest added in v0.2.4

type ToolCallHookRequest struct {
	Meta       EventMeta         `json:"meta"`
	Context    *TurnContext      `json:"context,omitempty"`
	Tool       string            `json:"tool"`
	Arguments  map[string]any    `json:"arguments,omitempty"`
	Channel    string            `json:"channel,omitempty"`
	ChatID     string            `json:"chat_id,omitempty"`
	HookResult *tools.ToolResult `json:"hook_result,omitempty"` // Result returned directly by hook (for respond action). Media is supported - see Media handling section in docs.
}

func (*ToolCallHookRequest) Clone added in v0.2.4

type ToolControl added in v0.2.7

type ToolControl int

ToolControl signals returned from ExecuteTools to drive tool loop iteration.

const (
	// ToolControlContinue tells the tool loop to jump to the next iteration
	// (pendingMessages arrived, SubTurn results, etc.).
	ToolControlContinue ToolControl = iota
	// ToolControlBreak tells the tool loop to exit and return to the coordinator.
	ToolControlBreak
	// ToolControlFinalize tells the coordinator that all tool responses were
	// handled and the turn should finalize without another LLM call.
	ToolControlFinalize
)

type ToolExecEndPayload added in v0.2.4

type ToolExecEndPayload struct {
	Tool       string
	Duration   time.Duration
	ForLLMLen  int
	ForUserLen int
	IsError    bool
	Async      bool
}

ToolExecEndPayload describes the outcome of a tool execution.

type ToolExecSkippedPayload added in v0.2.4

type ToolExecSkippedPayload struct {
	Tool   string
	Reason string
}

ToolExecSkippedPayload describes a skipped tool call.

type ToolExecStartPayload added in v0.2.4

type ToolExecStartPayload struct {
	Tool      string
	Arguments map[string]any
}

ToolExecStartPayload describes a tool execution request.

type ToolInterceptor added in v0.2.4

type ToolInterceptor interface {
	BeforeTool(ctx context.Context, call *ToolCallHookRequest) (*ToolCallHookRequest, HookDecision, error)
	AfterTool(ctx context.Context, result *ToolResultHookResponse) (*ToolResultHookResponse, HookDecision, error)
}

type ToolResultHookResponse added in v0.2.4

type ToolResultHookResponse struct {
	Meta      EventMeta         `json:"meta"`
	Context   *TurnContext      `json:"context,omitempty"`
	Tool      string            `json:"tool"`
	Arguments map[string]any    `json:"arguments,omitempty"`
	Result    *tools.ToolResult `json:"result,omitempty"`
	Duration  time.Duration     `json:"duration"`
}

func (*ToolResultHookResponse) Clone added in v0.2.4

type TurnContext added in v0.2.7

type TurnContext struct {
	Inbound *bus.InboundContext    `json:"inbound,omitempty"`
	Route   *routing.ResolvedRoute `json:"route,omitempty"`
	Scope   *session.SessionScope  `json:"scope,omitempty"`
}

TurnContext carries normalized turn-scoped facts that can be shared across events, hooks, and other runtime observers without re-parsing legacy fields.

type TurnEndPayload added in v0.2.4

type TurnEndPayload struct {
	Status          TurnEndStatus
	Iterations      int
	Duration        time.Duration
	FinalContentLen int
}

TurnEndPayload describes the completion of a turn.

type TurnEndStatus added in v0.2.4

type TurnEndStatus string

TurnEndStatus describes the terminal state of a turn.

const (
	// TurnEndStatusCompleted indicates the turn finished normally.
	TurnEndStatusCompleted TurnEndStatus = "completed"
	// TurnEndStatusError indicates the turn ended because of an error.
	TurnEndStatusError TurnEndStatus = "error"
	// TurnEndStatusAborted indicates the turn was hard-aborted and rolled back.
	TurnEndStatusAborted TurnEndStatus = "aborted"
)

type TurnPhase added in v0.2.4

type TurnPhase string
const (
	TurnPhaseSetup      TurnPhase = "setup"
	TurnPhaseRunning    TurnPhase = "running"
	TurnPhaseTools      TurnPhase = "tools"
	TurnPhaseFinalizing TurnPhase = "finalizing"
	TurnPhaseCompleted  TurnPhase = "completed"
	TurnPhaseAborted    TurnPhase = "aborted"
)

type TurnStartPayload added in v0.2.4

type TurnStartPayload struct {
	UserMessage string
	MediaCount  int
}

TurnStartPayload describes the start of a turn.

type UserDefinition added in v0.2.4

type UserDefinition struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

UserDefinition represents the resolved USER.md file linked to the workspace.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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