assistant

package
v0.0.0-...-820128f Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 50 Imported by: 0

Documentation

Overview

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Package assistant orchestrates conversations, extensions, cache, and prompt execution.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSteeringInactive indicates that the session has no active steering inbox.
	ErrSteeringInactive = errors.New("steering run is inactive")
	// ErrSteeringStaleRun indicates that the request targets an older active run.
	ErrSteeringStaleRun = errors.New("steering run identity is stale")
	// ErrSteeringClosed indicates that the targeted inbox closed before accepting the request.
	ErrSteeringClosed = errors.New("steering inbox is closed")
	// ErrSteeringCapacity indicates that the active inbox cannot accept more messages.
	ErrSteeringCapacity = errors.New("steering inbox capacity exceeded")
	// ErrSteeringInvalidInput indicates that a steering request failed validation.
	ErrSteeringInvalidInput = errors.New("invalid steering input")
)

Functions

func DefaultCWD

func DefaultCWD(cwd string) (string, error)

DefaultCWD returns an absolute working directory for prompt requests.

func IsContextWindowError

func IsContextWindowError(err error) bool

IsContextWindowError reports whether err indicates provider-side context exhaustion.

func IsStructuredContextWindowError

func IsStructuredContextWindowError(err error) bool

IsStructuredContextWindowError excludes broad message guesses from replay.

func ShouldRetryModelError

func ShouldRetryModelError(err error) bool

ShouldRetryModelError reports whether a model/provider error is transient.

func WithRunMetrics

func WithRunMetrics(ctx context.Context, metrics *RunMetrics) context.Context

WithRunMetrics returns a context that records prompt execution metrics.

func WithToolStrategy

func WithToolStrategy(ctx context.Context, strategy ToolStrategy) context.Context

WithToolStrategy returns a context that selects a provider-facing tool strategy.

Types

type AgentSubmitRequest

type AgentSubmitRequest struct {
	ParentTaskID    string
	OwnerSessionID  string
	CWD             string
	AgentName       string
	Prompt          string
	Model           string
	Provider        string
	ConcurrencyKey  string
	NodeKey         string
	InvocationIndex int
	Depth           int
}

AgentSubmitRequest describes one high-level durable agent launch.

type AgentSubmitter

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

AgentSubmitter creates child sessions and snapshots agent policy before submitting durable work.

func NewAgentSubmitter

func NewAgentSubmitter(
	controller AgentTaskController,
	catalog *agent.Catalog,
) (*AgentSubmitter, error)

NewAgentSubmitter creates the shared high-level agent submission boundary.

func (*AgentSubmitter) SubmitAgent

func (submitter *AgentSubmitter) SubmitAgent(
	ctx context.Context,
	request *AgentSubmitRequest,
) (*database.AgentTaskEntity, error)

SubmitAgent resolves policy, creates a child session, and durably submits work.

type AgentTaskController

type AgentTaskController interface {
	SubmitAgentTask(context.Context, *AgentTaskRequest) (*database.AgentTaskEntity, error)
	Get(context.Context, string) (*database.AgentTaskEntity, bool, error)
	List(context.Context, string, int) ([]database.AgentTaskEntity, error)
	Cancel(context.Context, string, string, string) (*database.TaskEntity, bool, error)
	Await(context.Context, string) (*database.AgentTaskEntity, error)
	SubscribeAgentTask(string) (events <-chan database.TaskEventEntity, cancel func(), err error)
}

AgentTaskController is the runtime-facing boundary for durable agent work.

type AgentTaskRequest

type AgentTaskRequest struct {
	ParentTaskID     string
	OwnerSessionID   string
	ChildSessionID   string
	ChildSessionCWD  string
	ChildSessionName string
	AgentName        string
	Prompt           string
	Model            string
	Provider         string
	PolicyJSON       string
	ConcurrencyKey   string
	NodeKey          string
	InvocationIndex  int
	Depth            int
}

AgentTaskRequest describes one asynchronous agent submission.

type Completer

type Completer interface {
	Complete(ctx context.Context, request *CompletionRequest) (*CompletionResult, error)
}

Completer talks to provider APIs through assistant-owned request/result types.

type CompletionRequest

type CompletionRequest struct {
	OnEvent                func(StreamEvent)                              `json:"-"`
	OnProviderObserve      func(context.Context, *CompletionRequest, int) `json:"-"`
	OnProviderResponse     func(context.Context, model.TokenUsage)        `json:"-"`
	OnProviderRequest      llm.ProviderRequestHook                        `json:"-"`
	OnRoundCheckpoint      llm.RoundCheckpoint                            `json:"-"`
	ToolRegistry           *tool.Registry                                 `json:"-"`
	ExecuteTools           ToolExecutor                                   `json:"-"`
	CWD                    string                                         `json:"cwd"`
	SystemPrompt           string                                         `json:"system_prompt"`
	ThinkingLevel          string                                         `json:"thinking_level"`
	SessionID              string                                         `json:"session_id"`
	Identity               RequestIdentity                                `json:"-"`
	Auth                   model.RequestAuth                              `json:"auth"`
	Messages               []database.MessageEntity                       `json:"messages"`
	Usage                  model.TokenUsage                               `json:"usage"`
	Model                  model.Model                                    `json:"model"`
	ProviderAttempt        int                                            `json:"-"`
	MaxTokens              int                                            `json:"max_tokens,omitempty"`
	DisableTools           bool                                           `json:"-"`
	ToolSideEffectsStarted bool                                           `json:"-"`
}

CompletionRequest describes one assistant-owned model completion request.

type CompletionResult

type CompletionResult struct {
	FinishReason llm.FinishReason        `json:"finish_reason,omitempty"`
	Termination  llm.TerminationMetadata `json:"termination,omitzero"`
	Text         string                  `json:"text"`
	Thinking     []string                `json:"thinking,omitempty"`
	ToolEvents   []ToolEvent             `json:"tool_events,omitempty"`
	Usage        model.TokenUsage        `json:"usage"`
}

CompletionResult is an assistant-owned provider response plus model-visible side effects.

type ExecutionKind

type ExecutionKind string

ExecutionKind identifies the purpose of one runtime execution.

const (
	// ExecutionTopLevel is an interactive user-owned prompt.
	ExecutionTopLevel ExecutionKind = "top_level"
	// ExecutionAgentTask is a durable background agent task.
	ExecutionAgentTask ExecutionKind = "agent_task"
)

type ExecutionProfile

type ExecutionProfile struct {
	Kind             ExecutionKind
	AgentName        string
	SystemPrompt     string
	Provider         string
	Model            string
	ThinkingLevel    model.ThinkingLevel
	PermissionMode   agent.PermissionMode
	Tools            []tool.Name
	EnableSkills     bool
	EnableExtensions bool
	MaxTurns         int
	Depth            int
}

ExecutionProfile is an immutable snapshot of prompt capabilities and overrides.

type HTTPClient

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

HTTPClient adapts the provider HTTP client to assistant-owned types.

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient creates an HTTP-backed provider client.

func (*HTTPClient) Complete

func (client *HTTPClient) Complete(
	ctx context.Context,
	request *CompletionRequest,
) (*CompletionResult, error)

Complete sends an assistant-owned completion request to the provider client.

type ImageAttachment

type ImageAttachment struct {
	Name     string `json:"name,omitempty"`
	MIMEType string `json:"mime_type"`
	Data     []byte `json:"-"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
}

ImageAttachment is one provider-neutral image supplied with a prompt.

type OverflowRecoveryDecision

type OverflowRecoveryDecision struct {
	Refusal string
	Recover bool
}

OverflowRecoveryDecision reports whether recovery is allowed and why it may be refused.

func DecideOverflowRecovery

func DecideOverflowRecovery(value any) OverflowRecoveryDecision

DecideOverflowRecovery applies the bounded one-replay overflow recovery policy.

type OverflowRecoveryDecisionInput

type OverflowRecoveryDecisionInput struct {
	Classification           ResponseClassification
	Identity, ActiveIdentity RequestIdentity
	Replay                   ReplayState
	HasCompactionCandidate   bool
}

OverflowRecoveryDecisionInput contains all state used by overflow recovery policy.

type PromptRequest

type PromptRequest struct {
	OnEvent          func(StreamEvent)          `json:"-"`
	OnRetry          RetryEventHandler          `json:"-"`
	OnUserEntry      func(PromptUserEntryEvent) `json:"-"`
	OnSteeringReturn func([]SteeringMessage)    `json:"-"`
	ParentEntryID    *string                    `json:"parent_entry_id,omitempty"`
	SessionID        string                     `json:"session_id"`
	CWD              string                     `json:"cwd"`
	Text             string                     `json:"text"`
	Name             string                     `json:"name"`
	Images           []ImageAttachment          `json:"images,omitempty"`
	ResumeLatest     bool                       `json:"resume_latest,omitempty"`
	HideUserPrompt   bool                       `json:"-"`
}

PromptRequest contains one user prompt invocation.

type PromptResponse

type PromptResponse struct {
	SessionID        string           `json:"session_id"`
	UserEntryID      string           `json:"user_entry_id"`
	AssistantEntryID string           `json:"assistant_entry_id"`
	Text             string           `json:"text"`
	Thinking         []string         `json:"thinking,omitempty"`
	ToolEvents       []ToolEvent      `json:"tool_events,omitempty"`
	Usage            model.TokenUsage `json:"usage"`
	Cached           bool             `json:"cached"`
}

PromptResponse describes persisted prompt output.

type PromptUserEntryEvent

type PromptUserEntryEvent struct {
	SessionID string `json:"session_id"`
	EntryID   string `json:"entry_id"`
}

PromptUserEntryEvent identifies the persisted user entry for an active prompt.

type ReplayState

type ReplayState struct{ RecoveryConsumed, ToolDispatchStarted, LineageAdvanced bool }

ReplayState records conditions that make replay unsafe or redundant.

type RequestIdentity

type RequestIdentity struct {
	LogicalRequestID     string
	Provider             string
	Model                string
	LineageParentEntryID string
	ProviderAttempt      int
	CompactionGeneration uint64
	RecoveryAttempt      uint8
}

RequestIdentity identifies one provider request and its active prompt lineage.

type ResponseCache

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

ResponseCache stores deterministic local prompt responses for fast replay.

func NewResponseCache

func NewResponseCache(enabled bool, capacity int, ttl time.Duration) *ResponseCache

NewResponseCache creates a TTL response cache.

func (*ResponseCache) Get

func (cache *ResponseCache) Get(key string) (value string, found bool, err error)

Get returns a cached response when caching is enabled and the key exists.

func (*ResponseCache) Set

func (cache *ResponseCache) Set(key, value string)

Set stores a response when caching is enabled.

func (*ResponseCache) Shutdown

func (cache *ResponseCache) Shutdown()

Shutdown stops the cache janitor.

type ResponseClass

type ResponseClass string

ResponseClass identifies the provider response category used by recovery policy.

const (
	ResponseSuccess                 ResponseClass = "success"
	ResponseExplicitContextOverflow ResponseClass = "explicit_context_overflow"
	ResponseMetadataContextOverflow ResponseClass = "metadata_context_overflow"
	ResponseOutputLengthTruncation  ResponseClass = "output_length_truncation"
	ResponseContentFilter           ResponseClass = "content_filter"
	ResponseRefusal                 ResponseClass = "refusal"
	ResponseProviderError           ResponseClass = "provider_error"
)

Provider response classifications.

type ResponseClassification

type ResponseClassification struct {
	Class                 ResponseClass
	FinishReason          llm.FinishReason
	IncompleteReason      string
	ContextOverflowSignal string
	OutputLimit           int
	ReportedOutputTokens  int
}

ResponseClassification records a response category and the metadata that determined it.

func ClassifyResponse

func ClassifyResponse(value any) ResponseClassification

ClassifyResponse is provider-aware and deliberately uses only documented, bounded metadata. Error text is never searched for successful responses.

type ResponseClassificationInput

type ResponseClassificationInput struct {
	Err                  error
	Termination          llm.TerminationMetadata
	Provider             string
	API                  string
	Model                string
	FinishReason         llm.FinishReason
	RequestedMaxOutput   int
	ReportedOutputTokens int
}

ResponseClassificationInput contains bounded provider metadata used to classify a response.

type RetryEvent

type RetryEvent struct {
	Kind        RetryEventKind `json:"kind"`
	Error       string         `json:"error,omitempty"`
	Attempt     int            `json:"attempt"`
	MaxAttempts int            `json:"max_attempts"`
	Delay       time.Duration  `json:"delay,omitempty"`
}

RetryEvent describes a model retry lifecycle transition.

type RetryEventHandler

type RetryEventHandler func(RetryEvent)

RetryEventHandler receives retry lifecycle events.

type RetryEventKind

type RetryEventKind string

RetryEventKind identifies model retry lifecycle events.

const (
	// RetryEventStart is emitted after a retryable model error before waiting.
	RetryEventStart RetryEventKind = "retry_start"
	// RetryEventEnd is emitted after a later attempt succeeds.
	RetryEventEnd RetryEventKind = "retry_end"
)

type RunMetrics

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

RunMetrics collects request-local provider, usage, and tool-trace observations.

func (*RunMetrics) ObserveStreamEvent

func (metrics *RunMetrics) ObserveStreamEvent(event StreamEvent)

ObserveStreamEvent records tool starts and results for trace accounting.

func (*RunMetrics) ProviderRoundTrips

func (metrics *RunMetrics) ProviderRoundTrips() int64

ProviderRoundTrips returns the observed provider request count.

func (*RunMetrics) SetUsageTotalsObserver

func (metrics *RunMetrics) SetUsageTotalsObserver(observer func(model.UsageTotals))

SetUsageTotalsObserver installs a callback invoked after every successfully accounted provider response. The callback runs without the metrics lock held.

func (*RunMetrics) Snapshot

func (metrics *RunMetrics) Snapshot() RunMetricsSnapshot

Snapshot returns a concurrency-safe copy of the collected metrics.

func (*RunMetrics) UsageTotals

func (metrics *RunMetrics) UsageTotals() (model.UsageTotals, error)

UsageTotals returns the cumulative provider usage snapshot and any accounting error.

type RunMetricsSnapshot

type RunMetricsSnapshot struct {
	ProviderRoundTrips  int64
	InputTokens         int64
	OutputTokens        int64
	ToolCalls           int
	NestedToolCalls     int
	UsageTotalsReported bool
	TraceComplete       bool
}

RunMetricsSnapshot is a stable point-in-time view of prompt execution metrics.

type Runtime

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

Runtime coordinates prompt handling and durable sessions.

func NewRuntime

func NewRuntime(options *RuntimeOptions) *Runtime

NewRuntime creates an assistant runtime.

func NewRuntimeForTest

func NewRuntimeForTest(setup func(*RuntimeTestOptions)) *Runtime

NewRuntimeForTest builds a Runtime from the given setup closure, setting every RuntimeOptions field explicitly in a single place. This eliminates duplicated struct literals across test files (which triggers SonarCloud duplication warnings when exhaustruct forces every field to be listed).

func (*Runtime) AgentDefinitions

func (runtime *Runtime) AgentDefinitions() []agent.Definition

AgentDefinitions returns immutable copies of discovered agent profiles.

func (*Runtime) AgentDiagnostics

func (runtime *Runtime) AgentDiagnostics() []agent.Diagnostic

AgentDiagnostics returns profile discovery and validation diagnostics.

func (*Runtime) AgentTask

func (runtime *Runtime) AgentTask(
	ctx context.Context,
	taskID string,
) (*database.AgentTaskEntity, bool, error)

AgentTask returns one durable agent task.

func (*Runtime) AgentTaskEvents

func (runtime *Runtime) AgentTaskEvents(
	ctx context.Context,
	taskID string,
	after int64,
	limit int,
) ([]database.TaskEventEntity, error)

AgentTaskEvents returns durable stream events for one agent task after a sequence.

func (*Runtime) AgentTasks

func (runtime *Runtime) AgentTasks(
	ctx context.Context,
	ownerSessionID string,
	limit int,
) ([]database.AgentTaskEntity, error)

AgentTasks returns durable agent tasks owned by a session.

func (*Runtime) BackgroundToolCompletion

func (runtime *Runtime) BackgroundToolCompletion(
	ctx context.Context,
	completion *tooltask.Completion,
) error

BackgroundToolCompletion applies result/error lifecycle hooks in the worker that owns the durable execution. Admission has already applied tool_call.

func (*Runtime) CancelAgentTask

func (runtime *Runtime) CancelAgentTask(
	ctx context.Context,
	ownerSessionID string,
	taskID string,
) (*database.TaskEntity, bool, error)

CancelAgentTask requests cancellation of one durable agent task.

func (*Runtime) CancelToolTask

func (runtime *Runtime) CancelToolTask(
	ctx context.Context,
	ownerSessionID string,
	taskID string,
) (*database.ToolTaskEntity, bool, error)

CancelToolTask requests owner-scoped cancellation of durable background tool work.

func (*Runtime) CompactSession

func (runtime *Runtime) CompactSession(
	ctx context.Context,
	sessionID string,
	cwd string,
) (*database.EntryEntity, error)

CompactSession summarizes older model-facing context and appends a compaction entry.

func (*Runtime) CompactSessionFrom

func (runtime *Runtime) CompactSessionFrom(
	ctx context.Context,
	sessionID string,
	cwd string,
	parentEntryID *string,
) (*database.EntryEntity, error)

CompactSessionFrom compacts the branch ending at parentEntryID, or the latest leaf when nil.

func (*Runtime) ContextUsage

func (runtime *Runtime) ContextUsage(ctx context.Context, sessionID, cwd string) (model.TokenUsage, error)

ContextUsage estimates the current model-facing context without executing a prompt. It is intended for diagnostics such as /context and intentionally avoids prompt-dependent skill activation and extension context mutation.

func (*Runtime) DetachForegroundTool

func (runtime *Runtime) DetachForegroundTool(callID string) (string, bool)

DetachForegroundTool detaches the eligible foreground call identified by its provider call ID. It returns the stable durable task ID.

func (*Runtime) ModelRegistry

func (runtime *Runtime) ModelRegistry() *model.Registry

ModelRegistry returns the model registry used by the runtime.

func (*Runtime) Prompt

func (runtime *Runtime) Prompt(ctx context.Context, request *PromptRequest) (response *PromptResponse, err error)

Prompt appends a user prompt and an assistant response to the selected session.

func (*Runtime) SessionRepository

func (runtime *Runtime) SessionRepository() *database.SessionRepository

SessionRepository returns the underlying session repository for command and UI layers.

func (*Runtime) Steer

func (runtime *Runtime) Steer(ctx context.Context, request *SteeringRequest) error

Steer transfers one user message to an active run's steering inbox.

func (*Runtime) SubscribeAgentTask

func (runtime *Runtime) SubscribeAgentTask(
	taskID string,
) (events <-chan database.TaskEventEntity, cancel func(), err error)

SubscribeAgentTask follows persisted events for one agent task.

func (*Runtime) SubscribeToolTaskCompletions

func (runtime *Runtime) SubscribeToolTaskCompletions() (
	events <-chan tooltask.Completion, cancel func(), err error,
)

SubscribeToolTaskCompletions follows locally completed durable tool executions.

func (*Runtime) ToolTask

func (runtime *Runtime) ToolTask(
	ctx context.Context,
	ownerSessionID string,
	taskID string,
) (*database.ToolTaskEntity, bool, error)

ToolTask returns one owner-scoped durable background tool task.

func (*Runtime) ToolTasks

func (runtime *Runtime) ToolTasks(
	ctx context.Context,
	ownerSessionID string,
	states []database.TaskState,
	limit int,
) ([]database.ToolTaskEntity, error)

ToolTasks returns durable background tool tasks owned by a session.

func (*Runtime) WithExecutionProfile

func (runtime *Runtime) WithExecutionProfile(profile *ExecutionProfile) *Runtime

WithExecutionProfile returns a runtime view with an immutable execution profile. Runtime dependencies remain shared and safe for concurrent prompt execution.

type RuntimeOptions

type RuntimeOptions struct {
	Config            *config.Config
	Sessions          *database.SessionRepository
	Extensions        runtimeExtensions
	Cache             *ResponseCache
	Models            *model.Registry
	Client            Completer
	Logger            *slog.Logger
	SkillsCache       *core.SkillsCache
	Agents            *agent.Catalog
	AgentTasks        AgentTaskController
	WorkflowSubmitter WorkflowSubmitter
	ToolTasks         ToolTaskController
	ToolCoordinator   *tool.Coordinator
}

RuntimeOptions contains dependencies for an assistant runtime.

type RuntimeTestOptions

type RuntimeTestOptions struct {
	Config            *config.Config
	Sessions          *database.SessionRepository
	Extensions        runtimeExtensions
	Cache             *ResponseCache
	Models            *model.Registry
	Client            Completer
	Logger            *slog.Logger
	SkillsCache       *core.SkillsCache
	Agents            *agent.Catalog
	AgentTasks        AgentTaskController
	WorkflowSubmitter WorkflowSubmitter
	ToolTasks         ToolTaskController
	ToolCoordinator   *tool.Coordinator
}

RuntimeTestOptions holds optional Runtime dependencies for test factories.

type SteeringConsumedEvent

type SteeringConsumedEvent struct {
	EntryID        string            `json:"entry_id"`
	Text           string            `json:"text"`
	Images         []ImageAttachment `json:"images,omitempty"`
	HideUserPrompt bool              `json:"hide_user_prompt"`
}

SteeringConsumedEvent identifies a steering message after it becomes durable.

type SteeringMessage

type SteeringMessage struct {
	Text           string            `json:"text"`
	Images         []ImageAttachment `json:"images,omitempty"`
	HideUserPrompt bool              `json:"-"`
}

SteeringMessage is a user draft returned when a run settles before consumption.

type SteeringRequest

type SteeringRequest struct {
	SessionID      string            `json:"session_id"`
	RunID          string            `json:"run_id"`
	Text           string            `json:"text"`
	Images         []ImageAttachment `json:"images,omitempty"`
	HideUserPrompt bool              `json:"-"`
}

SteeringRequest targets the active run identified by its initial user entry.

type StreamEvent

type StreamEvent struct {
	ToolCallEvent *ToolCallEvent    `json:"tool_call_event,omitempty"`
	ToolEvent     *ToolEvent        `json:"tool_event,omitempty"`
	Usage         *model.TokenUsage `json:"usage,omitempty"`
	Kind          StreamEventKind   `json:"kind"`
	Text          string            `json:"text,omitempty"`
}

StreamEvent is emitted during prompt execution before final persistence.

type StreamEventKind

type StreamEventKind string

StreamEventKind identifies incremental assistant activity.

const (
	// StreamEventTextDelta carries assistant text as it arrives.
	StreamEventTextDelta StreamEventKind = "text_delta"
	// StreamEventThinkingDelta carries model thinking/reasoning text as it arrives.
	StreamEventThinkingDelta StreamEventKind = "thinking_delta"
	// StreamEventToolStart announces a tool call before execution.
	StreamEventToolStart StreamEventKind = "tool_start"
	// StreamEventToolResult carries the completed tool call result.
	StreamEventToolResult StreamEventKind = "tool_result"
	// StreamEventSkillLoaded carries an explicitly loaded Agent Skill.
	StreamEventSkillLoaded StreamEventKind = "skill_loaded"
	// StreamEventUsage carries estimated or provider-reported token usage.
	StreamEventUsage StreamEventKind = "usage"
	// StreamEventUsageSnapshot carries a fresh full-context usage snapshot that should replace prior UI usage.
	StreamEventUsageSnapshot StreamEventKind = "usage_snapshot"
	// StreamEventUsageTotal carries cumulative provider-reported usage for one run.
	StreamEventUsageTotal StreamEventKind = "usage_total"
	// StreamEventSteeringConsumed reports that a steering message became durable.
	StreamEventSteeringConsumed StreamEventKind = "steering_consumed"
	// StreamEventContextCompaction carries UI-only context compaction notices.
	StreamEventContextCompaction StreamEventKind = "context_compaction"
	// StreamEventContextCompactionStart reports that context compaction has started.
	StreamEventContextCompactionStart StreamEventKind = "context_compaction_start"
	// StreamEventContextCompactionDone reports that context compaction completed.
	StreamEventContextCompactionDone StreamEventKind = "context_compaction_done"
	// StreamEventContextCompactionError reports that context compaction failed.
	StreamEventContextCompactionError StreamEventKind = "context_compaction_error"
	// StreamEventUnknown carries unexpected provider events without persistence side effects.
	StreamEventUnknown StreamEventKind = "unknown"
)

type ToolCall

type ToolCall struct {
	Metadata      map[string]any `json:"metadata,omitempty"`
	ArgumentsJSON string         `json:"arguments_json,omitempty"`
	ID            string         `json:"id"`
	Name          string         `json:"name"`
	Arguments     tool.Arguments `json:"arguments,omitzero"`
}

ToolCall is an assistant-local tool invocation requested by the model.

type ToolCallEvent

type ToolCallEvent struct {
	ArgumentsJSON string         `json:"arguments_json"`
	ID            string         `json:"id"`
	ParentCallID  string         `json:"parent_call_id,omitempty"`
	Name          string         `json:"name"`
	Arguments     tool.Arguments `json:"arguments,omitzero"`
	Sequence      int            `json:"sequence,omitempty"`
}

ToolCallEvent captures one requested tool call before execution.

type ToolEvent

type ToolEvent struct {
	CallID        string `json:"call_id,omitempty"`
	ParentCallID  string `json:"parent_call_id,omitempty"`
	Name          string `json:"name"`
	ArgumentsJSON string `json:"arguments_json"`
	DetailsJSON   string `json:"details_json,omitempty"`
	Result        string `json:"result"`
	Error         string `json:"error,omitempty"`
	Sequence      int    `json:"sequence,omitempty"`
	IsError       bool   `json:"is_error,omitempty"`
}

ToolEvent captures one tool call for persistence and TUI rendering.

func BackgroundToolCompletionEvent

func BackgroundToolCompletionEvent(completion *tooltask.Completion) ToolEvent

BackgroundToolCompletionEvent converts a canonical worker completion into the same result event used by foreground tools and provider streams.

type ToolExecutor

type ToolExecutor func(context.Context, []ToolCall, func(StreamEvent)) ([]ToolEvent, error)

ToolExecutor executes provider-requested tool calls through the assistant runtime.

type ToolStrategy

type ToolStrategy string

ToolStrategy controls which provider-facing tool surfaces are available.

const (
	// ToolStrategyHybrid exposes direct tools and the execute code-mode tool.
	ToolStrategyHybrid ToolStrategy = "hybrid"
	// ToolStrategyDirect exposes direct tools without execute.
	ToolStrategyDirect ToolStrategy = "direct"
)

type ToolTaskController

type ToolTaskController interface {
	Start(ctx context.Context, request *tooltask.StartRequest) (*database.ToolTaskEntity, error)
	Get(ctx context.Context, owner, taskID string) (*database.ToolTaskEntity, bool, error)
	List(
		ctx context.Context, owner string, states []database.TaskState, limit int,
	) ([]database.ToolTaskEntity, error)
	Cancel(ctx context.Context, owner, taskID string) (*database.ToolTaskEntity, bool, error)
	Wait(ctx context.Context, owner, taskID string) (*database.ToolTaskEntity, error)
}

ToolTaskController is the transport-neutral assistant boundary for durable tool work.

type WorkflowController

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

WorkflowController adapts the reusable agent submitter and task controller to the workflow runtime without weakening child-session ownership or policy snapshot semantics.

func NewWorkflowController

func NewWorkflowController(
	submitter *AgentSubmitter,
	tasks AgentTaskController,
	sessions *database.SessionRepository,
) (*WorkflowController, error)

NewWorkflowController creates the production workflow agent adapter.

func (*WorkflowController) Await

func (controller *WorkflowController) Await(
	ctx context.Context,
	taskID string,
) (*database.AgentTaskEntity, error)

Await waits for an agent task to reach a terminal state.

func (*WorkflowController) Cancel

func (controller *WorkflowController) Cancel(
	ctx context.Context,
	ownerSessionID string,
	taskID string,
	source string,
) (*database.TaskEntity, bool, error)

Cancel requests cancellation of a workflow-owned agent task.

func (*WorkflowController) Get

func (controller *WorkflowController) Get(
	ctx context.Context,
	taskID string,
) (*database.AgentTaskEntity, bool, error)

Get returns an agent task by ID.

func (*WorkflowController) List

func (controller *WorkflowController) List(
	ctx context.Context,
	ownerSessionID string,
	limit int,
) ([]database.AgentTaskEntity, error)

List returns agent tasks owned by a workflow session.

func (*WorkflowController) Submit

func (controller *WorkflowController) Submit(
	ctx context.Context,
	request *workflow.AgentRequest,
) (*database.AgentTaskEntity, error)

Submit resolves the owner's working directory and delegates child creation and policy capture to AgentSubmitter.

type WorkflowSubmitter

type WorkflowSubmitter interface {
	Submit(context.Context, *workflow.ServiceRequest) (*database.WorkflowRunEntity, error)
}

WorkflowSubmitter is the runtime-facing boundary for durable workflows.

Directories

Path Synopsis
Package lifecyclepayload builds extension-facing lifecycle event payloads.
Package lifecyclepayload builds extension-facing lifecycle event payloads.

Jump to

Keyboard shortcuts

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