runtime

package
v7.57.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 46 Imported by: 1

Documentation

Overview

Package runtime exposes Floret's durable, host-facing Agent runtime.

Floret owns canonical threads, turns, runs, provider-visible history, approvals, Agent todos, tool outcomes, projections, and recovery state. A host retains product policy, authorization, resources, model transport, UI, and commands that have not yet been admitted to a Floret thread.

Hosts create one store, configure its capability binders exactly once with configureHostCapabilities, bind the narrow capability needed for an exact ThreadID or parent ThreadID, and close the store only after active work has stopped. Public snapshot and result Validate methods are intended for host integration boundaries; invalid values must not be repaired from host metadata, observation events, or Floret implementation records.

Bind methods bind an identity or intent without first claiming that the referenced store state exists. Provider-free capabilities that require existing authority use NewHost(ctx, ...) so construction can validate the store. Recovery keeps explicit BindThread and BindSubAgent entry points because root and parent-child recovery authority are different contracts. Provider-backed factories accept only opaque option values returned by newTurnExecutionOptions, newThreadCompactionOptions, or newSubAgentOptions; factories revalidate both those values and current store authority before issuing a Host.

Index

Constants

View Source
const (
	MessageReferenceText      MessageReferenceKind = "text"
	MessageReferenceFile      MessageReferenceKind = "file"
	MessageReferenceDirectory MessageReferenceKind = "directory"
	MessageReferenceTerminal  MessageReferenceKind = "terminal"
	MessageReferenceProcess   MessageReferenceKind = "process"
	MessageReferenceThread    MessageReferenceKind = "thread"

	MaxMessageReferencesPerTurn           = 128
	MaxMessageReferenceIDBytes            = 128
	MaxMessageReferenceLabelRunes         = 256
	MaxMessageReferenceTextRunes          = 12_000
	MaxMessageReferenceResourceRefBytes   = 8_192
	MaxMessageReferencesPayloadBytes      = 256 * 1024
	MaxMessageAttachmentsPerTurn          = 32
	MaxMessageAttachmentResourceRefBytes  = 16 * 1024
	MaxMessageAttachmentNameRunes         = 1024
	MaxMessageAttachmentMIMETypeBytes     = 512
	MaxMessageAttachmentSizeBytes         = 64 * 1024 * 1024
	MaxMessageAttachmentsTotalSizeBytes   = 256 * 1024 * 1024
	MaxMessageAttachmentsPayloadBytes     = 512 * 1024
	MaxTurnSupplementalContextItems       = 128
	MaxTurnSupplementalContextKindRunes   = 128
	MaxTurnSupplementalContextTitleRunes  = 256
	MaxTurnSupplementalContextTextRunes   = 16_384
	MaxTurnSupplementalMetadataPairs      = 32
	MaxTurnSupplementalMetadataKeyBytes   = 128
	MaxTurnSupplementalMetadataValueRunes = 4_096
	MaxTurnSupplementalPayloadBytes       = 256 * 1024
)
View Source
const (
	CoreControlAskUser = tools.ControlAskUser
)

Variables

View Source
var (
	// ErrMigrationRequired reports an exact legacy schema that runtime.Open
	// refuses to migrate implicitly.
	ErrMigrationRequired = errors.New("floret storage migration required")
	// ErrUnsupportedSchema reports a nonempty schema outside the v3 contract.
	ErrUnsupportedSchema = errors.New("unsupported floret logical schema")
	// ErrStoreTooNew reports a store written by a newer storage contract.
	ErrStoreTooNew = errors.New("floret storage requires a newer runtime")
)
View Source
var (
	// ErrHostClosed reports that Host shutdown has started.
	ErrHostClosed = errors.New("floret host is closed")
	// ErrRevisionUnavailable reports a thread revision outside retained durable history.
	ErrRevisionUnavailable = errors.New("floret thread revision is unavailable")
	// ErrSubscriptionStale reports a subscription that must be recreated from a new snapshot.
	ErrSubscriptionStale = errors.New("floret subscription is stale")
	// ErrThreadNotFound reports that a requested durable thread was not found.
	ErrThreadNotFound = errors.New("floret thread not found")
	// ErrThreadDeleted reports that a requested durable identity is permanently tombstoned.
	ErrThreadDeleted = errors.New("floret thread is deleted")
	// ErrThreadNotActive reports that an active-only capability no longer owns the thread mutation.
	ErrThreadNotActive = errors.New("floret thread is not active")
	// ErrThreadBusy reports that another active turn or mutation currently owns the thread.
	ErrThreadBusy = errors.New("floret thread is busy")
	// ErrTurnNotFound reports that a requested durable turn was not found.
	ErrTurnNotFound = errors.New("floret turn not found")
	// ErrInterruptedTurnNotFound reports that a live exact recovery target has no active turn lease.
	ErrInterruptedTurnNotFound = errors.New("floret interrupted turn not found")
	// ErrRecoveryTargetResolved reports that an exact interrupted-turn target no longer owns its bound lease generation.
	ErrRecoveryTargetResolved = errors.New("floret interrupted turn recovery target is resolved")
	// ErrRunNotFound reports that a requested durable run was not found.
	ErrRunNotFound = errors.New("floret run not found")
	// ErrArtifactNotFound reports that a requested durable artifact was not found.
	ErrArtifactNotFound = errors.New("floret artifact not found")
	// ErrNoRetryTarget reports that a thread has no canonical turn eligible for retry.
	ErrNoRetryTarget = errors.New("floret thread has no retry target")
	// ErrPendingToolNotFound reports that a settlement target does not identify a canonical tool call.
	ErrPendingToolNotFound = errors.New("floret pending tool not found")
	// ErrPendingToolNotActive reports that a settlement target is not an active pending tool result.
	ErrPendingToolNotActive = errors.New("floret pending tool is not active")
	// ErrPendingToolSettlementConflict reports that a pending tool was already settled differently.
	ErrPendingToolSettlementConflict = errors.New("floret pending tool settlement conflict")
	// ErrSubAgentNotFound reports that a requested parent-scoped child thread was not found.
	ErrSubAgentNotFound = errors.New("floret subagent not found")
	// ErrSubAgentClosed reports that a requested child mutation targets a closed SubAgent.
	ErrSubAgentClosed = errors.New("floret subagent is closed")
	// ErrSubAgentClosing reports that an explicit close operation owns the child subtree.
	ErrSubAgentClosing = errors.New("floret subagent is closing")
	// ErrStaleAuthority reports that a local proof no longer owns the durable generation.
	ErrStaleAuthority = errors.New("floret authority proof is stale")
	// ErrRequestConflict reports durable request identity reuse with changed input.
	ErrRequestConflict = errors.New("floret request conflicts with persisted authority")
	// ErrAuthorityCorrupt reports an impossible durable authority shape.
	ErrAuthorityCorrupt = errors.New("floret authority state is corrupt")
	// ErrUnsupportedStoreCapability reports a backend that lacks required atomicity.
	ErrUnsupportedStoreCapability = errors.New("floret store capability is unsupported")
	// ErrEffectUnauthorized reports a current host-policy denial before handler entry.
	ErrEffectUnauthorized = errors.New("floret effect is unauthorized")
	// ErrAuthorizationUnavailable reports a host-policy, approval, audit, or gate failure before handler entry.
	ErrAuthorizationUnavailable = errors.New("floret effect authorization is unavailable")
	// ErrInvalidAuthorizationProof reports a proof that does not match the canonical invocation.
	ErrInvalidAuthorizationProof = errors.New("floret effect authorization proof is invalid")
	// ErrEffectDispatchConsumed reports reuse or deferred use of a one-shot authorized effect.
	ErrEffectDispatchConsumed = errors.New("floret authorized effect dispatch was consumed")
	// ErrEffectOutcomeUnknown reports an invocation that crossed dispatch without a known result.
	ErrEffectOutcomeUnknown = errors.New("floret effect outcome is unknown")
	// ErrAuthorizationContract reports a host gate that did not return the closure's sealed result.
	ErrAuthorizationContract = errors.New("floret effect authorization contract failed")
	// ErrStoreClosed reports that the store has started closing.
	ErrStoreClosed = ErrHostClosed
	// ErrSubAgentParentRequired reports that a child operation used a root-thread capability.
	ErrSubAgentParentRequired = errors.New("floret subagent operation requires parent authority")
	// ErrForkOperationConflict reports that an operation ID was reused with a different fork request.
	ErrForkOperationConflict = errors.New("floret fork operation conflicts with existing request")
	// ErrForkDestinationConflict reports that a planned destination is owned by another operation or node.
	ErrForkDestinationConflict = errors.New("floret fork destination conflicts with operation plan")
	// ErrAgentTodoVersionConflict reports that a todo update was based on a stale canonical version.
	ErrAgentTodoVersionConflict = errors.New("floret agent todo version conflict")
	// ErrJournalInvariant reports an ambiguous active path that Floret refuses to repair heuristically.
	ErrJournalInvariant = errors.New("floret thread journal invariant violated")
	// ErrThreadAuthorityInvariant reports invalid durable root/SubAgent ownership metadata.
	ErrThreadAuthorityInvariant = errors.New("floret thread authority invariant violated")
)
View Source
var (
	// ErrStorageResetUnsupported reports a backend that cannot atomically clear
	// all Floret-owned opaque records.
	ErrStorageResetUnsupported = errors.New("Floret storage reset is unsupported")
	// ErrStorageResetRequest reports incomplete reset ownership metadata.
	ErrStorageResetRequest = errors.New("invalid Floret storage reset request")
)
View Source
var ErrExecutionDeferred = errors.New("runtime execution is deferred")

ErrExecutionDeferred means a maintenance Host has not been activated.

View Source
var ErrModelContextUnavailable = engine.ErrModelContextUnavailable

ErrModelContextUnavailable classifies a required runtime snapshot collection failure. Hosts wrap this error with the actionable source failure. The turn settles and may be retried after the source is repaired, without replaying confirmed effects.

View Source
var ErrRestoredTurn = errors.New("restored turn cannot be retried; submit a new request")

ErrRestoredTurn requires the caller to submit a new user request instead of retrying execution whose side effects may have occurred after the snapshot.

Functions

func CoreControlDefinitions

func CoreControlDefinitions() []tools.ToolDefinition

CoreControlDefinitions returns Floret's product-neutral ask-user control tool.

func ManualCompactionOperationID

func ManualCompactionOperationID(runID identity.RunID, step int, requestID string) string

func ProviderSafeCoreControlText

func ProviderSafeCoreControlText(signal TurnSignal) string

ProviderSafeCoreControlText returns provider-visible transcript text for product-neutral core control signals.

Types

type Agent

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

Agent is an immutable assistant persona and execution-capability snapshot. It contains no durable conversation identity or storage ownership.

func NewAgent

func NewAgent(configuration config.AgentConfig, gateway provider.Gateway, options ...AgentOption) (*Agent, error)

NewAgent validates and snapshots one provider-neutral Agent configuration.

func (*Agent) Config

func (agent *Agent) Config() config.AgentConfig

Config returns a detached copy of the Agent's persona and model policy.

func (*Agent) ProviderIdentity

func (agent *Agent) ProviderIdentity() provider.Identity

ProviderIdentity returns the immutable identity declared by the Gateway.

func (*Agent) ToolDefinitions

func (agent *Agent) ToolDefinitions() []tools.ToolDefinition

ToolDefinitions returns detached provider-visible definitions for the Agent's static tool snapshot.

type AgentFactory

type AgentFactory interface {
	Agent(context.Context, AgentRequest) (*Agent, error)
}

AgentFactory resolves provider and tool capability outside the thread lock.

type AgentFactoryFunc

type AgentFactoryFunc func(context.Context, AgentRequest) (*Agent, error)

AgentFactoryFunc adapts a function to AgentFactory.

func (AgentFactoryFunc) Agent

func (factory AgentFactoryFunc) Agent(ctx context.Context, request AgentRequest) (*Agent, error)

type AgentOption

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

AgentOption configures one immutable Agent capability at construction time.

func WithAgentCapabilities

func WithAgentCapabilities(capabilities CapabilityOptions) AgentOption

WithAgentCapabilities configures product-neutral capability sources.

func WithAgentDynamicToolSurface

func WithAgentDynamicToolSurface(surface ToolSurfaceProvider) AgentOption

WithAgentDynamicToolSurface configures the product-neutral per-step tool surface source.

func WithAgentEffectAuthorization

func WithAgentEffectAuthorization(gate EffectAuthorizationGate) AgentOption

WithAgentEffectAuthorization configures the host-owned authorization gate for effectful local tools.

func WithAgentEventSink

func WithAgentEventSink(sink EventSink) AgentOption

WithAgentEventSink configures runtime event observation.

func WithAgentHostedTools added in v7.2.0

func WithAgentHostedTools(definitions ...provider.HostedToolDefinition) AgentOption

WithAgentHostedTools freezes provider-native tools for every execution by the Agent. It is mutually exclusive with WithAgentDynamicToolSurface. Hosted tools are never dispatched through the local tool registry.

func WithAgentIDGenerator

func WithAgentIDGenerator(generator func(string) string) AgentOption

WithAgentIDGenerator configures deterministic non-domain correlation IDs.

func WithAgentLoopLimits

func WithAgentLoopLimits(limits LoopLimits) AgentOption

WithAgentLoopLimits configures provider-loop safety limits.

func WithAgentManualCompactions

func WithAgentManualCompactions(source ManualCompactionSource) AgentOption

WithAgentManualCompactions configures host-owned manual compaction requests that are polled at safe points during each turn executed by the Agent.

func WithAgentProviderRequestTimeoutPolicy added in v7.42.0

func WithAgentProviderRequestTimeoutPolicy(policy ProviderRequestTimeoutPolicy) AgentOption

WithAgentProviderRequestTimeoutPolicy sets the single physical-request policy.

func WithAgentProviderRetryPolicy added in v7.38.0

func WithAgentProviderRetryPolicy(policy ProviderRetryPolicy) AgentOption

WithAgentProviderRetryPolicy configures and validates automatic model recovery.

func WithAgentRunLabels added in v7.1.0

func WithAgentRunLabels(labels RunLabels) AgentOption

WithAgentRunLabels snapshots provider-neutral correlation labels and opaque host execution context for every run executed by the Agent.

func WithAgentSubAgentTimeout

func WithAgentSubAgentTimeout(timeout time.Duration) AgentOption

WithAgentSubAgentTimeout bounds one child execution.

func WithAgentThreadTitleMode

func WithAgentThreadTitleMode(mode ThreadTitleMode) AgentOption

WithAgentThreadTitleMode configures host-owned or provider-owned titles.

func WithAgentTools

func WithAgentTools(items ...tools.Tool) AgentOption

WithAgentTools snapshots static local tools for every execution by the Agent.

type AgentRequest

type AgentRequest struct {
	TurnKind           TurnKind
	ThreadID           identity.ThreadID
	TurnID             identity.TurnID
	RequestKey         string
	Input              UserInput
	CanonicalTurnInput UserInput
	RetrySource        identity.TurnID
	InteractionID      string
	EffectAttemptID    string
}

AgentRequest identifies an admitted execution resolved outside the thread lock. TurnKind tells the factory whether this execution has canonical user input.

type ApprovalPresentation

type ApprovalPresentation struct {
	Label       string   `json:"label"`
	Description string   `json:"description,omitempty"`
	Command     string   `json:"command,omitempty"`
	Effects     []string `json:"effects,omitempty"`
	Targets     []string `json:"targets,omitempty"`
	Risk        string   `json:"risk,omitempty"`
	ToolName    string   `json:"tool_name"`
	ToolCallID  string   `json:"tool_call_id"`
}

type AttentionSummary

type AttentionSummary struct {
	ApprovalCount int `json:"approval_count"`
	InputCount    int `json:"input_count"`
}

type AuthorityBusyError

type AuthorityBusyError struct {
	Kind AuthorityBusyKind
	Err  error
}

AuthorityBusyError classifies which durable authority family blocked an operation without exposing an owner identity.

func (*AuthorityBusyError) Error

func (e *AuthorityBusyError) Error() string

func (*AuthorityBusyError) Is

func (e *AuthorityBusyError) Is(target error) bool

func (*AuthorityBusyError) Unwrap

func (e *AuthorityBusyError) Unwrap() error

type AuthorityBusyKind

type AuthorityBusyKind string
const (
	AuthorityBusyTurn      AuthorityBusyKind = "turn"
	AuthorityBusyAuthority AuthorityBusyKind = "authority"
)

type AuthorizedEffect

AuthorizedEffect invokes one prepared effect under the host-selected execution context. Floret additionally bounds that context by the active turn.

type CancelInput

type CancelInput struct {
	// IncludeDescendants also admits a stop for every existing child in the
	// selected subtree. Independent threads and pending inputs are preserved.
	IncludeDescendants bool `json:"include_descendants,omitempty"`
	// Mode defaults to immediate. Graceful stops admit immediately and allow
	// in-flight tools up to five seconds to commit their confirmed results.
	Mode       CancelMode        `json:"mode,omitempty"`
	ThreadID   identity.ThreadID `json:"thread_id"`
	RequestKey RequestKey        `json:"request_key"`
}

type CancelMode added in v7.10.0

type CancelMode string

CancelMode selects when an accepted stop seals in-flight effects.

const (
	CancelModeImmediate CancelMode = "immediate"
	CancelModeGraceful  CancelMode = "graceful"
)

type CapabilityOptions

type CapabilityOptions struct {
	SkillsEnabled          bool
	SkillSources           []string
	SkillPromptBudgetBytes int
}

type CommittedCleanupError

type CommittedCleanupError struct {
	ThreadID identity.ThreadID
	Err      error
}

CommittedCleanupError reports that canonical deletion committed and only physical or auxiliary cleanup remains retryable.

func (*CommittedCleanupError) Error

func (e *CommittedCleanupError) Error() string

func (*CommittedCleanupError) Unwrap

func (e *CommittedCleanupError) Unwrap() error

type CommittedEffectError

type CommittedEffectError struct {
	EffectAttemptID string
	Err             error
}

func (*CommittedEffectError) Error

func (e *CommittedEffectError) Error() string

func (*CommittedEffectError) Unwrap

func (e *CommittedEffectError) Unwrap() error

type CompactContextInput added in v7.26.0

type CompactContextInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	RequestKey RequestKey        `json:"request_key"`
}

CompactContextInput admits one independent, idle-only context operation.

type ContractError

type ContractError struct {
	Contract string
	Err      error
}

ContractError identifies a corrupt public result contract. Contract names the root DTO or projection without exposing internal store records.

func (*ContractError) Error

func (e *ContractError) Error() string

func (*ContractError) Is

func (e *ContractError) Is(target error) bool

func (*ContractError) Unwrap

func (e *ContractError) Unwrap() error

type CreateThreadInput

type CreateThreadInput struct {
	ParentThreadID  identity.ThreadID `json:"parent_thread_id,omitempty"`
	ParentTurnID    identity.TurnID   `json:"parent_turn_id,omitempty"`
	TaskName        string            `json:"task_name,omitempty"`
	TaskDescription string            `json:"task_description,omitempty"`
	HostProfileRef  string            `json:"host_profile_ref,omitempty"`
	ForkMode        string            `json:"fork_mode,omitempty"`
	RequestKey      RequestKey        `json:"request_key"`
}

type DeleteQueuedInput

type DeleteQueuedInput struct {
	ThreadID            identity.ThreadID `json:"thread_id"`
	QueueItemID         string            `json:"queue_item_id"`
	RequestKey          RequestKey        `json:"request_key"`
	ExpectedInputSHA256 string            `json:"expected_input_sha256,omitempty"`
}

DeleteQueuedInput removes pending input. ExpectedInputSHA256 optionally requires the complete pending input to match the lowercase SHA-256 hex digest of its encoding/json representation. Missing, started or changed input then returns ErrRequestConflict; exact retries of a committed deletion succeed.

type DeleteThreadInput

type DeleteThreadInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	RequestKey RequestKey        `json:"request_key"`
}

type EditQueuedInput added in v7.20.0

type EditQueuedInput struct {
	ThreadID      identity.ThreadID `json:"thread_id"`
	QueueItemID   string            `json:"queue_item_id"`
	ExpectedText  string            `json:"expected_text"`
	Text          string            `json:"text"`
	RequestKey    RequestKey        `json:"request_key"`
	ExpectedInput *UserInput        `json:"expected_input,omitempty"`
	Input         *UserInput        `json:"input,omitempty"`
}

EditQueuedInput uses ExpectedText to reject edits made against stale content. RequestKey identifies one edit, independently of the original send request. Text edits preserve attachments, references and context. To replace complete content, supply both ExpectedInput and Input, leaving ExpectedText and Text empty. The complete expected input rejects concurrent content changes even when text is unchanged. Both modes preserve identity, supplemental context and queue position. Already admitted turns cannot be edited through this boundary.

type EffectAuthorizationGate

type EffectAuthorizationGate interface {
	Dispatch(context.Context, EffectAuthorizationRequest, AuthorizedEffect) (EffectDispatchResult, error)
}

type EffectAuthorizationProof

type EffectAuthorizationProof struct {
	EffectAttemptID    string            `json:"effect_attempt_id"`
	RequestFingerprint string            `json:"request_fingerprint"`
	ThreadID           identity.ThreadID `json:"thread_id"`
	TurnID             identity.TurnID   `json:"turn_id"`
	RunID              identity.RunID    `json:"run_id"`
	ToolCallID         string            `json:"tool_call_id"`
	PolicyRevision     string            `json:"policy_revision"`
	ApprovalID         string            `json:"approval_id,omitempty"`
	AuditReference     string            `json:"audit_reference"`
	AuditHash          string            `json:"audit_hash"`
	AuthorizedAt       time.Time         `json:"authorized_at"`
}

type EffectAuthorizationRequest

type EffectAuthorizationRequest struct {
	EffectAttemptID    string            `json:"effect_attempt_id"`
	RequestFingerprint string            `json:"request_fingerprint"`
	ThreadID           identity.ThreadID `json:"thread_id"`
	TurnID             identity.TurnID   `json:"turn_id"`
	RunID              identity.RunID    `json:"run_id"`
	ToolCallID         string            `json:"tool_call_id"`
	ToolName           string            `json:"tool_name"`
	Arguments          string            `json:"arguments,omitempty"`
	ArgumentHash       string            `json:"argument_hash"`
	Step               int               `json:"step"`
	BatchIndex         int               `json:"batch_index"`
	BatchSize          int               `json:"batch_size"`
	Labels             map[string]string `json:"labels,omitempty"`
	HostContext        map[string]string `json:"host_context,omitempty"`
	// Activity is detached tool-authored display data. It is never authority.
	Activity    *tools.ActivityPresentation `json:"activity,omitempty"`
	Resources   []tools.ResourceRef         `json:"resources,omitempty"`
	Effects     []tools.Effect              `json:"effects,omitempty"`
	Permission  tools.PermissionSpec        `json:"permission"`
	ReadOnly    bool                        `json:"read_only"`
	Destructive bool                        `json:"destructive"`
	OpenWorld   bool                        `json:"open_world"`
}

type EffectDispatchResult

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

type Event

type Event struct {
	ProviderLastProgressAt *time.Time `json:"provider_last_progress_at,omitempty"`

	Retry              *ProviderRetryProgress         `json:"retry,omitempty"`
	Type               observation.EventType          `json:"type"`
	TraceID            identity.TraceID               `json:"trace_id,omitempty"`
	RunID              identity.RunID                 `json:"run_id,omitempty"`
	ThreadID           identity.ThreadID              `json:"thread_id,omitempty"`
	TurnID             identity.TurnID                `json:"turn_id,omitempty"`
	Step               int                            `json:"step,omitempty"`
	Provider           string                         `json:"provider,omitempty"`
	Model              string                         `json:"model,omitempty"`
	Message            string                         `json:"message,omitempty"`
	Result             string                         `json:"result,omitempty"`
	Error              string                         `json:"error,omitempty"`
	ToolID             string                         `json:"tool_id,omitempty"`
	ToolName           string                         `json:"tool_name,omitempty"`
	ToolKind           string                         `json:"tool_kind,omitempty"`
	ArgsHash           string                         `json:"args_hash,omitempty"`
	DurationMS         int64                          `json:"duration_ms,omitempty"`
	FinishReason       observation.FinishReason       `json:"finish_reason,omitempty"`
	RawFinishReason    string                         `json:"raw_finish_reason,omitempty"`
	FinishInferred     bool                           `json:"finish_inferred,omitempty"`
	CompletionReason   observation.CompletionReason   `json:"completion_reason,omitempty"`
	ContinuationReason observation.ContinuationReason `json:"continuation_reason,omitempty"`
	Activity           *tools.ActivityPresentation    `json:"activity,omitempty"`
	ActivityTimeline   *observation.ActivityTimeline  `json:"activity_timeline,omitempty"`
	Stream             *StreamObservation             `json:"stream,omitempty"`
	ContextUsage       *ThreadContextUsage            `json:"context_usage,omitempty"`
	ContextStatus      *observation.ContextStatus     `json:"context_status,omitempty"`
	// ThreadUsageTotals contains cumulative canonical usage after this final
	// provider-usage record has been committed to the thread journal.
	ThreadUsageTotals *ThreadTokenUsageTotals           `json:"thread_usage_totals,omitempty"`
	Compaction        *observation.CompactionEvent      `json:"compaction,omitempty"`
	CompactionDebug   *observation.CompactionDebugEvent `json:"compaction_debug,omitempty"`
	Sources           []publicprovider.Source           `json:"sources,omitempty"`
	Metadata          map[string]any                    `json:"metadata,omitempty"`
	Timestamp         time.Time                         `json:"timestamp,omitempty"`
	// contains filtered or unexported fields
}

func (Event) Validate

func (e Event) Validate() error

type EventSink

type EventSink interface {
	EmitEvent(Event)
}

type ForkThreadInput

type ForkThreadInput struct {
	// SourceItemID pins a committed assistant item on the active path.
	// It is mutually exclusive with SourceEntryID; unknown items are rejected.
	SourceItemID    string            `json:"source_item_id,omitempty"`
	SourceThreadID  identity.ThreadID `json:"source_thread_id"`
	SourceEntryID   string            `json:"source_entry_id,omitempty"`
	ParentThreadID  identity.ThreadID `json:"parent_thread_id,omitempty"`
	ParentTurnID    identity.TurnID   `json:"parent_turn_id,omitempty"`
	TaskName        string            `json:"task_name,omitempty"`
	TaskDescription string            `json:"task_description,omitempty"`
	HostProfileRef  string            `json:"host_profile_ref,omitempty"`
	ForkMode        string            `json:"fork_mode,omitempty"`
	RequestKey      RequestKey        `json:"request_key"`
}

type HistoryPage

type HistoryPage struct {
	Turns   []ThreadTurn `json:"turns"`
	Items   []ThreadItem `json:"items"`
	Before  string       `json:"before,omitempty"`
	HasMore bool         `json:"has_more,omitempty"`
}

type Host

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

Host is the composition-root owner of Floret storage and narrow capability issuance. Application services must retain only handles issued by Host.

func Open

func Open(ctx context.Context, options Options) (*Host, error)

Open validates the exact v3 logical schema, initializes an empty Backend, and transfers exclusive backend lifecycle ownership to a new Host.

func (*Host) Activate added in v7.6.0

func (host *Host) Activate(ctx context.Context) error

Activate enables execution after the host application has finished preparing all of its stores and current authorization. It is idempotent. Hydrated active threads retain the ordinary recovery policy; unopened threads recover on View.

func (*Host) MediaInventory added in v7.28.0

func (host *Host) MediaInventory(ctx context.Context) (MediaInventory, error)

MediaInventory returns canonical media retention and whether every retained execution is terminal. Archived threads, inactive paths, and queue facts are included; deleted threads are excluded. Descriptors grant no resource access. Hosts must protect not-yet-admitted resources. In particular, a tool-media store must hold its write gate before reading the inventory and collect only while Idle is true, or while Host execution remains deferred.

func (*Host) PrepareRestore added in v7.6.0

func (host *Host) PrepareRestore(ctx context.Context) (RestorePreparation, error)

PrepareRestore ends unfinished execution and queued work in a restored snapshot. It requires a deferred Host and is idempotent across interruption. Use it on the staged snapshot, before publishing any restored storage set. Historical messages remain unchanged and deleted queue inputs remain visible in ThreadView.RestoredInputs. Existing approval decisions cannot resume work.

func (*Host) Shutdown

func (host *Host) Shutdown(ctx context.Context) error

Shutdown stops in-memory executions and closes the owned canonical store.

func (*Host) ThreadService

func (host *Host) ThreadService(factory AgentFactory) (ThreadService, error)

ThreadRuntime returns the Host-owned typed runtime service.

type IDSource

type IDSource interface {
	NewThreadID() (identity.ThreadID, error)
	NewTurnID() (identity.TurnID, error)
	NewRunID() (identity.RunID, error)
}

IDSource supplies deterministic identities to tests. Production uses the cryptographic source installed by Open.

type ImportPendingInputsInput

type ImportPendingInputsInput struct {
	ThreadID identity.ThreadID      `json:"thread_id"`
	Items    []ImportedPendingInput `json:"items"`
}

type ImportResult

type ImportResult struct {
	ThreadID identity.ThreadID `json:"thread_id"`
	Imported int               `json:"imported"`
	View     ThreadView        `json:"view"`
}

type ImportedPendingInput

type ImportedPendingInput struct {
	RequestKey          RequestKey                    `json:"request_key"`
	Input               UserInput                     `json:"input"`
	SupplementalContext []TurnSupplementalContextItem `json:"supplemental_context,omitempty"`
}

type InputChoice added in v7.13.0

type InputChoice struct {
	ChoiceID    string `json:"choice_id,omitempty"`
	Value       string `json:"value"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

InputChoice preserves display metadata alongside the established v7 answer value. ChoiceID identifies the original option; clients submit Value through Respond.

type InputPresentation

type InputPresentation struct {
	// ReasonCode, RequiredFromUser and EvidenceRefs preserve validated ask_user
	// intent. Evidence references express association, never access or permission.
	ReasonCode       string          `json:"reason_code,omitempty"`
	RequiredFromUser []string        `json:"required_from_user,omitempty"`
	EvidenceRefs     []string        `json:"evidence_refs,omitempty"`
	Summary          string          `json:"summary"`
	Questions        []InputQuestion `json:"questions"`
}

type InputQuestion

type InputQuestion struct {
	ID     string `json:"id"`
	Prompt string `json:"prompt"`
	Kind   string `json:"kind"`
	// Options retains the v7 answer values, in the same order as Choices when present.
	Options          []string `json:"options,omitempty"`
	WriteLabel       string   `json:"write_label,omitempty"`
	Secret           bool     `json:"secret,omitempty"`
	Header           string   `json:"header,omitempty"`
	WritePlaceholder string   `json:"write_placeholder,omitempty"`
	// ChoicesExhaustive is absent when the source did not declare it.
	ChoicesExhaustive *bool         `json:"choices_exhaustive,omitempty"`
	Choices           []InputChoice `json:"choices,omitempty"`
}

type InteractionAnswer

type InteractionAnswer struct {
	InteractionID string            `json:"interaction_id,omitempty"`
	Approved      *bool             `json:"approved,omitempty"`
	Input         map[string]string `json:"input,omitempty"`
}

InteractionAnswer resolves one user or approval interaction.

type InteractionResolution

type InteractionResolution struct {
	Accepted bool              `json:"accepted"`
	Redacted bool              `json:"redacted,omitempty"`
	Outcome  string            `json:"outcome,omitempty"`
	Approved *bool             `json:"approved,omitempty"`
	Input    map[string]string `json:"input,omitempty"`
	At       time.Time         `json:"at"`
}

type ListParentEventsInput added in v7.49.0

type ListParentEventsInput struct {
	ThreadID        identity.ThreadID
	SourceThreadIDs []identity.ThreadID
	AfterEventID    string
	Limit           int
	PendingOnly     bool
}

type LookupQueuedEditInput added in v7.34.0

type LookupQueuedEditInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	RequestKey RequestKey        `json:"request_key"`
}

type LookupSendInput added in v7.24.0

type LookupSendInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	RequestKey RequestKey        `json:"request_key"`
}

type LookupToolResultInput added in v7.30.0

type LookupToolResultInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	TurnID     identity.TurnID   `json:"turn_id"`
	RunID      identity.RunID    `json:"run_id"`
	ToolCallID string            `json:"tool_call_id"`
}

type LoopLimits

type LoopLimits struct {
	MaxEmptyProviderRetries int
	NoProgressLimit         int
	DuplicateToolLimit      int
	WallTime                time.Duration
}

type ManualCompactionPollRequest

type ManualCompactionPollRequest struct {
	RunID         identity.RunID         `json:"run_id,omitempty"`
	ThreadID      identity.ThreadID      `json:"thread_id,omitempty"`
	TurnID        identity.TurnID        `json:"turn_id,omitempty"`
	TraceID       identity.TraceID       `json:"trace_id,omitempty"`
	PromptScopeID identity.PromptScopeID `json:"prompt_scope_id,omitempty"`
	Step          int                    `json:"step,omitempty"`
}

type ManualCompactionRequest

type ManualCompactionRequest struct {
	RequestID   string    `json:"request_id"`
	Source      string    `json:"source"`
	RequestedAt time.Time `json:"requested_at,omitempty"`
}

type ManualCompactionSource

type ManualCompactionSource interface {
	PollManualCompaction(context.Context, ManualCompactionPollRequest) (ManualCompactionRequest, bool, error)
}

type MediaInventory added in v7.28.0

type MediaInventory struct {
	References []MediaReference
	Idle       bool
}

MediaInventory is a canonical retention snapshot. Idle is false while any retained execution has not reached a terminal outcome, including waits.

type MediaReference added in v7.28.0

type MediaReference struct {
	ThreadID   identity.ThreadID
	Attachment MessageAttachment
}

MediaReference identifies host-owned media retained by canonical conversation state. It is an opaque retention fact, not authorization to read the resource.

type MessageAttachment

type MessageAttachment struct {
	ResourceRef string                      `json:"resource_ref"`
	Name        string                      `json:"name"`
	MIMEType    string                      `json:"mime_type"`
	SizeBytes   int64                       `json:"size_bytes,omitempty"`
	TextStats   *MessageAttachmentTextStats `json:"text_stats,omitempty"`
}

MessageAttachment identifies one host-owned resource attached to a durable user message or confirmed tool result. ResourceRef is opaque to Floret and is resolved only by the host's modelGateway implementation.

func (MessageAttachment) Locator added in v7.51.0

func (a MessageAttachment) Locator() (string, error)

Locator returns a stable opaque identifier for the complete descriptor. Hosts must verify canonical thread membership and current product permission before resolving it. A locator never grants access.

func (MessageAttachment) Validate

func (a MessageAttachment) Validate() error

type MessageAttachmentTextStats

type MessageAttachmentTextStats struct {
	UnicodeCodePointCount int64 `json:"unicode_code_points"`
	LogicalLineCount      int64 `json:"logical_lines"`
}

type MessageContextItem added in v7.8.0

type MessageContextItem struct {
	Kind  string `json:"kind"`
	Title string `json:"title"`
	Text  string `json:"text"`
}

MessageContextItem is a durable model-context snapshot admitted with a user message. Kind and Title are non-empty single-line labels (128 and 256 characters); Text is non-empty UTF-8 (64,000 characters). An input permits 128 items / 256 KiB. Do not place secrets or opaque resource locators in this persistent context.

func (MessageContextItem) Validate added in v7.8.0

func (item MessageContextItem) Validate() error

type MessageReference

type MessageReference struct {
	ReferenceID string               `json:"reference_id"`
	Kind        MessageReferenceKind `json:"kind"`
	Label       string               `json:"label"`
	Text        string               `json:"text,omitempty"`
	ResourceRef string               `json:"resource_ref,omitempty"`
	Truncated   bool                 `json:"truncated,omitempty"`
	// ReferencedThreadID identifies the referenced conversation, never the owning thread.
	ReferencedThreadID identity.ThreadID `json:"referenced_thread_id,omitempty"`
}

MessageReference is one ordered, durable, user-visible reference associated with a canonical user message. ResourceRef is opaque to Floret.

func (MessageReference) Validate

func (r MessageReference) Validate() error

type MessageReferenceKind

type MessageReferenceKind string

type MigrationRequiredError

type MigrationRequiredError struct {
	Version string
}

MigrationRequiredError identifies the exact legacy logical schema observed by runtime.Open.

func (*MigrationRequiredError) Error

func (failure *MigrationRequiredError) Error() string

Error describes the required explicit migration.

func (*MigrationRequiredError) Is

func (failure *MigrationRequiredError) Is(target error) bool

Is classifies MigrationRequiredError with ErrMigrationRequired.

type ModelContextSection added in v7.40.0

type ModelContextSection struct {
	Key   string `json:"key"`
	Title string `json:"title"`
	Text  string `json:"text"`
}

ModelContextSection is one complete runtime fact partition. Key is a stable, unique single-line label (128 characters); Title is a display label (256 characters); Text is non-empty UTF-8 (64,000 characters). Facts are not instructions or resource authorization and must not contain secrets.

type ModelContextSnapshot added in v7.40.0

type ModelContextSnapshot struct {
	Sections []ModelContextSection `json:"sections"`
}

ModelContextSnapshot replaces the complete managed context. Nil means no supplied update; a non-nil empty collection clears all sections. Missing keys remove earlier sections. Admission copies and sorts sections by Key. At most 128 sections and 256 KiB of encoded content are permitted; invalid inputs fail.

func (ModelContextSnapshot) Validate added in v7.40.0

func (snapshot ModelContextSnapshot) Validate() error

type Options

type Options struct {
	Storage publicstorage.Source
	// EnableParentEvents admits passive child reports and critical events at natural provider boundaries.
	EnableParentEvents bool
	// DeferExecution keeps provider and tool execution disabled until Activate.
	DeferExecution bool
	// StartupProgress observes product-neutral storage startup phases. The
	// callback runs synchronously and must return promptly.
	StartupProgress     StartupProgress
	StartupWorkProgress StartupWorkProgress
	// IDSource exists only for v3 source compatibility.
	// Deprecated: production hosts must leave this nil; tests should use
	// florettest.NewIDSource.
	IDSource IDSource
}

Options configures one runtime Host.

type ParentEvent added in v7.49.0

type ParentEvent struct {
	ID             string            `json:"id"`
	ParentThreadID identity.ThreadID `json:"parent_thread_id"`
	// ParentTurnID is the most recently started ordinary turn at receipt on the
	// queried canonical path, including after its end. Compaction does not advance
	// it. Empty means no preceding ordinary turn; forks retain inherited ownership.
	ParentTurnID   identity.TurnID   `json:"parent_turn_id,omitempty"`
	SourceThreadID identity.ThreadID `json:"source_thread_id"`
	SourceTurnID   identity.TurnID   `json:"source_turn_id"`
	SourceRunID    identity.RunID    `json:"source_run_id"`
	SourceEntryID  string            `json:"source_entry_id"`
	Kind           ParentEventKind   `json:"kind"`
	ReasonCode     string            `json:"reason_code,omitempty"`
	InteractionID  string            `json:"interaction_id,omitempty"`
	Message        string            `json:"message,omitempty"`
	ReceivedAt     string            `json:"received_at"`
	Admitted       bool              `json:"admitted"`
	Resolved       bool              `json:"resolved,omitempty"`
}

ParentEvent is detached; reads include complete report text. Admitted means canonical context placement, not proof that a model read the event.

type ParentEventKind added in v7.49.0

type ParentEventKind string

ParentEventKind classifies a canonical child report or critical source fact.

const (
	ParentEventReport           ParentEventKind = "report"
	ParentEventCompleted        ParentEventKind = "completed"
	ParentEventFailed           ParentEventKind = "failed"
	ParentEventCancelled        ParentEventKind = "cancelled"
	ParentEventInterrupted      ParentEventKind = "interrupted"
	ParentEventTimedOut         ParentEventKind = "timed_out"
	ParentEventInputRequired    ParentEventKind = "input_required"
	ParentEventApprovalRequired ParentEventKind = "approval_required"
)

type ParentEventPage added in v7.49.0

type ParentEventPage struct {
	ThreadID         identity.ThreadID `json:"thread_id"`
	Events           []ParentEvent     `json:"events"`
	FirstEventID     string            `json:"first_event_id,omitempty"`
	LastEventID      string            `json:"last_event_id,omitempty"`
	NextAfterEventID string            `json:"next_after_event_id,omitempty"`
}

ParentEventPage identifies the queried canonical thread path. Inherited events retain their original ParentThreadID, which may differ from ThreadID.

type ParentEventReceipt added in v7.49.0

type ParentEventReceipt struct {
	Accepted       bool              `json:"accepted"`
	EventID        string            `json:"event_id"`
	ParentThreadID identity.ThreadID `json:"parent_thread_id"`
}

type PromoteQueuedInput

type PromoteQueuedInput = DeleteQueuedInput

type ProviderRequestProgress added in v7.39.0

type ProviderRequestProgress struct {
	LogicalRequestID      identity.LogicalRequestID `json:"logical_request_id"`
	AttemptID             string                    `json:"attempt_id"`
	AttemptEpoch          int                       `json:"attempt_epoch"`
	StartedAt             time.Time                 `json:"started_at"`
	LastProgressAt        *time.Time                `json:"last_progress_at,omitempty"`
	FirstOutputAt         *time.Time                `json:"first_output_at,omitempty"`
	EstimatedOutputTokens int64                     `json:"estimated_output_tokens"`
}

ProviderRequestProgress is memory-only feedback for the current request attempt. EstimatedOutputTokens measures received text, reasoning and local arguments; it is not provider Usage, billable tokens or context-window consumption.

type ProviderRequestTimeoutPolicy added in v7.42.0

type ProviderRequestTimeoutPolicy providerattempt.RequestTimeoutPolicy

ProviderRequestTimeoutPolicy bounds physical requests, excluding local tools, approvals and user input. Zero fields use defaults; negative fields are invalid.

func DefaultProviderRequestTimeoutPolicy added in v7.42.0

func DefaultProviderRequestTimeoutPolicy() ProviderRequestTimeoutPolicy

DefaultProviderRequestTimeoutPolicy allows five minutes for first output or hosted tools, two minutes between output, and fifteen minutes per attempt.

func (ProviderRequestTimeoutPolicy) Validate added in v7.42.0

func (policy ProviderRequestTimeoutPolicy) Validate() error

Validate rejects negative request deadlines.

type ProviderRetryPolicy added in v7.38.0

type ProviderRetryPolicy providerretry.Policy

ProviderRetryPolicy bounds recovery of each frozen model request. An Agent defaults to DefaultProviderRetryPolicy; set Disabled to disable recovery.

func DefaultProviderRetryPolicy added in v7.38.0

func DefaultProviderRetryPolicy() ProviderRetryPolicy

DefaultProviderRetryPolicy returns four extra attempts, three timeout retries, jittered 2/4/8/10-second delays and a five-minute recovery window.

func (ProviderRetryPolicy) Validate added in v7.38.0

func (policy ProviderRetryPolicy) Validate() error

Validate rejects invalid budgets, delays and recovery windows.

type ProviderRetryProgress added in v7.38.0

type ProviderRetryProgress = observation.ProviderRetryProgress

ProviderRetryProgress describes a scheduled attempt replacement in live state.

type ProviderToolSurface added in v7.18.0

type ProviderToolSurface struct {
	SystemPrompt          string
	ToolDefinitions       []tools.ToolDefinition
	HostedToolDefinitions []publicprovider.HostedToolDefinition
}

ProviderToolSurface is detached model-visible configuration from a checkpoint.

type QueuedInput

type QueuedInput struct {
	ID                  string                        `json:"id"`
	RequestKey          string                        `json:"request_key"`
	Input               UserInput                     `json:"input"`
	SupplementalContext []TurnSupplementalContextItem `json:"supplemental_context,omitempty"`
	CreatedAt           time.Time                     `json:"created_at"`
}

QueuedInput is one accepted input waiting behind the active turn.

type QueuedInputEdit added in v7.34.0

type QueuedInputEdit struct {
	QueueItemID   string    `json:"queue_item_id"`
	ExpectedInput UserInput `json:"expected_input"`
	Input         UserInput `json:"input"`
}

QueuedInputEdit is the immutable before/after content of one committed edit.

type ReadParentEventsInput added in v7.49.0

type ReadParentEventsInput struct {
	ThreadID     identity.ThreadID
	EventID      string
	FirstEventID string
	LastEventID  string
	AfterEventID string
	Limit        int
}

ReadParentEventsInput selects one event or a closed immutable event interval. Continue with the returned fixed boundaries and explicit NextAfterEventID.

type ReorderQueueInput

type ReorderQueueInput struct {
	ThreadID       identity.ThreadID `json:"thread_id"`
	OrderedItemIDs []string          `json:"ordered_item_ids"`
	RequestKey     RequestKey        `json:"request_key"`
}

type ReportToParentInput added in v7.49.0

type ReportToParentInput struct {
	ThreadID     identity.ThreadID
	TurnID       identity.TurnID
	RunID        identity.RunID
	ToolCallID   string
	ToolName     string
	ArgumentHash string
	RequestKey   RequestKey
	Message      string
}

ReportToParentInput contains host-supplied invocation identity, never model routing.

type RequestConflictError

type RequestConflictError struct {
	Operation string
	RequestID string
	Err       error
}

RequestConflictError identifies the immutable request key that was reused with different input. It never exposes the stored request payload.

func (*RequestConflictError) Error

func (e *RequestConflictError) Error() string

func (*RequestConflictError) Is

func (e *RequestConflictError) Is(target error) bool

func (*RequestConflictError) Unwrap

func (e *RequestConflictError) Unwrap() error

type RequestKey

type RequestKey string

RequestKey is the stable idempotency identity of one transport mutation.

type RespondInput

type RespondInput struct {
	ThreadID      identity.ThreadID   `json:"thread_id"`
	InteractionID string              `json:"interaction_id"`
	Answers       []InteractionAnswer `json:"answers"`
	RequestKey    RequestKey          `json:"request_key"`
}

type RestorePreparation added in v7.6.0

type RestorePreparation struct {
	StoppedThreads     int `json:"stopped_threads"`
	StoppedQueueInputs int `json:"stopped_queue_inputs"`
}

RestorePreparation reports changes made while preparing an offline restore.

type RestoredInput added in v7.6.0

type RestoredInput struct {
	ID    string    `json:"id"`
	Input UserInput `json:"input"`
}

RestoredInput preserves a cancelled queue input as a read-only canonical projection. It is never an executable queue item or authorization evidence.

type RetryInput

type RetryInput struct {
	ThreadID     identity.ThreadID `json:"thread_id"`
	SourceTurnID identity.TurnID   `json:"source_turn_id"`
	RequestKey   RequestKey        `json:"request_key"`
}

type RunLabels

type RunLabels struct {
	Correlation map[string]string `json:"correlation,omitempty"`
	Host        map[string]string `json:"host,omitempty"`
}

type RunMetrics

type RunMetrics struct {
	ProviderUsage publicprovider.Usage `json:"provider_usage"`
	Steps         int                  `json:"steps"`
	LLMRequests   int                  `json:"llm_requests"`
	ToolCalls     int                  `json:"tool_calls"`
	Compactions   int                  `json:"compactions"`
	Retries       int                  `json:"retries"`
	WallTimeMS    int64                `json:"wall_time_ms,omitempty"`
}

type SendInput

type SendInput struct {
	ThreadID            identity.ThreadID             `json:"thread_id"`
	Input               UserInput                     `json:"input"`
	SupplementalContext []TurnSupplementalContextItem `json:"supplemental_context,omitempty"`
	RequestKey          RequestKey                    `json:"request_key"`
}

type SetTitleInput

type SetTitleInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	Title      string            `json:"title"`
	RequestKey RequestKey        `json:"request_key"`
}

type SignalDisposition

type SignalDisposition string
const (
	SignalContinue SignalDisposition = "continue"
	SignalWaiting  SignalDisposition = "waiting"
)

type StartupPhase added in v7.0.2

type StartupPhase string

StartupPhase identifies storage startup work performed by Open.

const (
	StartupPhaseMigrating StartupPhase = "migrating"
	StartupPhaseVerifying StartupPhase = "verifying"
	StartupPhaseIndexing  StartupPhase = "indexing"
)

type StartupProgress added in v7.0.2

type StartupProgress interface {
	OnStartupPhase(StartupPhase)
}

StartupProgress observes changes in the storage startup phase.

type StartupProgressFunc added in v7.0.2

type StartupProgressFunc func(StartupPhase)

StartupProgressFunc adapts a function to StartupProgress.

func (StartupProgressFunc) OnStartupPhase added in v7.0.2

func (progress StartupProgressFunc) OnStartupPhase(phase StartupPhase)

OnStartupPhase reports one startup phase when the function is non-nil.

type StartupWork added in v7.52.0

type StartupWork struct {
	Phase     StartupPhase
	Completed int64
	Total     int64
}

StartupWork reports real completed work in the current phase. Total is zero when the owner does not know the total. Counts are thread projections.

type StartupWorkProgress added in v7.52.0

type StartupWorkProgress interface{ OnStartupWork(StartupWork) }

StartupWorkProgress is an optional synchronous workload observer. Callbacks must return promptly; cancellation belongs to Open's context.

type StartupWorkProgressFunc added in v7.52.0

type StartupWorkProgressFunc func(StartupWork)

StartupWorkProgressFunc adapts a function to StartupWorkProgress.

func (StartupWorkProgressFunc) OnStartupWork added in v7.52.0

func (progress StartupWorkProgressFunc) OnStartupWork(work StartupWork)

type SteerInput added in v7.36.0

type SteerInput struct {
	ThreadID   identity.ThreadID `json:"thread_id"`
	Input      UserInput         `json:"input"`
	RequestKey RequestKey        `json:"request_key"`
}

type SteerQueuedInput added in v7.36.0

type SteerQueuedInput struct {
	ThreadID      identity.ThreadID `json:"thread_id"`
	QueueItemID   string            `json:"queue_item_id"`
	ExpectedInput UserInput         `json:"expected_input"`
	RequestKey    RequestKey        `json:"request_key"`
}

SteerQueuedInput atomically consumes the exact pending input. An edited, removed, or already consumed item returns ErrRequestConflict.

type StorageInspection added in v7.6.0

type StorageInspection struct {
	Exists            bool `json:"exists"`
	MigrationRequired bool `json:"migration_required"`
}

StorageInspection describes compatibility without exposing domain records.

func InspectSQLite added in v7.6.0

func InspectSQLite(ctx context.Context, path string) (result StorageInspection, err error)

InspectSQLite validates the committed SQLite state and supported migration path without creating a Host or writing to the source. Migration writes are evaluated in a disposable memory overlay of one read transaction. Callers must exclude all writers until they finish their coordinated startup.

type StorageResetPreflight

type StorageResetPreflight struct {
	EnvironmentID           string
	OperationID             string
	OwnershipManifestSHA256 string
	Supported               bool
}

StorageResetPreflight is safe to present before destructive confirmation.

func PreflightStorageReset

func PreflightStorageReset(ctx context.Context, request StorageResetRequest) (StorageResetPreflight, error)

PreflightStorageReset verifies request ownership metadata and backend reset support without changing Floret records. The caller must keep every runtime Host for the selected store stopped until reset completes.

type StorageResetRequest

type StorageResetRequest struct {
	Storage                 publicstorage.Source
	EnvironmentID           string
	OperationID             string
	OwnershipManifestSHA256 string
}

StorageResetRequest binds one destructive maintenance operation to the exact environment and host ownership manifest that selected the store.

type StorageResetResult

type StorageResetResult struct {
	EnvironmentID           string
	OperationID             string
	OwnershipManifestSHA256 string
	PreviousDataRemoved     bool
}

StorageResetResult reports a newly initialized current-schema store.

func ResetStorage

func ResetStorage(ctx context.Context, request StorageResetRequest) (result StorageResetResult, retErr error)

ResetStorage removes all Floret records through the backend owner, then initializes and verifies one fresh current-schema store. Repeating the same request is idempotent and never imports previous records.

type StreamObservation

type StreamObservation struct {
	EstimatedOutputTokens  int64                     `json:"estimated_output_tokens,omitempty"`
	ArgumentPreview        *tools.ArgumentPreview    `json:"argument_preview,omitempty"`
	ArgumentPreviewUpdated bool                      `json:"argument_preview_updated,omitempty"`
	Type                   StreamObservationType     `json:"type"`
	Text                   string                    `json:"text,omitempty"`
	ToolCallStream         *ToolCallStream           `json:"tool_call_stream,omitempty"`
	Reason                 string                    `json:"reason,omitempty"`
	FinishReason           observation.FinishReason  `json:"finish_reason,omitempty"`
	RawFinishReason        string                    `json:"raw_finish_reason,omitempty"`
	FinishInferred         bool                      `json:"finish_inferred,omitempty"`
	Attempt                int                       `json:"attempt,omitempty"`
	LogicalRequestID       identity.LogicalRequestID `json:"logical_request_id,omitempty"`
	AttemptID              string                    `json:"attempt_id,omitempty"`
	AttemptEpoch           int                       `json:"attempt_epoch,omitempty"`
	Labels                 RunLabels                 `json:"labels,omitempty"`
}

StreamObservation is a provider-neutral, engine-confirmed streaming fact for hosts that render live assistant output from Floret runtime events.

func (StreamObservation) Validate

func (s StreamObservation) Validate() error

type StreamObservationType

type StreamObservationType string
const (
	StreamObservationAssistantDelta   StreamObservationType = "assistant_delta"
	StreamObservationReasoningDelta   StreamObservationType = "reasoning_delta"
	StreamObservationToolCallStart    StreamObservationType = "tool_call_start"
	StreamObservationToolCallDelta    StreamObservationType = "tool_call_delta"
	StreamObservationToolCallEnd      StreamObservationType = "tool_call_end"
	StreamObservationModelRetry       StreamObservationType = "model_retry"
	StreamObservationModelStreamDone  StreamObservationType = "model_stream_done"
	StreamObservationModelStreamAbort StreamObservationType = "model_stream_abort"
)

func (StreamObservationType) Valid

func (t StreamObservationType) Valid() bool

type ThreadActivity

type ThreadActivity string

ThreadActivity reports whether a thread owns an accepted turn. RunProgress separately reports transient progress while its current run is advancing.

const (
	ThreadActivityIdle   ThreadActivity = "idle"
	ThreadActivityActive ThreadActivity = "active"
)

type ThreadCancellation added in v7.10.0

type ThreadCancellation struct {
	ThreadID    identity.ThreadID `json:"thread_id"`
	Source      string            `json:"source"`
	Mode        CancelMode        `json:"mode"`
	TurnID      identity.TurnID   `json:"turn_id"`
	RunID       identity.RunID    `json:"run_id"`
	RequestedAt time.Time         `json:"requested_at"`
}

ThreadCancellation is a canonical stop request for the indicated execution. Active views with this fact are stopping; terminal views retain its provenance.

type ThreadContextCompaction

type ThreadContextCompaction struct {
	AfterItemID         string            `json:"after_item_id,omitempty"`
	RunID               identity.RunID    `json:"run_id,omitempty"`
	ThreadID            identity.ThreadID `json:"thread_id,omitempty"`
	TurnID              identity.TurnID   `json:"turn_id,omitempty"`
	Step                int               `json:"step,omitempty"`
	OperationID         string            `json:"operation_id,omitempty"`
	RequestID           string            `json:"request_id,omitempty"`
	Phase               string            `json:"phase,omitempty"`
	Status              string            `json:"status,omitempty"`
	Trigger             string            `json:"trigger,omitempty"`
	Reason              string            `json:"reason,omitempty"`
	Source              string            `json:"source,omitempty"`
	TokensBefore        int64             `json:"tokens_before,omitempty"`
	TokensAfterEstimate int64             `json:"tokens_after_estimate,omitempty"`
	Error               string            `json:"error,omitempty"`
	ObservedAt          time.Time         `json:"observed_at,omitempty"`
}

type ThreadContextCompactor added in v7.26.0

type ThreadContextCompactor interface {
	CompactContext(context.Context, CompactContextInput) (ThreadView, error)
}

ThreadContextCompactor is an optional capability of the typed thread service. Acceptance returns immediately; execution is observed through the workspace subscription and canonical context snapshot.

type ThreadContextModel

type ThreadContextModel struct {
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
}

type ThreadContextPolicy

type ThreadContextPolicy struct {
	ModelMaxOutputTokens int64 `json:"model_max_output_tokens,omitempty"`
	ContextWindowTokens  int64 `json:"context_window_tokens,omitempty"`
	MaxOutputTokens      int64 `json:"max_output_tokens,omitempty"`
	ReservedOutputTokens int64 `json:"reserved_output_tokens,omitempty"`
}

type ThreadContextReader

type ThreadContextReader interface {
	Context(context.Context, identity.ThreadID) (ThreadContextSnapshot, error)
}

ThreadContextReader exposes canonical context lifecycle facts without widening the lifecycle mutation surface of ThreadService.

type ThreadContextSnapshot

type ThreadContextSnapshot struct {
	ModelContext *ThreadModelContext        `json:"model_context,omitempty"`
	ContextUsage *ThreadContextUsage        `json:"context_usage,omitempty"`
	Model        ThreadContextModel         `json:"model,omitempty"`
	Policy       ThreadContextPolicy        `json:"policy,omitempty"`
	Usage        *observation.ContextStatus `json:"usage,omitempty"`
	UsageTotals  *ThreadTokenUsageTotals    `json:"usage_totals,omitempty"`
	Compactions  []ThreadContextCompaction  `json:"compactions,omitempty"`
	UpdatedAt    time.Time                  `json:"updated_at,omitempty"`
}

ThreadContextSnapshot is the canonical context and compaction projection for one thread. Compactions contain one latest lifecycle record per operation.

type ThreadContextUsage added in v7.15.0

type ThreadContextUsage struct {
	Confirmed *observation.ContextStatus `json:"confirmed,omitempty"`
	Estimate  *observation.ContextStatus `json:"estimate,omitempty"`
}

ThreadContextUsage separates model-confirmed input usage from the current request estimate. Confirmed describes a completed provider request, not a count of all tokens currently visible in the conversation. Nil samples mean unavailable; a non-nil empty snapshot explicitly clears obsolete samples.

type ThreadInteraction

type ThreadInteraction struct {
	ID         string                 `json:"id"`
	TurnID     identity.TurnID        `json:"turn_id"`
	RunID      identity.RunID         `json:"run_id"`
	Kind       ThreadInteractionKind  `json:"kind"`
	ToolCallID string                 `json:"tool_call_id,omitempty"`
	Resolved   bool                   `json:"resolved,omitempty"`
	Approved   *bool                  `json:"approved,omitempty"`
	Approval   *ApprovalPresentation  `json:"approval,omitempty"`
	Input      *InputPresentation     `json:"input,omitempty"`
	Resolution *InteractionResolution `json:"resolution,omitempty"`
	// contains filtered or unexported fields
}

ThreadInteraction is an unresolved or resolved action embedded in one item.

type ThreadInteractionKind

type ThreadInteractionKind string
const (
	ThreadInteractionApproval ThreadInteractionKind = "approval"
	ThreadInteractionInput    ThreadInteractionKind = "input"
)

type ThreadItem

type ThreadItem struct {
	Steering *ThreadSteering         `json:"steering,omitempty"`
	Sources  []publicprovider.Source `json:"sources,omitempty"`

	ID     string          `json:"id"`
	TurnID identity.TurnID `json:"turn_id,omitempty"`
	RunID  identity.RunID  `json:"run_id"`
	// Ordinal is the stable one-based position in the thread presentation.
	Ordinal uint64         `json:"ordinal"`
	Kind    ThreadItemKind `json:"kind"`
	Text    string         `json:"text,omitempty"`
	// Live reports that this segment may still grow in place.
	Live        bool                      `json:"live,omitempty"`
	CreatedAt   time.Time                 `json:"created_at,omitempty"`
	Attachments []MessageAttachment       `json:"attachments,omitempty"`
	References  []MessageReference        `json:"references,omitempty"`
	Context     []MessageContextItem      `json:"context,omitempty"`
	Activity    *observation.ActivityItem `json:"activity,omitempty"`
	Interaction *ThreadInteraction        `json:"interaction,omitempty"`
	// contains filtered or unexported fields
}

ThreadItem is a directly renderable current-view item.

type ThreadItemKind

type ThreadItemKind string

ThreadItemKind identifies one stable current-view item.

const (
	ThreadItemUser     ThreadItemKind = "user"
	ThreadItemSteering ThreadItemKind = "steering"
	// ThreadItemThinking is one ordered reasoning segment in a thread view.
	ThreadItemThinking    ThreadItemKind = "thinking"
	ThreadItemAssistant   ThreadItemKind = "assistant"
	ThreadItemTool        ThreadItemKind = "tool"
	ThreadItemInteraction ThreadItemKind = "interaction"
)

type ThreadModelContext added in v7.40.0

type ThreadModelContext struct {
	Snapshot        ModelContextSnapshot `json:"snapshot"`
	EntryID         string               `json:"entry_id"`
	PathDepth       int64                `json:"path_depth"`
	TurnID          identity.TurnID      `json:"turn_id"`
	RunID           identity.RunID       `json:"run_id"`
	UpdatedAt       time.Time            `json:"updated_at"`
	ChangedKeys     []string             `json:"changed_keys"`
	RemovedKeys     []string             `json:"removed_keys"`
	UsedByRequestID string               `json:"used_by_request_id,omitempty"`
	UsedByTurnID    identity.TurnID      `json:"used_by_turn_id,omitempty"`
	UsedByRunID     identity.RunID       `json:"used_by_run_id,omitempty"`
	UsedAt          *time.Time           `json:"used_at,omitempty"`
}

ThreadModelContext describes the current admitted managed facts on the active path and the latest prepared request that used that exact canonical record. A nil UsedAt means the facts have not yet been used by a model request.

type ThreadParentEventService added in v7.49.0

type ThreadParentEventService interface {
	ReportToParent(context.Context, ReportToParentInput) (ParentEventReceipt, error)
	ListParentEvents(context.Context, ListParentEventsInput) (ParentEventPage, error)
	ReadParentEvents(context.Context, ReadParentEventsInput) (ParentEventPage, error)
}

ThreadParentEventService is an optional Host-owned passive delivery capability. Hosts authorize each read. Reporting additionally verifies the canonical active invocation and derives the recipient from the direct parent relationship.

type ThreadPhase

type ThreadPhase string
const (
	ThreadPhaseIdle ThreadPhase = "idle"
	ThreadPhaseTurn ThreadPhase = "turn"
)

type ThreadQueryReader added in v7.31.0

ThreadQueryReader is an optional canonical index capability. Hosts authorize Scope before each query, page, read and aggregate. Tool arguments and confirmed output are private host facts; do not add them to ordinary presentation DTOs.

type ThreadQueueController added in v7.20.0

type ThreadQueueController interface {
	EditQueued(context.Context, EditQueuedInput) (ThreadView, error)
	SendQueuedNow(context.Context, PromoteQueuedInput) (ThreadView, error)
}

ThreadQueueController is an optional extension implemented by Host.ThreadService. It edits pending input or gracefully stops a response to send a chosen input. Existing ThreadService implementations remain source-compatible.

type ThreadQueueEditReader added in v7.34.0

type ThreadQueueEditReader interface {
	LookupQueuedEdit(context.Context, LookupQueuedEditInput) (QueuedInputEdit, bool, error)
}

ThreadQueueEditReader reads a committed queue edit from canonical facts, even after subsequent editing, promotion, deletion or restart. Hosts can validate transport retries without resolving resources again. It grants no access.

type ThreadRunPhase

type ThreadRunPhase string

ThreadRunPhase identifies one provider-neutral active-run phase.

const (
	ThreadRunPhasePreparing       ThreadRunPhase = "preparing"
	ThreadRunPhaseWaitingResponse ThreadRunPhase = "waiting_response"
	ThreadRunPhaseStreaming       ThreadRunPhase = "streaming"
	ThreadRunPhaseRetrying        ThreadRunPhase = "retrying"
	ThreadRunPhaseFinalizing      ThreadRunPhase = "finalizing"
	ThreadRunPhaseToolExecution   ThreadRunPhase = "tool_execution"
)

type ThreadRunProgress

type ThreadRunProgress struct {
	Request *ProviderRequestProgress `json:"request,omitempty"`
	Retry   *ProviderRetryProgress   `json:"retry,omitempty"`
	Phase   ThreadRunPhase           `json:"phase"`
}

ThreadRunProgress is the process-local presentation of an advancing run. It is absent while the thread is idle, terminal, or waiting for interaction.

type ThreadScope

type ThreadScope struct {
	ParentID *identity.ThreadID `json:"parent_id,omitempty"`
}

ThreadScope is a host-neutral root or direct-child inventory filter.

type ThreadSendReader added in v7.24.0

type ThreadSendReader interface {
	LookupSend(context.Context, LookupSendInput) (UserInput, bool, error)
}

ThreadSendReader is an optional read-only extension implemented by Host.ThreadService. It returns the original admitted input for a send key, even after queue editing, promotion, deletion, or restart. Hosts can validate transport retries without resolving attachments or refreshing runtime context. It does not authorize a caller or admit new work.

type ThreadStatus

type ThreadStatus string
const (
	ThreadStatusIdle        ThreadStatus = "idle"
	ThreadStatusRunning     ThreadStatus = "running"
	ThreadStatusCompleted   ThreadStatus = "completed"
	ThreadStatusWaiting     ThreadStatus = "waiting"
	ThreadStatusFailed      ThreadStatus = "failed"
	ThreadStatusCancelled   ThreadStatus = "cancelled"
	ThreadStatusInterrupted ThreadStatus = "interrupted"
)

type ThreadSteering added in v7.36.0

type ThreadSteering struct {
	Status ThreadSteeringStatus `json:"status"`
	// Reason classifies cancelled input: stopped, effect_outcome_unknown, task_ended, or fork.
	Reason string `json:"reason,omitempty"`
}

type ThreadSteeringController added in v7.36.0

type ThreadSteeringController interface {
	Steer(context.Context, SteerInput) (ThreadView, error)
	SteerQueued(context.Context, SteerQueuedInput) (ThreadView, error)
}

ThreadSteeringController is an optional capability of Host.ThreadService. Steering interrupts the current execution fragment, preserving the task and confirmed tool results. Accepted input is durable before this method returns.

type ThreadSteeringStatus added in v7.36.0

type ThreadSteeringStatus string
const (
	ThreadSteeringPending   ThreadSteeringStatus = "pending"
	ThreadSteeringApplied   ThreadSteeringStatus = "applied"
	ThreadSteeringCancelled ThreadSteeringStatus = "cancelled"
)

type ThreadSummary

type ThreadSummary struct {
	TurnKind        TurnKind            `json:"turn_kind,omitempty"`
	Cancellation    *ThreadCancellation `json:"cancellation,omitempty"`
	ID              identity.ThreadID   `json:"id"`
	ParentThreadID  identity.ThreadID   `json:"parent_thread_id,omitempty"`
	ParentTurnID    identity.TurnID     `json:"parent_turn_id,omitempty"`
	TaskName        string              `json:"task_name,omitempty"`
	TaskDescription string              `json:"task_description,omitempty"`
	HostProfileRef  string              `json:"host_profile_ref,omitempty"`
	ForkMode        string              `json:"fork_mode,omitempty"`
	Title           string              `json:"title,omitempty"`
	TitleStatus     ThreadTitleStatus   `json:"title_status,omitempty"`
	// TitleGeneration orders the complete Title/TitleStatus snapshot independently
	// of runtime view versions and activity timestamps. Zero means unset. A new
	// automatic attempt or manual title advances the generation; within one
	// generation, pending may settle to ready or failed, never the reverse.
	TitleGeneration int64              `json:"title_generation"`
	CreatedAt       time.Time          `json:"created_at"`
	UpdatedAt       time.Time          `json:"updated_at"`
	Activity        ThreadActivity     `json:"activity"`
	Attention       AttentionSummary   `json:"attention"`
	LastOutcome     *TurnOutcome       `json:"last_outcome,omitempty"`
	TurnID          identity.TurnID    `json:"turn_id,omitempty"`
	RunID           identity.RunID     `json:"run_id,omitempty"`
	RunProgress     *ThreadRunProgress `json:"run_progress,omitempty"`
	QueueCount      int                `json:"queue_count,omitempty"`
	Failure         *ThreadTurnFailure `json:"failure,omitempty"`
	PendingInput    *InputPresentation `json:"pending_input,omitempty"`
	LastItemAt      time.Time          `json:"last_item_at,omitempty"`
	LastItemPreview string             `json:"last_item_preview,omitempty"`
}

type ThreadSummaryReader added in v7.52.0

type ThreadSummaryReader interface {
	Summary(context.Context, identity.ThreadID) (ThreadSummary, error)
}

ThreadSummaryReader reads canonical summaries without constructing ThreadView history or creating a thread actor. Hosts authorize the thread before reading.

type ThreadTitleMode

type ThreadTitleMode string

ThreadTitleMode selects who owns durable thread title generation.

const (
	ThreadTitleModeHostOwned ThreadTitleMode = "host_owned"
	ThreadTitleModeProvider  ThreadTitleMode = "provider"
)

type ThreadTitleStatus

type ThreadTitleStatus string

ThreadTitleStatus is presentation metadata derived from the canonical thread journal. It does not own thread lifecycle state.

const (
	ThreadTitleStatusUnset   ThreadTitleStatus = ""
	ThreadTitleStatusPending ThreadTitleStatus = "pending"
	ThreadTitleStatusReady   ThreadTitleStatus = "ready"
	ThreadTitleStatusFailed  ThreadTitleStatus = "failed"
)

type ThreadTokenUsageTotals

type ThreadTokenUsageTotals struct {
	InputTokens      int64 `json:"input_tokens,omitempty"`
	OutputTokens     int64 `json:"output_tokens,omitempty"`
	CacheReadTokens  int64 `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
}

ThreadTokenUsageTotals contains disjoint token totals from canonical final provider usage records across one thread.

type ThreadToolCallPreview added in v7.39.0

type ThreadToolCallPreview struct {
	ThreadID          identity.ThreadID         `json:"thread_id"`
	TurnID            identity.TurnID           `json:"turn_id"`
	RunID             identity.RunID            `json:"run_id"`
	LogicalRequestID  identity.LogicalRequestID `json:"logical_request_id"`
	AttemptID         string                    `json:"attempt_id"`
	AttemptEpoch      int                       `json:"attempt_epoch"`
	CallID            string                    `json:"call_id"`
	Name              string                    `json:"name"`
	ArgumentsComplete bool                      `json:"arguments_complete"`
	Preview           *tools.ArgumentPreview    `json:"preview"`
}

ThreadToolCallPreview describes unvalidated arguments, never a running tool. It has no canonical item ordinal or durable representation. Matching admitted calls may use its counts until their authoritative result arrives.

type ThreadToolResult added in v7.30.0

type ThreadToolResult struct {
	EffectOutcome tools.EffectOutcome `json:"effect_outcome,omitempty"`
	ToolName      string              `json:"tool_name"`
	Arguments     string              `json:"arguments"`
	Content       string              `json:"content"`
	Status        string              `json:"status"`
}

ThreadToolResult contains the original canonical arguments and visible output, without rebuilding provider history or resolving any host resource.

type ThreadToolResultReader added in v7.30.0

type ThreadToolResultReader interface {
	LookupToolResult(context.Context, LookupToolResultInput) (ThreadToolResult, bool, error)
}

ThreadToolResultReader reads a confirmed local tool result from the active canonical path. Hosts authorize access and interpret their own tool output; these private facts must not be included in public presentation by default. Lookup never dispatches a tool, reads an artifact, or changes journal state.

type ThreadTurn added in v7.29.0

type ThreadTurn struct {
	TurnID                identity.TurnID `json:"turn_id"`
	RunID                 identity.RunID  `json:"run_id"`
	Kind                  TurnKind        `json:"kind,omitempty"`
	StartedAt             time.Time       `json:"started_at"`
	EndedAt               *time.Time      `json:"ended_at,omitempty"`
	Outcome               *TurnOutcome    `json:"outcome,omitempty"`
	ElapsedMS             int64           `json:"elapsed_ms"`
	WaitingMS             int64           `json:"waiting_ms"`
	WorkDurationMS        int64           `json:"work_duration_ms"`
	FinalItemIDs          []string        `json:"final_item_ids"`
	FinalBoundaryComplete bool            `json:"final_boundary_complete"`
	// contains filtered or unexported fields
}

ThreadTurn contains canonical facts about one admitted conversational turn. Durations settle only with a terminal marker, exclude queue time, and deduct the union of user-input and approval waits. An unavailable final boundary is distinct from a recorded final boundary with no assistant text.

type ThreadTurnFailure

type ThreadTurnFailure struct {
	Reason ThreadTurnFailureReason `json:"reason,omitempty"`

	ProviderTimeout *publicprovider.RequestTimeoutDetails `json:"provider_timeout,omitempty"`
	Code            ThreadTurnFailureCode                 `json:"code"`
	Message         string                                `json:"message"`
}

func (ThreadTurnFailure) Validate

func (f ThreadTurnFailure) Validate() error

type ThreadTurnFailureCode

type ThreadTurnFailureCode string
const (
	ThreadTurnFailureCancelled                ThreadTurnFailureCode = "cancelled"
	ThreadTurnFailureInterrupted              ThreadTurnFailureCode = "interrupted"
	ThreadTurnFailureProvider                 ThreadTurnFailureCode = "provider"
	ThreadTurnFailureToolDispatch             ThreadTurnFailureCode = "tool_dispatch"
	ThreadTurnFailureControlError             ThreadTurnFailureCode = "control_error"
	ThreadTurnFailureEffectOutcomeUnknown     ThreadTurnFailureCode = "effect_outcome_unknown"
	ThreadTurnFailureAuthorizationUnavailable ThreadTurnFailureCode = "authorization_unavailable"
	ThreadTurnFailureAuthorizationContract    ThreadTurnFailureCode = "authorization_contract"
	ThreadTurnFailureStorage                  ThreadTurnFailureCode = "storage"
	ThreadTurnFailureEngineContract           ThreadTurnFailureCode = "engine_contract"
	ThreadTurnFailureContextBudgetInvalid     ThreadTurnFailureCode = "context_budget_invalid"
	ThreadTurnFailureContextFixedOverhead     ThreadTurnFailureCode = "context_fixed_overhead"
	ThreadTurnFailureContextCompactionLimit   ThreadTurnFailureCode = "context_compaction_limit"
	ThreadTurnFailureContextPrefixDrift       ThreadTurnFailureCode = "context_prefix_drift"
	ThreadTurnFailureModelContextUnavailable  ThreadTurnFailureCode = "model_context_unavailable"
	ThreadTurnFailureLegacyUnclassified       ThreadTurnFailureCode = "legacy_unclassified"
)

func (ThreadTurnFailureCode) Valid

func (c ThreadTurnFailureCode) Valid() bool

type ThreadTurnFailureReason added in v7.51.0

type ThreadTurnFailureReason string

ThreadTurnFailureReason is a safe, product-neutral classification derived from canonical failure facts. Unknown messages retain an empty reason.

const (
	ThreadTurnFailureRepeatedToolCalls   ThreadTurnFailureReason = "repeated_tool_calls"
	ThreadTurnFailureNoProgress          ThreadTurnFailureReason = "no_progress"
	ThreadTurnFailureDuplicateToolCallID ThreadTurnFailureReason = "duplicate_tool_call_id"
	ThreadTurnFailureStopHookLoop        ThreadTurnFailureReason = "stop_hook_loop"
)

type ThreadView

type ThreadView struct {
	// ParentEvents is a bounded, explicitly paginated receipt view, separate from streamed item ordinals.
	ParentEvents     *ParentEventPage        `json:"parent_events,omitempty"`
	ToolCallPreviews []ThreadToolCallPreview `json:"tool_call_previews,omitempty"`
	Turns            []ThreadTurn            `json:"turns"`
	TurnKind         TurnKind                `json:"turn_kind,omitempty"`
	Cancellation     *ThreadCancellation     `json:"cancellation,omitempty"`
	RestoredInputs   []RestoredInput         `json:"restored_inputs,omitempty"`
	ThreadID         identity.ThreadID       `json:"thread_id"`
	ViewVersion      uint64                  `json:"view_version"`
	Activity         ThreadActivity          `json:"activity"`
	Attention        AttentionSummary        `json:"attention"`
	LastOutcome      *TurnOutcome            `json:"last_outcome,omitempty"`
	Failure          *ThreadTurnFailure      `json:"failure,omitempty"`
	TurnID           identity.TurnID         `json:"turn_id,omitempty"`
	RunID            identity.RunID          `json:"run_id,omitempty"`
	RunProgress      *ThreadRunProgress      `json:"run_progress,omitempty"`
	Items            []ThreadItem            `json:"items,omitempty"`
	Queue            []QueuedInput           `json:"queue,omitempty"`
	Interactions     []ThreadInteraction     `json:"interactions,omitempty"`
}

ThreadView is the complete, replaceable presentation for one thread. Its version is process-local notification ordering, not a durable journal cursor.

type ThreadWaitReason added in v7.51.0

type ThreadWaitReason string
const (
	ThreadWaitCompleted         ThreadWaitReason = "completed"
	ThreadWaitAttentionRequired ThreadWaitReason = "attention_required"
	ThreadWaitMissing           ThreadWaitReason = "missing"
	ThreadWaitTimedOut          ThreadWaitReason = "timed_out"
)
const ThreadWaitEvents ThreadWaitReason = "events"

type ThreadWaitResult added in v7.51.0

type ThreadWaitResult struct {
	ParentEvents     *ParentEventPage    `json:"parent_events,omitempty"`
	Threads          []ThreadSummary     `json:"threads"`
	MissingThreadIDs []identity.ThreadID `json:"missing_thread_ids"`
	Reason           ThreadWaitReason    `json:"reason"`
}

type ThreadWaiter added in v7.51.0

type ThreadWaiter interface {
	WaitThreads(context.Context, WaitThreadsInput) (ThreadWaitResult, error)
}

ThreadWaiter observes current state without admitting input or resuming parents. Omitted targets are frozen by the first scoped read.

type ToolCallStream

type ToolCallStream struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
}

type ToolSurface

type ToolSurface struct {
	ModelContextSnapshot *ModelContextSnapshot

	// RefreshProviderSurface opts into resolving system text and tool definitions
	// at each provider request. Model, reasoning, context policy and historical
	// checkpoints stay fixed. The zero value preserves the first Turn surface.
	RefreshProviderSurface bool
	Tools                  *tools.Registry
	ToolDefinitions        []tools.ToolDefinition
	HostedToolDefinitions  []publicprovider.HostedToolDefinition
	SystemPrompt           string
	HostContext            map[string]string
	Epoch                  string
	Reason                 string
}

type ToolSurfaceProvider

type ToolSurfaceProvider func(context.Context, ToolSurfaceRequest) (ToolSurface, error)

type ToolSurfaceRequest

type ToolSurfaceRequest struct {
	// InitialProviderSurface is the first checkpoint of this Turn, or nil before
	// the first provider checkpoint. Hosts can retain capabilities unrelated to a live policy change.
	// Mutating it cannot alter stored requests.
	InitialProviderSurface *ProviderToolSurface
	RunID                  identity.RunID
	ThreadID               identity.ThreadID
	TurnID                 identity.TurnID
	TraceID                identity.TraceID
	PromptScopeID          identity.PromptScopeID
	Step                   int
	Phase                  string
	Labels                 RunLabels
	HostContext            map[string]string
}

type TurnInput

type TurnInput struct {
	ModelContextSnapshot *ModelContextSnapshot `json:"model_context_snapshot,omitempty"`
	Text                 string                `json:"text,omitempty"`
	Attachments          []MessageAttachment   `json:"attachments,omitempty"`
	References           []MessageReference    `json:"references,omitempty"`
	Context              []MessageContextItem  `json:"context,omitempty"`
}

func (TurnInput) Validate

func (i TurnInput) Validate() error

type TurnKind added in v7.26.0

type TurnKind string

TurnKind distinguishes a conversation turn from a context-only operation. The zero value retains the ordinary conversation contract.

const TurnKindContextCompaction TurnKind = "context_compaction"

type TurnLimits

type TurnLimits struct {
	MaxInputTokens           int64
	MaxTotalTokens           int64
	MaxCostUSD               float64
	MaxToolCalls             int
	MaxLengthContinuations   int
	MaxStopHookContinuations int
}

type TurnOutcome

type TurnOutcome string

TurnOutcome is a terminal outcome rendered on one turn, never as thread failure.

const (
	TurnOutcomeCompleted   TurnOutcome = "completed"
	TurnOutcomeFailed      TurnOutcome = "failed"
	TurnOutcomeCancelled   TurnOutcome = "cancelled"
	TurnOutcomeInterrupted TurnOutcome = "interrupted"
)

type TurnResult

type TurnResult struct {
	ThreadID           identity.ThreadID              `json:"thread_id"`
	TurnID             identity.TurnID                `json:"turn_id"`
	RunID              identity.RunID                 `json:"-"`
	Status             TurnStatus                     `json:"status"`
	Output             string                         `json:"output,omitempty"`
	Failure            *ThreadTurnFailure             `json:"failure,omitempty"`
	Diagnostics        map[string]string              `json:"diagnostics,omitempty"`
	Metrics            RunMetrics                     `json:"metrics"`
	CompletionReason   observation.CompletionReason   `json:"completion_reason,omitempty"`
	ContinuationReason observation.ContinuationReason `json:"continuation_reason,omitempty"`
	FinishReason       observation.FinishReason       `json:"finish_reason,omitempty"`
	RawFinishReason    string                         `json:"raw_finish_reason,omitempty"`
	FinishInferred     bool                           `json:"finish_inferred,omitempty"`
	Signal             *TurnSignal                    `json:"signal,omitempty"`
	ActivityTimeline   observation.ActivityTimeline   `json:"activity_timeline"`
	Replayed           bool                           `json:"replayed,omitempty"`
}

func (TurnResult) Validate

func (r TurnResult) Validate() error

type TurnSignal

type TurnSignal struct {
	Disposition SignalDisposition           `json:"disposition"`
	Name        string                      `json:"name"`
	CallID      string                      `json:"call_id,omitempty"`
	Payload     map[string]any              `json:"payload,omitempty"`
	Activity    *tools.ActivityPresentation `json:"activity,omitempty"`
	OutputText  string                      `json:"output_text,omitempty"`
	ArgsHash    string                      `json:"args_hash,omitempty"`
	Labels      map[string]string           `json:"labels,omitempty"`
}

func ProjectCoreControlSignal

func ProjectCoreControlSignal(call tools.ToolCall) (TurnSignal, bool, error)

ProjectCoreControlSignal projects ask_user calls into Floret control signals.

type TurnSignalSpec

type TurnSignalSpec struct {
	Definitions []tools.ToolDefinition
	Identity    string
	Project     func(tools.ToolCall) (TurnSignal, bool, error)
}

type TurnStatus

type TurnStatus string
const (
	TurnStatusRunning     TurnStatus = "running"
	TurnStatusCompleted   TurnStatus = "completed"
	TurnStatusWaiting     TurnStatus = "waiting"
	TurnStatusFailed      TurnStatus = "failed"
	TurnStatusCancelled   TurnStatus = "cancelled"
	TurnStatusInterrupted TurnStatus = "interrupted"
)

func (TurnStatus) IsTerminal

func (s TurnStatus) IsTerminal() bool

func (TurnStatus) Valid

func (s TurnStatus) Valid() bool

type TurnSupplementalContextItem

type TurnSupplementalContextItem struct {
	Kind      string
	Title     string
	Text      string
	Metadata  map[string]string
	Sensitive bool
	Truncated bool
}

type UserInput

type UserInput = TurnInput

UserInput is one user-authored thread input.

type WaitThreadsInput added in v7.51.0

type WaitThreadsInput struct {
	// PendingParentEvents returns pending canonical receipts for Scope.ParentID.
	// This is passive observation and never wakes an idle parent execution.
	PendingParentEvents bool

	Scope     ThreadScope
	ThreadIDs []identity.ThreadID
	Timeout   time.Duration
}

type WorkspaceSubscription

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

WorkspaceSubscription receives replaceable current views.

func (*WorkspaceSubscription) Close

func (subscription *WorkspaceSubscription) Close()

func (*WorkspaceSubscription) Next

func (subscription *WorkspaceSubscription) Next(ctx context.Context) (ThreadView, error)

Jump to

Keyboard shortcuts

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