Documentation
¶
Overview ¶
Package agentruntime contains front-end-neutral execution policy primitives.
Index ¶
- Constants
- func BuildRegistry(workDir string, sandboxMgr *sandbox.Manager, settings *config.Settings, ...) (*tools.Registry, error)
- func CloseMCPClients(clients []*mcp.Client)
- func CreateDurableRun(sessionDir string, run DurableRun) error
- func CreateSession(opts CreateSessionOptions) (*session.Manager, error)
- func DefaultPlanToolPolicy(settings *config.Settings) *bool
- func DeleteSession(sessionDir, id string) error
- func DeliveryPendingData(responseRunID, responseID, state, assistantEntryID string, ...) map[string]any
- func DisplayErrorMessage(info ErrorInfo) string
- func FinishDurableRun(sessionDir, runID string, state RunState, message string) error
- func IsValidMode(mode string) bool
- func NewAgentManager(opts AgentManagerOptions) (*agent.AgentManager, error)
- func NormalizeAdditionalDirectories(directories []string) ([]string, error)
- func OpenSession(sessionDir, id string) (*session.Manager, error)
- func OpenSessionForWorkDir(workDir, sessionDir, id string) (*session.Manager, error)
- func RecoverDurableRun(sessionDir string, run session.SessionRun, state RunState, message string, ...) error
- func ReopenDurableRun(sessionDir, runID string, state RunState, message string) error
- func ReplayDecisions(records []DecisionRecord) map[string]DecisionRecord
- func ReplayDecisionsAt(records []DecisionRecord, now time.Time) map[string]DecisionRecord
- func ReplayDeliveries(events []session.SessionRunEvent) map[string]DeliveryRecord
- func ReplayDeliveriesFromRunEvents(events []RunEvent) map[string]DeliveryRecord
- func ReplayRunEventsJSON(events []session.SessionRunEvent, runID string) ([]byte, error)
- func UpdateDurableRun(sessionDir, runID string, state RunState, message string) error
- func ValidateThinkingLevel(value string) (provider.ThinkingLevel, error)
- type AgentBuildOptions
- type AgentEventObservation
- type AgentManagerOptions
- type AttachedResources
- type BuildOptions
- type Builder
- type CommandRisk
- type ContextResources
- type CreateSessionOptions
- type DecisionKind
- type DecisionRecord
- func ExpiredDecisions(records []DecisionRecord, now time.Time) []DecisionRecord
- func NewDecisionRequestRecord(request DecisionRequest, payload any) (DecisionRecord, error)
- func NewDecisionRequestRecordWithDeadline(request DecisionRequest, payload any, expiresAt time.Time) (DecisionRecord, error)
- func NewDecisionResolutionRecord(request DecisionRequest, resolution DecisionResolution, payload any) (DecisionRecord, error)
- type DecisionRequest
- type DecisionResolution
- type DecisionService
- func (s *DecisionService) Bind(id string, resolve func(string) error) error
- func (s *DecisionService) ClearRun(runID string) []DecisionRequest
- func (s *DecisionService) ClearRunWithValue(runID, value string) []DecisionRequest
- func (s *DecisionService) Pending() []DecisionRequest
- func (s *DecisionService) Register(request DecisionRequest) error
- func (s *DecisionService) Rehydrate(records []DecisionRecord) ([]DecisionRequest, error)
- func (s *DecisionService) Resolve(resolution DecisionResolution) (DecisionRequest, error)
- func (s *DecisionService) ResolveWith(resolution DecisionResolution, commit func(DecisionRequest) error) (DecisionRequest, error)
- type DeliveryRecord
- type DurableConversationTurnEventFinisher
- type DurableConversationTurnFinisher
- type DurableConversationTurnStore
- type DurableIntentEventStore
- type DurableIntentStore
- type DurableRun
- type DurableRunEventStore
- type DurableRunMetadataStore
- type DurableRunStore
- type DurableRunUsageStore
- type ErrorClassificationOptions
- type ErrorInfo
- type ExecutionIntent
- type ExecutionPolicy
- type ExecutionRuntime
- func (r *ExecutionRuntime) Active() (string, bool)
- func (r *ExecutionRuntime) Begin(parent context.Context, runID string) (context.Context, error)
- func (r *ExecutionRuntime) BeginDurable(parent context.Context, run DurableRun, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) BeginIntentDurable(parent context.Context, intent ExecutionIntent, run DurableRun, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) BeginRetryDurable(parent context.Context, run DurableRun, event RunEvent) (*ExecutionIntent, context.Context, error)
- func (r *ExecutionRuntime) BeginWithEvent(parent context.Context, runID string, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) Cancel() bool
- func (r *ExecutionRuntime) CancelDurable(message string) (bool, error)
- func (r *ExecutionRuntime) Finish(runID string)
- func (r *ExecutionRuntime) FinishDurable(runID string, state RunState, message string, event RunEvent) error
- func (r *ExecutionRuntime) FinishWithEvent(runID string, state RunState, event RunEvent) error
- func (r *ExecutionRuntime) FinishWithState(runID string, state RunState) error
- func (r *ExecutionRuntime) ObserveAgentEvent(ev agent.Event) (AgentEventObservation, error)
- func (r *ExecutionRuntime) ReattachDurable(parent context.Context, runID string, state RunState) (context.Context, error)
- func (r *ExecutionRuntime) ReattachDurableRun(parent context.Context, run DurableRun, state RunState, startEvent RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) RecordErrorInfo(info ErrorInfo) (ErrorInfo, error)
- func (r *ExecutionRuntime) RecordEvent(ev RunEvent) (string, error)
- func (r *ExecutionRuntime) RecordFailure(err error, opts ErrorClassificationOptions) (ErrorInfo, error)
- func (r *ExecutionRuntime) RecordUsage(runID string, usage, contextUsage json.RawMessage) error
- func (r *ExecutionRuntime) Resume(runID string) error
- func (r *ExecutionRuntime) SetAgent(a interface{ ... })
- func (r *ExecutionRuntime) SetEventSink(sink RunEventSink)
- func (r *ExecutionRuntime) SetRunStore(store DurableRunStore)
- func (r *ExecutionRuntime) Shutdown(message string) error
- func (r *ExecutionRuntime) ShutdownContext(ctx context.Context, message string) error
- func (r *ExecutionRuntime) State() RunState
- func (r *ExecutionRuntime) UpdateDurable(runID string, state RunState, message string) error
- func (r *ExecutionRuntime) Wait(ctx context.Context) error
- func (r *ExecutionRuntime) WaitForApproval(runID string) error
- func (r *ExecutionRuntime) WaitForQuestion(runID string) error
- type FailureClass
- type ForkOptions
- type ForkResult
- type MCPPolicy
- type ModeResolver
- type Policy
- type RecoveryAction
- type RefreshOptions
- type RegistryHook
- type RegistryMutator
- type RegistryPolicy
- type RetryInfo
- type RetryMode
- type RunEvent
- type RunEventProjector
- type RunEventSink
- type RunEventSinkFunc
- type RunPhase
- type RunRecoveryPolicy
- type RunRecoveryResult
- type RunReplay
- type RunState
- type RunStore
- func (s RunStore) Create(run DurableRun) error
- func (s RunStore) CreateIntentAndRun(intent ExecutionIntent, run DurableRun) error
- func (s RunStore) CreateIntentAndRunWithEvent(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateIntentAndRunWithEventAndTurn(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateRunWithEvent(run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateRunWithEventAndTurn(run DurableRun, event RunEvent) (string, error)
- func (s RunStore) Finish(runID string, state RunState, message string) error
- func (s RunStore) FinishConversationTurn(run DurableRun, state RunState, message string) error
- func (s RunStore) FinishRunAndConversationTurn(run DurableRun, state RunState, message string, event RunEvent) (string, error)
- func (s RunStore) GetIntent(intentID string) (*ExecutionIntent, error)
- func (s RunStore) LeaseLost(sessionID string) <-chan struct{}
- func (s RunStore) Reopen(runID string, state RunState, message string) error
- func (s RunStore) Update(runID string, state RunState, message string) error
- func (s RunStore) UpdateErrorInfo(runID string, info ErrorInfo) error
- func (s RunStore) UpdateProgress(runID string, progress RetryInfo) error
- func (s RunStore) UpdateUsage(runID string, usage, contextUsage json.RawMessage) error
- type RuntimeSource
- type SessionConfigOption
- type SessionConfigOptionChoice
- type SessionModelBinding
- type SessionRunEventSink
- type SessionRuntime
- func (r *SessionRuntime) AdditionalDirectoriesSnapshot() []string
- func (r *SessionRuntime) ApplyRegistryHooks(hooks []RegistryHook) error
- func (r *SessionRuntime) BindSession(manager *session.Manager, requested RuntimeSource) error
- func (r *SessionRuntime) BuildAgent(opts AgentBuildOptions) (*agent.Agent, error)
- func (r *SessionRuntime) BuildTransientAgent(registry *tools.Registry, opts AgentBuildOptions) (*agent.Agent, error)
- func (r *SessionRuntime) Close()
- func (r *SessionRuntime) ConfigOptions() []SessionConfigOption
- func (r *SessionRuntime) ConfigSnapshot() (provider.Provider, string, *provider.Model, string, provider.ThinkingLevel)
- func (r *SessionRuntime) ConfigureSession(p provider.Provider, providerName string, model *provider.Model, mode string, ...) error
- func (r *SessionRuntime) ConnectConfiguredMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) ConnectMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) RefreshResources(settings *config.Settings, opts RefreshOptions) error
- func (r *SessionRuntime) ReloadAdditionalDirectories(manager *session.Manager) error
- func (r *SessionRuntime) ResolvePolicy(sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
- func (r *SessionRuntime) SetAdditionalDirectories(directories []string) error
- func (r *SessionRuntime) SetConfigOption(id, value string) error
- func (r *SessionRuntime) SetDecisions(decisions *DecisionService)
- func (r *SessionRuntime) SetExecution(execution *ExecutionRuntime)
- func (r *SessionRuntime) Shutdown(ctx context.Context) error
- func (r *SessionRuntime) SynchronizeCoreTools(browserEnabled bool)
- func (r *SessionRuntime) UnbindSession() error
- type SideEffectState
- type Source
- type SourceConflictError
- type SourceResolution
- func ResolvePolicy(input SourceResolutionInput, sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
- func ResolvePolicyFromSession(sessionDir, sessionID string, input SourceResolutionInput, ...) (SourceResolution, string, error)
- func ResolveSource(input SourceResolutionInput) SourceResolution
- func ResolveSourceFromSession(sessionDir, sessionID string, input SourceResolutionInput) (SourceResolution, error)
- type SourceResolutionInput
- type ToolCallPolicyDecision
Constants ¶
const ( ModePlan = "plan" ModeAgent = "agent" ModeYolo = "yolo" ModeOS = "os" )
const ( ConfigOptionModel = "model" ConfigOptionMode = "mode" ConfigOptionThinkingLevel = "thinking_level" )
SessionConfigOption IDs are stable protocol-neutral identifiers.
Variables ¶
This section is empty.
Functions ¶
func BuildRegistry ¶
func BuildRegistry(workDir string, sandboxMgr *sandbox.Manager, settings *config.Settings, policy RegistryPolicy) (*tools.Registry, error)
BuildRegistry creates the base registry and applies explicit adapter tool policy. It is the only registry construction API for non-test adapters.
func CloseMCPClients ¶
CloseMCPClients releases clients held by legacy adapter aliases during migration.
func CreateDurableRun ¶
func CreateDurableRun(sessionDir string, run DurableRun) error
CreateDurableRun is the Runtime-owned entry point for callers that need to create a canonical row before an in-memory ExecutionRuntime is available. Normal Agent executions should use ExecutionRuntime.BeginDurable.
func CreateSession ¶
func CreateSession(opts CreateSessionOptions) (*session.Manager, error)
CreateSession initializes a persisted local or bound channel session.
func DefaultPlanToolPolicy ¶
DefaultPlanToolPolicy returns the configured plan-tool setting.
func DeleteSession ¶
DeleteSession removes a persisted session by ID when it is not active.
func DeliveryPendingData ¶
func DeliveryPendingData(responseRunID, responseID, state, assistantEntryID string, extra map[string]any) map[string]any
DeliveryPendingData returns the compatibility payload used by existing channel recovery while keeping delivery semantics at the Runtime boundary.
func DisplayErrorMessage ¶ added in v1.2.88
DisplayErrorMessage returns a truthful, concise message for adapters. It keeps an explicit category message when present, but never drops the provider detail that explains what actually failed.
func FinishDurableRun ¶
FinishDurableRun applies a Runtime-owned terminal transition when no live ExecutionRuntime can be reattached. It remains monotonic and idempotent.
func IsValidMode ¶
IsValidMode reports whether mode is one of the public execution modes.
func NewAgentManager ¶
func NewAgentManager(opts AgentManagerOptions) (*agent.AgentManager, error)
NewAgentManager constructs an AgentFactory and AgentManager using the shared runtime's sandbox, context, rules and skills. All entry points should use this path instead of assembling AgentFactory arguments independently.
func NormalizeAdditionalDirectories ¶ added in v1.2.90
NormalizeAdditionalDirectories validates the ACP directory-root contract: absolute, cleaned, deterministic and duplicate-free paths.
func OpenSession ¶
OpenSession opens a persisted session by exact ID regardless of its workdir.
func OpenSessionForWorkDir ¶
OpenSessionForWorkDir opens a persisted session scoped to its working directory.
func RecoverDurableRun ¶
func RecoverDurableRun(sessionDir string, run session.SessionRun, state RunState, message string, event RunEvent) error
RecoverDurableRun terminalizes a local orphan and records the corresponding Runtime recovery event as one shared operation. The caller may perform adapter-specific decision cleanup before invoking it.
func ReopenDurableRun ¶
ReopenDurableRun is the explicit recovery-only terminal-to-active transition.
func ReplayDecisions ¶
func ReplayDecisions(records []DecisionRecord) map[string]DecisionRecord
ReplayDecisions reconstructs the latest pending decision set from durable request/resolution records. It is intentionally protocol-neutral; adapters remain responsible for decoding their payload fields.
func ReplayDecisionsAt ¶
func ReplayDecisionsAt(records []DecisionRecord, now time.Time) map[string]DecisionRecord
ReplayDecisionsAt reconstructs pending decisions at a stable clock instant. Expired records are omitted so callers can terminalize them durably.
func ReplayDeliveries ¶
func ReplayDeliveries(events []session.SessionRunEvent) map[string]DeliveryRecord
ReplayDeliveries reconstructs pending channel/background deliveries from durable run events. Unknown events and protocol payloads remain untouched.
func ReplayDeliveriesFromRunEvents ¶
func ReplayDeliveriesFromRunEvents(events []RunEvent) map[string]DeliveryRecord
func ReplayRunEventsJSON ¶
func ReplayRunEventsJSON(events []session.SessionRunEvent, runID string) ([]byte, error)
ReplayRunEventsJSON provides a stable JSON projection for adapters that need to pass durable replay data across an API boundary.
func UpdateDurableRun ¶
UpdateDurableRun applies a canonical non-terminal transition for a recovered or externally-owned run. Active Agent loops should use UpdateDurable.
func ValidateThinkingLevel ¶ added in v1.2.90
func ValidateThinkingLevel(value string) (provider.ThinkingLevel, error)
ValidateThinkingLevel validates a config option value without making provider-specific assumptions.
Types ¶
type AgentBuildOptions ¶
type AgentBuildOptions struct {
ID agentpkg.AgentID
ParentID agentpkg.AgentID
Provider provider.Provider
ProviderName string
Model *provider.Model
Settings *config.Settings
Allow *config.AllowConfig
Mode string
ToolExecutionMode string
MaxToolConcurrency int
ExtraContext string
RuleContent string
ThinkingLevel provider.ThinkingLevel
MaxTokens int
MaxTokensSet bool
MultiAgent bool
DelegateMode bool
Workflows bool
ApprovalHandler func(string, string, map[string]any) bool
ApprovalDecisionLookup func(string, string, map[string]any) (bool, bool)
MaxIterations int
ContextPressure float64
BudgetPressure float64
BeforeToolCall func(agent.BeforeToolCallContext) *agent.ToolCallBlockResult
AfterToolCall func(agent.AfterToolCallContext) *agent.ToolCallResult
GetSteeringMessages func() []provider.Message
ConversationTurnID string
IntentID string
RunID string
ConversationTurn bool
RuntimeOwnsTurnEnd bool
}
AgentBuildOptions are per-run inputs supplied by an adapter after Runtime has resolved its source, policy, session resources, and effective mode.
func AgentBuildOptionsFromConfig ¶
func AgentBuildOptionsFromConfig(cfg agent.Config) AgentBuildOptions
AgentBuildOptionsFromConfig converts the legacy Agent.Config shape used by provider-specific drivers into Runtime-owned build inputs.
type AgentEventObservation ¶
AgentEventObservation is the adapter-neutral result of consuming an Agent Core event. The adapter may render it in its protocol, but must not infer retry safety or terminal error semantics from presentation text.
type AgentManagerOptions ¶
type AgentManagerOptions struct {
Runtime *SessionRuntime
Provider provider.Provider
Model *provider.Model
Settings *config.Settings
ProviderName string
Allow *config.AllowConfig
MultiAgentEnabled bool
DelegateEnabled bool
WorkflowsEnabled bool
}
AgentManagerOptions binds provider-specific execution dependencies to a shared SessionRuntime. Adapter-specific event and approval handling remains outside this type.
type AttachedResources ¶
type AttachedResources struct {
ID string
Source RuntimeSource
EntrySource RuntimeSource
WorkDir string
Manager *session.Manager
Registry *tools.Registry
SandboxMgr *sandbox.Manager
SkillsMgr *skills.Manager
MCPClients []*mcp.Client
ExtraContext string
RuleContent string
AdditionalDirectories []string
}
AttachedResources are adapter-policy-selected resources attached to the common runtime. Use this only when protocol-specific registry or MCP policy cannot yet be represented by Builder; Runtime retains all lifecycle ownership.
type BuildOptions ¶
type BuildOptions struct {
ID string
Source RuntimeSource
WorkDir string
Manager *session.Manager
Workflows bool
Browser bool
RegistryHooks []RegistryHook
}
BuildOptions are the resource-affecting session capabilities. They are kept separate from adapter-specific presentation and approval options.
type Builder ¶
func (Builder) Build ¶
func (b Builder) Build(ctx context.Context, opts BuildOptions) (*SessionRuntime, error)
Build constructs context, skills, sandbox, tools and MCP connections for one session. The caller owns the returned runtime and must call Close on failures after successful construction or when the session is evicted.
type CommandRisk ¶
type CommandRisk string
CommandRisk is the unattended-execution risk assigned to a bash command.
const ( CommandRiskLow CommandRisk = "low" CommandRiskMedium CommandRisk = "medium" CommandRiskHigh CommandRisk = "high" )
func ClassifyBashCommand ¶
func ClassifyBashCommand(command string) CommandRisk
ClassifyBashCommand classifies command risk for unattended execution. High risk detection tokenizes shell control operators and executable paths so quoting, compound commands, and common flag variants cannot bypass it.
type ContextResources ¶
ContextResources are the shared context/skill inputs used by a session runtime.
func LoadContextResources ¶
func LoadContextResources(settings *config.Settings, workDir string, workflows, browserEnabled bool) (*ContextResources, error)
LoadContextResources loads context files, project/global skills, and rules. It is shared by all adapters; adapters choose only the requested capabilities.
type CreateSessionOptions ¶
type CreateSessionOptions struct {
WorkDir string
SessionDir string
ID string
ChannelType string
ChannelID string
}
CreateSessionOptions describes persisted session identity without coupling it to a front-end protocol. Channel binding remains adapter policy input.
type DecisionKind ¶
type DecisionKind string
DecisionKind identifies an interactive decision that can pause a run.
const ( DecisionApproval DecisionKind = "approval" DecisionQuestion DecisionKind = "question" )
type DecisionRecord ¶
type DecisionRecord struct {
ID string `json:"id"`
SessionID string `json:"sessionId"`
RunID string `json:"runId"`
Kind DecisionKind `json:"kind"`
Status string `json:"status"`
Value string `json:"value,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
DecisionRecord is the protocol-neutral durable projection of a pending or resolved Approval/Question. Adapters may persist their legacy payload beside this record while migrating; the record itself must not contain agent/runtime pointers or protocol-specific response channels.
func ExpiredDecisions ¶
func ExpiredDecisions(records []DecisionRecord, now time.Time) []DecisionRecord
func NewDecisionRequestRecord ¶
func NewDecisionRequestRecord(request DecisionRequest, payload any) (DecisionRecord, error)
func NewDecisionRequestRecordWithDeadline ¶
func NewDecisionRequestRecordWithDeadline(request DecisionRequest, payload any, expiresAt time.Time) (DecisionRecord, error)
func NewDecisionResolutionRecord ¶
func NewDecisionResolutionRecord(request DecisionRequest, resolution DecisionResolution, payload any) (DecisionRecord, error)
type DecisionRequest ¶
type DecisionRequest struct {
ID string
RunID string
SessionID string
Kind DecisionKind
Resolve func(string) error
}
DecisionRequest is the adapter-neutral identity of a pending decision.
type DecisionResolution ¶
type DecisionResolution struct {
ID string
Kind DecisionKind
Status string
Value string
}
DecisionResolution is the adapter-neutral result of resolving a decision.
type DecisionService ¶
type DecisionService struct {
// contains filtered or unexported fields
}
DecisionService owns pending decision identity and first-response-wins semantics. Protocol-specific payloads and rendering remain in adapters.
func (*DecisionService) Bind ¶
func (s *DecisionService) Bind(id string, resolve func(string) error) error
Bind associates an adapter-owned resume callback with a registered decision. The callback must succeed before Resolve consumes the pending decision.
func (*DecisionService) ClearRun ¶
func (s *DecisionService) ClearRun(runID string) []DecisionRequest
func (*DecisionService) ClearRunWithValue ¶
func (s *DecisionService) ClearRunWithValue(runID, value string) []DecisionRequest
ClearRunWithValue removes all decisions for a Run and invokes their resolver callbacks with the supplied value. It is used for cancellation and timeout paths where no protocol resolution is available.
func (*DecisionService) Pending ¶
func (s *DecisionService) Pending() []DecisionRequest
func (*DecisionService) Register ¶
func (s *DecisionService) Register(request DecisionRequest) error
func (*DecisionService) Rehydrate ¶
func (s *DecisionService) Rehydrate(records []DecisionRecord) ([]DecisionRequest, error)
Rehydrate restores the latest pending durable decisions without binding protocol callbacks. Adapters may bind callbacks after reconnect/restore. Rehydration is idempotent for an already identical pending decision.
func (*DecisionService) Resolve ¶
func (s *DecisionService) Resolve(resolution DecisionResolution) (DecisionRequest, error)
func (*DecisionService) ResolveWith ¶
func (s *DecisionService) ResolveWith(resolution DecisionResolution, commit func(DecisionRequest) error) (DecisionRequest, error)
ResolveWith performs the adapter persistence commit before consuming the pending request. A callback or commit failure leaves the request retryable.
type DeliveryRecord ¶
type DeliveryRecord struct {
RunID string
SessionID string
Pending bool
AssistantEntry string
Status string
Source string
}
DeliveryRecord is the protocol-neutral projection of a durable delivery handoff. The actual message remains in the session transcript.
type DurableConversationTurnEventFinisher ¶ added in v1.2.92
type DurableConversationTurnFinisher ¶ added in v1.2.92
type DurableConversationTurnFinisher interface {
FinishConversationTurn(DurableRun, RunState, string) error
}
type DurableConversationTurnStore ¶ added in v1.2.92
type DurableConversationTurnStore interface {
CreateIntentAndRunWithEventAndTurn(ExecutionIntent, DurableRun, RunEvent) (string, error)
CreateRunWithEventAndTurn(DurableRun, RunEvent) (string, error)
}
DurableConversationTurnStore extends atomic Run admission for executions that append a user/assistant transcript. Non-conversation maintenance Runs continue to use the smaller interfaces above.
type DurableIntentEventStore ¶
type DurableIntentEventStore interface {
DurableIntentStore
CreateIntentAndRunWithEvent(ExecutionIntent, DurableRun, RunEvent) (string, error)
}
DurableIntentEventStore extends intent admission with an atomic started event. Stores that implement it prevent a process loss between the Run row and its first replay anchor.
type DurableIntentStore ¶
type DurableIntentStore interface {
CreateIntentAndRun(ExecutionIntent, DurableRun) error
GetIntent(string) (*ExecutionIntent, error)
}
DurableIntentStore is the Runtime-owned persistence boundary for an accepted original request. Adapters keep their request decoding private but must not create a second intent store or lifecycle chain.
type DurableRun ¶
type DurableRun struct {
ID string
SessionID string
IntentID string
RetryOf string
Attempt int
WorkDir string
Source string
Model string
Mode string
Status string
StartedAt time.Time
FinishedAt *time.Time
Error string
ErrorInfo ErrorInfo
Progress RetryInfo
Usage json.RawMessage
ContextUsage json.RawMessage
ConversationTurnID string
ConversationTurn bool
}
DurableRun is the adapter-neutral lifecycle row for one execution.
type DurableRunEventStore ¶
type DurableRunEventStore interface {
CreateRunWithEvent(DurableRun, RunEvent) (string, error)
}
DurableRunEventStore atomically admits a linked Run and its initial event. It is separate from DurableIntentEventStore because retries reuse an immutable intent that already exists.
type DurableRunMetadataStore ¶
type DurableRunMetadataStore interface {
UpdateErrorInfo(string, ErrorInfo) error
UpdateProgress(string, RetryInfo) error
}
DurableRunMetadataStore is an optional extension implemented by stores that persist structured recovery state. Keeping it optional preserves test and embedded adapters that only need lifecycle rows.
type DurableRunStore ¶
type DurableRunStore interface {
Create(DurableRun) error
Update(string, RunState, string) error
Finish(string, RunState, string) error
}
DurableRunStore is the persistence boundary used by ExecutionRuntime to coordinate canonical run rows with in-memory lifecycle transitions.
type DurableRunUsageStore ¶
type DurableRunUsageStore interface {
UpdateUsage(string, json.RawMessage, json.RawMessage) error
}
DurableRunUsageStore is an optional metadata extension for providers that expose token/context usage before terminalization. Keeping it separate from DurableRunMetadataStore preserves embedded stores that predate usage rows.
type ErrorClassificationOptions ¶
type ErrorClassificationOptions struct {
Code string
Type string
Phase RunPhase
Message string
Detail string
MessageKey string
HTTPStatus int
RetryAfterMS int
Attempt int
MaxAttempts int
SideEffectState SideEffectState
PartialOutput bool
RunID string
IntentID string
RequestID string
}
ErrorClassificationOptions adds execution facts that cannot be derived from an error value alone. The defaults are intentionally safe for callers that have not observed tools or output yet.
type ErrorInfo ¶
type ErrorInfo struct {
Code string `json:"code,omitempty"`
Type string `json:"type,omitempty"`
FailureClass FailureClass `json:"failureClass,omitempty"`
Phase RunPhase `json:"phase,omitempty"`
MessageKey string `json:"messageKey,omitempty"`
Message string `json:"message,omitempty"`
Detail string `json:"detail,omitempty"`
RetryMode RetryMode `json:"retryMode,omitempty"`
Retryable bool `json:"retryable,omitempty"`
RetryAfterMS int `json:"retryAfterMs,omitempty"`
Attempt int `json:"attempt,omitempty"`
MaxAttempts int `json:"maxAttempts,omitempty"`
SideEffectState SideEffectState `json:"sideEffectState,omitempty"`
PartialOutput bool `json:"partialOutput,omitempty"`
RunID string `json:"runId,omitempty"`
IntentID string `json:"intentId,omitempty"`
RequestID string `json:"requestId,omitempty"`
}
ErrorInfo is the durable, adapter-neutral description of an execution failure. Message is the user-facing description and Detail preserves the provider diagnostic that caused it. Detail is bounded and redacted before persistence so failures remain useful without turning session history into a credentials sink.
func ClassifyError ¶
func ClassifyError(err error, opts ErrorClassificationOptions) ErrorInfo
ClassifyError converts a raw failure into the shared durable contract. It intentionally has no adapter/UI dependencies, and only marks automatic retries safe before output or side effects exist.
type ExecutionIntent ¶
type ExecutionIntent = session.ExecutionIntent
ExecutionIntent is the durable, adapter-neutral accepted request. The request and policy snapshots remain opaque at this boundary; their owner rehydrates them only through the shared Runtime execution path.
type ExecutionPolicy ¶
type ExecutionPolicy struct {
Source RuntimeSource
DefaultMode string
}
ExecutionPolicy describes the mode semantics shared by all adapters for one run.
func PolicyForSource ¶
func PolicyForSource(source RuntimeSource, defaultMode string) ExecutionPolicy
PolicyForSource returns the default mode policy associated with a resolved source. Channel sources retain their forced yolo invariant.
func (ExecutionPolicy) EvaluateToolCall ¶
func (p ExecutionPolicy) EvaluateToolCall(toolName string, args map[string]any) ToolCallPolicyDecision
EvaluateToolCall applies non-overridable source policy before approval. A forced mode controls agent behavior only; it never disables this guard.
type ExecutionRuntime ¶
type ExecutionRuntime struct {
// contains filtered or unexported fields
}
ExecutionRuntime owns the adapter-neutral active run state for one session. When configured with a DurableRunStore and RunEventSink it also owns the canonical durable transitions; adapters provide those storage implementations plus protocol event projection and any compatibility admission lock.
func (*ExecutionRuntime) Active ¶
func (r *ExecutionRuntime) Active() (string, bool)
Active reports the current run ID and whether a run is active.
func (*ExecutionRuntime) Begin ¶
Begin starts one exclusive execution. The caller must finish the run exactly once, including when agent construction fails.
func (*ExecutionRuntime) BeginDurable ¶
func (r *ExecutionRuntime) BeginDurable(parent context.Context, run DurableRun, event RunEvent) (context.Context, error)
BeginDurable starts an exclusive in-memory execution, creates its canonical durable run row, and records the initial event. Failures are compensated so a partially-started run is not left active or persisted as running.
func (*ExecutionRuntime) BeginIntentDurable ¶
func (r *ExecutionRuntime) BeginIntentDurable(parent context.Context, intent ExecutionIntent, run DurableRun, event RunEvent) (context.Context, error)
BeginIntentDurable atomically admits the immutable original request and its first durable Run. A user-initiated retry must use BeginRetryDurable instead, which creates a linked Run without mutating the accepted intent.
func (*ExecutionRuntime) BeginRetryDurable ¶
func (r *ExecutionRuntime) BeginRetryDurable(parent context.Context, run DurableRun, event RunEvent) (*ExecutionIntent, context.Context, error)
BeginRetryDurable creates a new linked attempt for an existing immutable execution intent. It never reopens a terminal Run, preserving the attempt chain for all adapters and after process restart.
func (*ExecutionRuntime) BeginWithEvent ¶
func (r *ExecutionRuntime) BeginWithEvent(parent context.Context, runID string, event RunEvent) (context.Context, error)
BeginWithEvent starts a run and records its initial durable event through the configured sink. Event persistence remains best-effort for adapters that do not attach a sink; a configured sink error is returned to the caller.
func (*ExecutionRuntime) Cancel ¶
func (r *ExecutionRuntime) Cancel() bool
Cancel requests context cancellation and aborts the core agent if present.
func (*ExecutionRuntime) CancelDurable ¶
func (r *ExecutionRuntime) CancelDurable(message string) (bool, error)
CancelDurable requests cancellation and persists the canonical cancelling state. Final terminalization remains the responsibility of FinishDurable.
func (*ExecutionRuntime) Finish ¶
func (r *ExecutionRuntime) Finish(runID string)
Finish transitions the active run to completed. Callers that know the run failed, was cancelled, or timed out must use FinishWithState.
func (*ExecutionRuntime) FinishDurable ¶
func (r *ExecutionRuntime) FinishDurable(runID string, state RunState, message string, event RunEvent) error
FinishDurable performs one canonical terminal transition, records its final event, and updates the durable run row. Persistence happens before releasing in-memory ownership so failed writes remain retryable and concurrent finishers cannot emit duplicate terminal events.
func (*ExecutionRuntime) FinishWithEvent ¶
func (r *ExecutionRuntime) FinishWithEvent(runID string, state RunState, event RunEvent) error
FinishWithEvent transitions a run to a terminal state and records its final durable event. The event is written only after the state transition succeeds.
func (*ExecutionRuntime) FinishWithState ¶
func (r *ExecutionRuntime) FinishWithState(runID string, state RunState) error
FinishWithState transitions the active run to an explicit terminal state.
func (*ExecutionRuntime) ObserveAgentEvent ¶
func (r *ExecutionRuntime) ObserveAgentEvent(ev agent.Event) (AgentEventObservation, error)
ObserveAgentEvent normalizes the Agent Core event stream into the shared execution contract. It tracks output and tool facts, persists retry progress for reconnecting adapters, and returns structured terminal errors. It does not terminalize the Run: that remains the caller's single FinishDurable path.
func (*ExecutionRuntime) ReattachDurable ¶
func (r *ExecutionRuntime) ReattachDurable(parent context.Context, runID string, state RunState) (context.Context, error)
ReattachDurable restores in-memory ownership of an already persisted, non-terminal Run without creating a duplicate canonical row.
func (*ExecutionRuntime) ReattachDurableRun ¶
func (r *ExecutionRuntime) ReattachDurableRun(parent context.Context, run DurableRun, state RunState, startEvent RunEvent) (context.Context, error)
ReattachDurableRun restores an existing row with its full identity. The metadata is required so a later shutdown or FinishWithState can emit a valid terminal event without relying on adapter-local fallbacks.
func (*ExecutionRuntime) RecordErrorInfo ¶
func (r *ExecutionRuntime) RecordErrorInfo(info ErrorInfo) (ErrorInfo, error)
RecordErrorInfo records a previously classified, safe failure. It supports remote/background paths that fail outside an Agent event stream while keeping durable error state and terminal-event facts Runtime-owned.
func (*ExecutionRuntime) RecordEvent ¶
func (r *ExecutionRuntime) RecordEvent(ev RunEvent) (string, error)
func (*ExecutionRuntime) RecordFailure ¶
func (r *ExecutionRuntime) RecordFailure(err error, opts ErrorClassificationOptions) (ErrorInfo, error)
RecordFailure records a failure that happened before an Agent event stream existed, such as shared resource or Agent construction. It uses the same durable error contract as ObserveAgentEvent so adapters never need a second error classifier for preflight failures.
func (*ExecutionRuntime) RecordUsage ¶
func (r *ExecutionRuntime) RecordUsage(runID string, usage, contextUsage json.RawMessage) error
RecordUsage persists the latest provider and context-window usage for the active Run. Usage is durable metadata, not a terminal-event-only projection, so reconnects and recovery can inspect it before terminalization.
func (*ExecutionRuntime) Resume ¶
func (r *ExecutionRuntime) Resume(runID string) error
Resume returns a run from an approval or question wait to active execution.
func (*ExecutionRuntime) SetAgent ¶
func (r *ExecutionRuntime) SetAgent(a interface{ Abort() })
SetAgent associates the core agent so cancellation can unblock agent waits.
func (*ExecutionRuntime) SetEventSink ¶
func (r *ExecutionRuntime) SetEventSink(sink RunEventSink)
SetEventSink attaches the durable event sink used by adapter-neutral run lifecycle helpers. It does not emit an event by itself.
func (*ExecutionRuntime) SetRunStore ¶
func (r *ExecutionRuntime) SetRunStore(store DurableRunStore)
SetRunStore attaches the canonical durable run store used by lifecycle helpers. Adapters should configure it once when assembling a session runtime.
func (*ExecutionRuntime) Shutdown ¶
func (r *ExecutionRuntime) Shutdown(message string) error
Shutdown requests cancellation and waits for the active execution to terminalize. If an Agent loop is bound, cancellation only requests termination; the owner of that loop must perform the terminal transition. Executions without a bound Agent are terminalized synchronously, which covers runs restored for process cleanup before their adapter loop exists.
func (*ExecutionRuntime) ShutdownContext ¶
func (r *ExecutionRuntime) ShutdownContext(ctx context.Context, message string) error
ShutdownContext is the context-bounded form of Shutdown. It is the boundary SessionRuntime uses before releasing MCP and other shared resources.
func (*ExecutionRuntime) State ¶
func (r *ExecutionRuntime) State() RunState
State reports the current run state. It returns the last terminal state when idle after a run has finished, and an empty state for a zero-value runtime.
func (*ExecutionRuntime) UpdateDurable ¶
func (r *ExecutionRuntime) UpdateDurable(runID string, state RunState, message string) error
UpdateDurable persists a non-terminal state for the active canonical run.
func (*ExecutionRuntime) Wait ¶
func (r *ExecutionRuntime) Wait(ctx context.Context) error
Wait waits for the active execution to reach a terminal state.
func (*ExecutionRuntime) WaitForApproval ¶
func (r *ExecutionRuntime) WaitForApproval(runID string) error
WaitForApproval transitions an active run into an approval wait.
func (*ExecutionRuntime) WaitForQuestion ¶
func (r *ExecutionRuntime) WaitForQuestion(runID string) error
WaitForQuestion transitions an active run into a question wait.
type FailureClass ¶
type FailureClass string
FailureClass identifies the stable, adapter-neutral category of a failed execution. Adapters render it differently, but must not infer it from an English provider error string.
const ( FailureValidation FailureClass = "validation" FailurePolicy FailureClass = "policy" FailureTransient FailureClass = "transient" FailureProvider FailureClass = "provider" FailureTool FailureClass = "tool" FailureTransport FailureClass = "transport" FailureCancelled FailureClass = "canceled" FailureIncomplete FailureClass = "incomplete" FailurePersistence FailureClass = "persistence" FailureInternal FailureClass = "internal" )
type ForkOptions ¶ added in v1.2.92
type ForkOptions = session.ForkOptions
ForkOptions is the front-end-neutral request for a Session prefix fork. RequestID is mandatory so retries can reconcile the original child.
type ForkResult ¶ added in v1.2.92
type ForkResult = session.ForkResult
func Fork ¶ added in v1.2.92
func Fork(ctx context.Context, sessionDir string, options ForkOptions) (ForkResult, error)
Fork performs the canonical Session fork operation. The data layer owns the SQLite snapshot/copy transaction; this Runtime boundary keeps adapters from implementing their own copy or Agent lifecycle.
type MCPPolicy ¶
type MCPPolicy struct {
Servers []mcp.ServerConfig
Callbacks mcp.Callbacks
Optional bool
OnError func(error)
}
MCPPolicy describes adapter-specific MCP transport behavior while Runtime owns client connection and release.
type ModeResolver ¶
type ModeResolver struct {
Policy ExecutionPolicy
}
ModeResolver applies an execution policy consistently at every adapter boundary.
type Policy ¶
type Policy = ExecutionPolicy
Policy is retained as a concise compatibility alias for ExecutionPolicy.
func (Policy) ForcedMode ¶
ForcedMode returns the source-mandated mode, if any.
func (Policy) HasForcedMode ¶
HasForcedMode reports whether a source has a non-overridable execution mode.
func (Policy) ResolveMode ¶
ResolveMode returns the one effective mode for UI display, agent construction, run records, approvals, and recovery. Bound WeChat and Feishu sessions always execute in yolo mode; a request or persisted capability cannot downgrade them.
type RecoveryAction ¶
type RecoveryAction string
const ( RecoveryFailLocal RecoveryAction = "fail_local" RecoveryKeepRemote RecoveryAction = "keep_remote" )
func DefaultRunRecoveryPolicy ¶
func DefaultRunRecoveryPolicy(run session.SessionRun) RecoveryAction
DefaultRunRecoveryPolicy preserves remotely resumable Responses runs and fails local Agent loops, which cannot survive process termination.
type RefreshOptions ¶
RefreshOptions are mutable resource-affecting session capabilities.
type RegistryHook ¶
type RegistryHook func(*SessionRuntime) error
RegistryHook injects adapter-specific tools into a fully initialized shared runtime. Hooks run after core tools are registered and before MCP connects, so MCP tools see the final registry without owning Runtime lifecycle.
type RegistryMutator ¶
RegistryMutator is an adapter policy callback for tools that cannot yet be represented as core Runtime capabilities.
type RegistryPolicy ¶
type RegistryPolicy struct {
RegisterDefaults bool
EnablePlanTool *bool
SkillsMgr *skills.Manager
Browser bool
Mutators []RegistryMutator
}
RegistryPolicy controls shared registry construction without letting adapters own its sandbox, workdir, or lifecycle.
type RetryInfo ¶
type RetryInfo struct {
Attempt int `json:"attempt,omitempty"`
MaxAttempts int `json:"maxAttempts,omitempty"`
Phase RunPhase `json:"phase,omitempty"`
ReasonCode string `json:"reasonCode,omitempty"`
RetryAfterMS int `json:"retryAfterMs,omitempty"`
Continue bool `json:"continue,omitempty"`
MessageKey string `json:"messageKey,omitempty"`
Message string `json:"message,omitempty"`
}
RetryInfo is a non-terminal progress record. It is persisted as a run event so reconnecting adapters can render the same automatic retry state.
type RetryMode ¶
type RetryMode string
RetryMode states who may make progress after a failure. Automatic retry is owned by Agent Core/Runtime; adapters only project its progress. Reconcile means the caller must first discover whether a previous submission exists.
type RunEvent ¶
type RunEvent struct {
ID string
SessionID string
RunID string
EventType string
Source string
Status string
Model string
Mode string
Timestamp time.Time
Data json.RawMessage
}
RunEvent is the front-end-neutral durable representation of a run event. Adapters may keep their protocol payload in Data, but persistence is owned by this runtime boundary.
func NewDeliveryPendingEvent ¶
func NewDeliveryReconciledEvent ¶
func NewDeliveryReconciledEvent(sessionID, runID, source string, data json.RawMessage) RunEvent
type RunEventProjector ¶
RunEventProjector is an optional live-transport hook used when an event was persisted as part of an atomic admission transaction. It must not write a second durable row; it only fans the already committed event out to clients.
type RunEventSink ¶
RunEventSink persists run lifecycle events without exposing the adapter implementation to the Runtime.
type RunEventSinkFunc ¶
RunEventSinkFunc adapts a function to the adapter-neutral event sink.
type RunPhase ¶
type RunPhase string
RunPhase indicates where a failure or retry occurred.
const ( PhaseAdmission RunPhase = "admission" PhaseModel RunPhase = "model" PhaseContext RunPhase = "context" PhaseTool RunPhase = "tool" PhaseApproval RunPhase = "approval" PhasePersistence RunPhase = "persistence" PhaseTransport RunPhase = "transport" PhaseTerminalization RunPhase = "terminalization" )
type RunRecoveryPolicy ¶
type RunRecoveryPolicy func(session.SessionRun) RecoveryAction
type RunRecoveryResult ¶
type RunRecoveryResult struct {
Failed []session.SessionRun
Kept []session.SessionRun
}
func RecoverOrphanedRuns ¶
func RecoverOrphanedRuns(sessionDir string, policy RunRecoveryPolicy, beforeFail func(session.SessionRun) error) (RunRecoveryResult, error)
RecoverOrphanedRuns applies one shared startup policy to all durable runs. beforeFail may persist adapter-compatible decision cleanup before the run is marked failed.
type RunReplay ¶
type RunReplay struct {
SessionID string
RunID string
Events []RunEvent
Status RunState
Terminal bool
}
RunReplay is the adapter-neutral projection of persisted run events. It is intentionally read-only: adapters decide how to render or recover protocol state from the event data.
func ReplayRunEvents ¶
func ReplayRunEvents(events []session.SessionRunEvent, runID string) RunReplay
ReplayRunEvents reconstructs one run's latest lifecycle state from durable SessionRunEvents. Unknown event types remain in Events for adapter replay.
type RunState ¶
type RunState string
RunState is the adapter-neutral lifecycle state of an active execution.
const ( RunStateCreated RunState = "created" RunStateQueued RunState = "queued" RunStateRunning RunState = "running" RunStateWaitingApproval RunState = "waiting_for_approval" RunStateWaitingQuestion RunState = "waiting_for_question" RunStateCancelling RunState = "cancelling" RunStateCompleted RunState = "completed" RunStateIncomplete RunState = "incomplete" RunStateFailed RunState = "failed" RunStateCancelled RunState = "cancelled" RunStateTimedOut RunState = "timed_out" )
type RunStore ¶
type RunStore struct {
SessionDir string
}
RunStore persists the canonical run row alongside RunEvent records. It reuses the existing session_runs schema so startup recovery can discover runs from every adapter.
func (RunStore) Create ¶
func (s RunStore) Create(run DurableRun) error
func (RunStore) CreateIntentAndRun ¶
func (s RunStore) CreateIntentAndRun(intent ExecutionIntent, run DurableRun) error
func (RunStore) CreateIntentAndRunWithEvent ¶
func (s RunStore) CreateIntentAndRunWithEvent(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
func (RunStore) CreateIntentAndRunWithEventAndTurn ¶ added in v1.2.92
func (s RunStore) CreateIntentAndRunWithEventAndTurn(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
func (RunStore) CreateRunWithEvent ¶
func (s RunStore) CreateRunWithEvent(run DurableRun, event RunEvent) (string, error)
func (RunStore) CreateRunWithEventAndTurn ¶ added in v1.2.92
func (s RunStore) CreateRunWithEventAndTurn(run DurableRun, event RunEvent) (string, error)
func (RunStore) FinishConversationTurn ¶ added in v1.2.92
func (s RunStore) FinishConversationTurn(run DurableRun, state RunState, message string) error
func (RunStore) FinishRunAndConversationTurn ¶ added in v1.2.92
func (RunStore) LeaseLost ¶ added in v1.2.92
LeaseLost exposes the process-local loss signal for the Session lease. The ExecutionRuntime uses it to cancel provider/tool work promptly; persistence methods still validate the durable epoch and token independently.
func (RunStore) Reopen ¶
Reopen explicitly reactivates a terminal run for provider recovery. It is intentionally separate from Update so ordinary lifecycle transitions remain monotonic.
func (RunStore) UpdateErrorInfo ¶
func (RunStore) UpdateProgress ¶
func (RunStore) UpdateUsage ¶
func (s RunStore) UpdateUsage(runID string, usage, contextUsage json.RawMessage) error
type RuntimeSource ¶
type RuntimeSource string
RuntimeSource identifies the runtime that owns a session's execution policy.
const ( SourceUnknown RuntimeSource = "" SourceTUI RuntimeSource = "tui" SourceWebUI RuntimeSource = "webui" SourceWeChat RuntimeSource = "wechat" SourceFeishu RuntimeSource = "feishu" SourceACP RuntimeSource = "acp" SourceCLI RuntimeSource = "cli" SourceCron RuntimeSource = "cron" )
func SourceFromChannelType ¶
func SourceFromChannelType(channelType string) RuntimeSource
SourceFromChannelType maps persisted channel bindings to a runtime source.
func SourceFromSessionHeader ¶
func SourceFromSessionHeader(header *session.Header) RuntimeSource
SourceFromSessionHeader derives policy ownership from persisted session identity.
type SessionConfigOption ¶ added in v1.2.90
type SessionConfigOption struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Category string `json:"category,omitempty"`
CurrentValue string `json:"currentValue"`
Options []SessionConfigOptionChoice `json:"options,omitempty"`
}
SessionConfigOption is the front-end-neutral representation of a mutable session setting. ACP serializes this shape directly as a select option, while other adapters can render the same catalog in their native UI.
func SessionConfigOptions ¶ added in v1.2.90
func SessionConfigOptions(providerName string, models []*provider.Model, model *provider.Model, mode string, thinking provider.ThinkingLevel) []SessionConfigOption
SessionConfigOptions builds the standard model, mode, and thinking catalogs.
type SessionConfigOptionChoice ¶ added in v1.2.90
type SessionConfigOptionChoice struct {
Value string `json:"value"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
SessionConfigOptionChoice is one value in a mutable session option.
type SessionModelBinding ¶ added in v1.2.90
SessionModelBinding is the persisted/runtime model identity for one session. Provider is process-owned; Model is session-owned and can be changed without rebuilding credentials or any other session resources.
type SessionRunEventSink ¶
type SessionRunEventSink struct {
SessionDir string
}
SessionRunEventSink stores events in the existing session_run_events table. It intentionally reuses the existing session persistence API and schema.
func (SessionRunEventSink) Record ¶
func (s SessionRunEventSink) Record(ev RunEvent) (string, error)
func (SessionRunEventSink) RecordJSON ¶
func (s SessionRunEventSink) RecordJSON(sessionID, runID, eventType, source, status, model, mode string, data any) (string, error)
type SessionRuntime ¶
type SessionRuntime struct {
ID string
Source RuntimeSource
EntrySource RuntimeSource
Policy ExecutionPolicy
WorkDir string
Manager *session.Manager
Registry *tools.Registry
SandboxMgr *sandbox.Manager
SkillsMgr *skills.Manager
MCPClients []*mcp.Client
ExtraContext string
RuleContent string
LastUsed time.Time
Execution *ExecutionRuntime
Decisions *DecisionService
// Provider is process-owned while Model, Mode, and ThinkingLevel are
// session-owned bindings used by BuildAgent when adapters omit overrides.
Provider provider.Provider
ProviderName string
Model *provider.Model
Mode string
ThinkingLevel provider.ThinkingLevel
AdditionalDirectories []string
// contains filtered or unexported fields
}
SessionRuntime is the front-end-neutral state required to construct and run an agent session. Adapters may wrap it with protocol-specific locks, approval state, and event delivery, but must not rebuild these shared resources.
func AttachSessionResources ¶
func AttachSessionResources(resources AttachedResources) (*SessionRuntime, error)
AttachSessionResources creates a SessionRuntime around already-selected resources. It validates the session ownership boundary and is the sole compatibility bridge for adapters with protocol-specific Registry/MCP policy.
func (*SessionRuntime) AdditionalDirectoriesSnapshot ¶ added in v1.2.90
func (r *SessionRuntime) AdditionalDirectoriesSnapshot() []string
AdditionalDirectoriesSnapshot returns a copy of the current session roots.
func (*SessionRuntime) ApplyRegistryHooks ¶
func (r *SessionRuntime) ApplyRegistryHooks(hooks []RegistryHook) error
ApplyRegistryHooks injects adapter-owned tools into this Runtime. It is intentionally limited to Registry mutation; policy resolution, sandbox, allow rules, session ownership and run lifecycle remain Runtime-owned.
func (*SessionRuntime) BindSession ¶
func (r *SessionRuntime) BindSession(manager *session.Manager, requested RuntimeSource) error
BindSession attaches or replaces the persisted session identity owned by this Runtime. It is used by frontends that create sessions lazily.
func (*SessionRuntime) BuildAgent ¶
func (r *SessionRuntime) BuildAgent(opts AgentBuildOptions) (*agent.Agent, error)
This preserves adapter-selected session tools and MCP clients while keeping provider/config/sandbox/context assembly out of adapters.
func (*SessionRuntime) BuildTransientAgent ¶
func (r *SessionRuntime) BuildTransientAgent(registry *tools.Registry, opts AgentBuildOptions) (*agent.Agent, error)
BuildTransientAgent constructs a non-persisted agent over an adapter-provided registry. It is intended for temporary side queries such as TUI /btw. The shared Runtime still supplies provider-independent context and sandbox defaults, while the adapter retains ownership of the temporary registry.
func (*SessionRuntime) Close ¶
func (r *SessionRuntime) Close()
Close releases resources owned by this runtime. It is safe to call more than once and prevents new resource mutations after the first close.
func (*SessionRuntime) ConfigOptions ¶ added in v1.2.90
func (r *SessionRuntime) ConfigOptions() []SessionConfigOption
ConfigOptions returns the standard mutable configuration catalog for this session. An empty catalog means the runtime has not been bound to a provider.
func (*SessionRuntime) ConfigSnapshot ¶ added in v1.2.90
func (r *SessionRuntime) ConfigSnapshot() (provider.Provider, string, *provider.Model, string, provider.ThinkingLevel)
ConfigSnapshot returns the current session configuration atomically.
func (*SessionRuntime) ConfigureSession ¶ added in v1.2.90
func (r *SessionRuntime) ConfigureSession(p provider.Provider, providerName string, model *provider.Model, mode string, thinking provider.ThinkingLevel) error
ConfigureSession installs the process provider and the initial per-session model/mode/thinking bindings. It does not own provider construction.
func (*SessionRuntime) ConnectConfiguredMCP ¶
func (r *SessionRuntime) ConnectConfiguredMCP(ctx context.Context, policy MCPPolicy) error
ConnectConfiguredMCP loads project MCP configuration and applies the same strict/optional connection behavior as ConnectMCP.
func (*SessionRuntime) ConnectMCP ¶
func (r *SessionRuntime) ConnectMCP(ctx context.Context, policy MCPPolicy) error
ConnectMCP connects policy servers to this Runtime's registry. Strict policy returns errors; optional policy records them via OnError and leaves the Runtime usable without MCP clients.
func (*SessionRuntime) RefreshResources ¶
func (r *SessionRuntime) RefreshResources(settings *config.Settings, opts RefreshOptions) error
RefreshResources reloads context files and skills, synchronizes the shared skill_ref/browser tools, and updates the Runtime fields atomically after all validation succeeds. Adapter-specific AgentManager and optional tools are deliberately outside this method.
func (*SessionRuntime) ReloadAdditionalDirectories ¶ added in v1.2.90
func (r *SessionRuntime) ReloadAdditionalDirectories(manager *session.Manager) error
ReloadAdditionalDirectories applies the latest persisted directory binding.
func (*SessionRuntime) ResolvePolicy ¶
func (r *SessionRuntime) ResolvePolicy(sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
ResolvePolicy resolves one source/mode pair from Runtime-owned identity.
func (*SessionRuntime) SetAdditionalDirectories ¶ added in v1.2.90
func (r *SessionRuntime) SetAdditionalDirectories(directories []string) error
SetAdditionalDirectories persists and applies a complete replacement of the session's additional directory roots.
func (*SessionRuntime) SetConfigOption ¶ added in v1.2.90
func (r *SessionRuntime) SetConfigOption(id, value string) error
SetConfigOption validates, persists, and applies one mutable session option. Persistence happens before the in-memory binding changes so failed requests cannot leave a runtime ahead of its session history.
func (*SessionRuntime) SetDecisions ¶
func (r *SessionRuntime) SetDecisions(decisions *DecisionService)
SetDecisions attaches the session's shared decision lifecycle. Adapters may keep protocol payload maps alongside it, but Runtime owns cleanup on close.
func (*SessionRuntime) SetExecution ¶
func (r *SessionRuntime) SetExecution(execution *ExecutionRuntime)
SetExecution attaches the session's canonical execution lifecycle.
func (*SessionRuntime) Shutdown ¶
func (r *SessionRuntime) Shutdown(ctx context.Context) error
Shutdown cancels the active execution, waits for its terminal transition, and then releases Runtime-owned MCP resources. A context bounds the wait.
func (*SessionRuntime) SynchronizeCoreTools ¶
func (r *SessionRuntime) SynchronizeCoreTools(browserEnabled bool)
SynchronizeCoreTools applies mutable registry tools that have no adapter dependency. It is safe to call when context content itself is unchanged.
func (*SessionRuntime) UnbindSession ¶
func (r *SessionRuntime) UnbindSession() error
UnbindSession clears persisted session identity while retaining reusable Runtime-owned resources for a frontend that will lazily create another session.
type SideEffectState ¶
type SideEffectState string
SideEffectState is deliberately conservative. A runtime must not replay an execution with unknown or mutating side effects without an explicit policy decision.
const ( SideEffectNone SideEffectState = "none" SideEffectReadOnly SideEffectState = "read_only" SideEffectMutating SideEffectState = "mutating" SideEffectUnknown SideEffectState = "unknown" )
type Source ¶
type Source = RuntimeSource
Source is retained as a concise compatibility alias for RuntimeSource.
type SourceConflictError ¶
type SourceConflictError struct {
Diagnostics []string
}
SourceConflictError reports contradictory persisted/runtime policy identity. Adapter entry is supplied as Requested and therefore does not conflict with an authoritative binding or session header.
func (*SourceConflictError) Error ¶
func (e *SourceConflictError) Error() string
type SourceResolution ¶
type SourceResolution struct {
Source RuntimeSource
Conflicted bool
Diagnostics []string
}
SourceResolution describes the effective source and any contradictory persisted identity discovered while resolving it.
func ResolvePolicy ¶
func ResolvePolicy(input SourceResolutionInput, sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
ResolvePolicy resolves source and then applies the mode policy to the same identity, preventing display and execution paths from selecting different sources or defaults.
func ResolvePolicyFromSession ¶
func ResolvePolicyFromSession(sessionDir, sessionID string, input SourceResolutionInput, sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
ResolvePolicyFromSession loads authoritative binding state and resolves mode through the same policy used by live Runtime instances.
func ResolveSource ¶
func ResolveSource(input SourceResolutionInput) SourceResolution
ResolveSource applies the source precedence required by the Runtime boundary. A persisted binding wins over a session header, which wins over the current runtime source, which wins over a request source. Conflicting persisted values are reported instead of silently being discarded.
func ResolveSourceFromSession ¶
func ResolveSourceFromSession(sessionDir, sessionID string, input SourceResolutionInput) (SourceResolution, error)
ResolveSourceFromSession loads the persisted binding before applying the source precedence rules. It is intended for existing-session recovery paths.
type SourceResolutionInput ¶
type SourceResolutionInput struct {
Binding *session.Binding
SessionHeader *session.Header
Current RuntimeSource
Requested RuntimeSource
}
SourceResolutionInput contains all source candidates available at a runtime boundary. Persisted binding and session header are authoritative for existing sessions; request source is only eligible for an unbound session.
type ToolCallPolicyDecision ¶
ToolCallPolicyDecision is the source policy result for one tool call.
Source Files
¶
- agent_build.go
- agent_manager.go
- attach.go
- decision.go
- decision_record.go
- decision_replay.go
- delivery_events.go
- delivery_replay.go
- durable_ops.go
- error_info.go
- execution.go
- execution_events.go
- execution_observation.go
- execution_persistence.go
- fork.go
- policy.go
- registry.go
- run_event.go
- run_recovery.go
- run_replay.go
- run_store.go
- session_directories.go
- session_lifecycle.go
- session_options.go
- session_runtime.go
- source.go
- tool_policy.go