agentruntime

package
v1.2.96 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

Package agentruntime contains front-end-neutral execution policy primitives.

Index

Constants

View Source
const (
	ModePlan  = "plan"
	ModeAgent = "agent"
	ModeYolo  = "yolo"
	ModeOS    = "os"
)
View Source
const (
	DefaultRecoveryScanInterval   = 5 * time.Second
	DefaultRecoveryAttemptTimeout = 10 * time.Second
)
View Source
const (
	ConfigOptionProvider      = "provider"
	ConfigOptionModel         = "model"
	ConfigOptionMode          = "mode"
	ConfigOptionThinkingLevel = "thinking_level"
	ConfigOptionSandbox       = "sandbox"
	ConfigOptionBrowser       = "browser"
	ConfigOptionWebSearch     = "web_search"
)

SessionConfigOption IDs are stable protocol-neutral identifiers.

View Source
const (
	DefaultTerminalPersistenceTimeout = 10 * time.Second
)

Variables

View Source
var ErrDetachedRemoteExecution = errors.New("session has a recoverable detached remote execution")
View Source
var ErrIdempotencyKeyConflict = session.ErrRuntimeSubmissionConflict

ErrIdempotencyKeyConflict means a submission key was reused for a different request or admission scope. Callers must not silently start another Run.

View Source
var ErrIdempotencyRunMissing = errors.New("idempotency started event has no durable run")

ErrIdempotencyRunMissing means a durable started event matched a submission key but its canonical Run row is unavailable for reconciliation.

View Source
var ErrRemoteStopUnsupported = errors.New("remote stop is unsupported")

ErrRemoteStopUnsupported lets a provider control hook distinguish a missing cancel capability from an upstream failure.

Functions

func AcquireExecutionAdmission added in v1.2.96

func AcquireExecutionAdmission(ctx context.Context, sessionDir, sessionID string, options ExecutionAdmissionOptions) (*session.RuntimeLeaseGuard, error)

AcquireExecutionAdmission obtains the explicit admission lease for a new Run. If a stale durable Run blocks admission, this operation reconciles it through the same lease-first Runtime recovery path and retries. A valid local or external owner is never displaced.

func AcquireSessionMutation added in v1.2.96

func AcquireSessionMutation(ctx context.Context, sessionDir, sessionID string, options ExecutionAdmissionOptions) (*session.RuntimeLeaseGuard, error)

AcquireSessionMutation waits for (or immediately attempts) an explicit mutation lease. An orphaned local Run is reconciled through the same shared recovery path before the mutation is retried.

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

func CloseMCPClients(clients []*mcp.Client)

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

func DefaultPlanToolPolicy(settings *config.Settings) *bool

DefaultPlanToolPolicy returns the configured plan-tool setting.

func DeleteSession

func DeleteSession(sessionDir, id string) error

DeleteSession removes a persisted session by ID when it is not active.

func DeliveryOperationText added in v1.2.96

func DeliveryOperationText(raw []byte, operationKind string) string

DeliveryOperationText returns the frozen text payload for a durable text operation. Transport adapters use this Runtime-owned projection for both immediate delivery and recovery, so neither path reconstructs a caption or fallback from mutable adapter state.

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

func DisplayErrorMessage(info ErrorInfo) string

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 FindIdempotentRun added in v1.2.96

func FindIdempotentRun(ctx context.Context, sessionDir, sessionID, key, fingerprint, scope string) (*session.SessionRun, error)

FindIdempotentRun reconciles a submission key against canonical started events. It is intentionally a read-only compatibility bridge until the Runtime-owned submission table is migrated; callers must invoke it again after acquiring their session/runtime admission locks.

func FinishDurableRun

func FinishDurableRun(sessionDir, runID string, state RunState, message string) error

FinishDurableRun applies a Runtime-owned terminal transition when no live ExecutionRuntime can be reattached. It remains monotonic and idempotent.

func GetActiveDurableRun added in v1.2.96

func GetActiveDurableRun(ctx context.Context, sessionDir, sessionID string) (*session.SessionRun, error)

GetActiveDurableRun loads the canonical non-terminal Run for a Session. Callers that need ownership, submit, or cancellation decisions must use InspectSessionExecution instead, since an active row alone does not prove a local execution owner.

func GetDurableRun added in v1.2.96

func GetDurableRun(ctx context.Context, sessionDir, runID string) (*session.SessionRun, error)

GetDurableRun loads one canonical Run row for inspection by an adapter. Durable lifecycle writes remain owned by ExecutionRuntime/RunStore; this read boundary keeps adapters from treating session storage as their own execution state store.

func IdempotencyKeyFingerprint added in v1.2.96

func IdempotencyKeyFingerprint(key string) string

IdempotencyKeyFingerprint keeps a client/platform key out of durable event data while retaining a stable equality token for reconciliation.

func IsValidMode

func IsValidMode(mode string) bool

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

func NormalizeAdditionalDirectories(directories []string) ([]string, error)

NormalizeAdditionalDirectories validates the ACP directory-root contract: absolute, cleaned, deterministic and duplicate-free paths.

func OpenSession

func OpenSession(sessionDir, id string) (*session.Manager, error)

OpenSession opens a persisted session by exact ID regardless of its workdir.

func OpenSessionForWorkDir

func OpenSessionForWorkDir(workDir, sessionDir, id string) (*session.Manager, error)

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

func ReopenDurableRun(sessionDir, runID string, state RunState, message string) error

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

func UpdateDurableRun(sessionDir, runID string, state RunState, message string) error

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
	SandboxMgr             *sandbox.Manager
	SandboxEnabled         *bool
	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
	BeforeToolExecute      func(agent.BeforeToolExecuteContext) *agent.ToolCallBlockResult
	AfterToolCall          func(agent.AfterToolCallContext) *agent.ToolCallResult
	GetSteeringMessages    func() []provider.Message
	ConversationTurnID     string
	IntentID               string
	RunID                  string
	ConversationTurn       bool
	RuntimeOwnsTurnEnd     bool
	RuntimeOwnsUserEntry   bool
	UserEntryID            string
}

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

type AgentEventObservation struct {
	Retry *RetryInfo
	Error *ErrorInfo
}

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 ArtifactCollector added in v1.2.96

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

ArtifactCollector owns the generated artifacts registered during one Runtime run. It is created by SessionRuntime before Agent construction so publish_artifact participates in the frozen, canonical tool registry.

func (*ArtifactCollector) Artifacts added in v1.2.96

func (c *ArtifactCollector) Artifacts() []SessionAttachment

Artifacts returns a stable copy of every artifact successfully copied to Runtime-owned private storage during this run.

func (*ArtifactCollector) Close added in v1.2.96

func (c *ArtifactCollector) Close()

Close removes this run's dynamic tool. Channel runs are serialized by their SessionRuntime lock; identity comparison still prevents an old collector from removing a newer run's tool if a caller closes late.

func (*ArtifactCollector) Register added in v1.2.96

func (c *ArtifactCollector) Register(ctx context.Context, sourcePath, filename, requestedKind string) (SessionAttachment, error)

Register copies a regular file from the Runtime work directory to private attachment storage. It refuses symlink escapes and persists only the copied content's generated attachment ID, never the source path.

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
	Providers             ProviderCatalog
	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 AttachmentKind added in v1.2.96

type AttachmentKind string

AttachmentKind identifies the media classes supported by Runtime input and artifact delivery. Provider attachments are normalized into this store only when they become concrete files.

const (
	AttachmentImage AttachmentKind = "image"
	AttachmentFile  AttachmentKind = "file"
	AttachmentAudio AttachmentKind = "audio"
	AttachmentVideo AttachmentKind = "video"
)

type AttachmentPolicy added in v1.2.96

type AttachmentPolicy struct {
	MaxImageBytes int64
	MaxFileBytes  int64
	Retention     time.Duration
}

AttachmentPolicy contains the local resource limits for accepted media. These are reliability limits for a self-hosted service, not a moderation or multi-tenant authorization policy.

func DefaultAttachmentPolicy added in v1.2.96

func DefaultAttachmentPolicy() AttachmentPolicy

type AttachmentService added in v1.2.96

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

AttachmentService owns attachment storage and its session-backed records. Platform adapters provide only the authenticated Open function.

func NewAttachmentService added in v1.2.96

func NewAttachmentService(sessionDir string, policy AttachmentPolicy) (*AttachmentService, error)

func (*AttachmentService) CleanupExpired added in v1.2.96

func (s *AttachmentService) CleanupExpired(ctx context.Context) (int, error)

CleanupExpired expires and removes private attachment content whose TTL has elapsed. It is deliberately tolerant of an already-missing file: expiry is a durable Runtime state, while a subsequent invocation can retry a failed filesystem removal without involving any transport adapter.

func (*AttachmentService) Get added in v1.2.96

func (s *AttachmentService) Get(ctx context.Context, sessionID, attachmentID string) (SessionAttachment, error)

Get returns one attachment record belonging to sessionID.

func (*AttachmentService) Open added in v1.2.96

func (s *AttachmentService) Open(ctx context.Context, sessionID, attachmentID string) (SessionAttachment, io.ReadCloser, error)

Open returns the private content stream after checking session ownership and expiry. Callers must close the returned reader.

func (*AttachmentService) Policy added in v1.2.96

func (s *AttachmentService) Policy() AttachmentPolicy

func (*AttachmentService) SetStatus added in v1.2.96

func (s *AttachmentService) SetStatus(ctx context.Context, sessionID, attachmentID, status string) error

SetStatus updates the Runtime-owned lifecycle state of an attachment. It is used for explicit state transitions such as accepted -> generated -> expired; adapters do not write attachment rows or statuses directly.

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

type Builder struct {
	Settings     *config.Settings
	SandboxLevel sandbox.Level
}

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

type ContextResources struct {
	SkillsMgr    *skills.Manager
	ExtraContext string
	RuleContent  string
}

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 DeliveryCapability added in v1.2.96

type DeliveryCapability struct {
	Text      bool
	SendImage bool
	SendFile  bool
	SendVideo bool
}

DeliveryCapability describes a transport's actual media behavior. It is a Runtime policy input, not a promise inferred from a platform's wire format.

type DeliveryCoordinator added in v1.2.96

type DeliveryCoordinator struct {
	SessionDir string
	Owner      string
	Lease      time.Duration
	MaxRetries int
}

DeliveryCoordinator is the Runtime-owned claim/fence/retry boundary for durable delivery outbox operations.

func NewDeliveryCoordinator added in v1.2.96

func NewDeliveryCoordinator(sessionDir, owner string) *DeliveryCoordinator

func (*DeliveryCoordinator) Claim added in v1.2.96

func (c *DeliveryCoordinator) Claim(ctx context.Context, operationID string, now time.Time) (*session.DeliveryOperation, error)

func (*DeliveryCoordinator) Complete added in v1.2.96

func (c *DeliveryCoordinator) Complete(ctx context.Context, operation *session.DeliveryOperation, result DeliveryResult) error

func (*DeliveryCoordinator) Progress added in v1.2.96

func (c *DeliveryCoordinator) Progress(ctx context.Context, operation *session.DeliveryOperation, result DeliveryResult) error

Progress checkpoints an in-flight provider phase without releasing its lease. Complete must later use the same operation owner and epoch.

func (*DeliveryCoordinator) ReconcileDue added in v1.2.96

func (c *DeliveryCoordinator) ReconcileDue(ctx context.Context, now time.Time, execute DeliveryExecutor) (int, error)

ReconcileDue claims and executes all currently due operations. Errors from a transport are converted to bounded retry_wait; callers can explicitly return DeliveryResult{Status:"uncertain"} when the provider result is ambiguous.

type DeliveryExecutor added in v1.2.96

type DeliveryExecutor func(context.Context, session.DeliveryOperation) (DeliveryResult, error)

DeliveryExecutor performs one platform operation after the Runtime has claimed it. It may upload/send through a platform SDK but cannot write delivery rows directly.

type DeliveryIntentPlan added in v1.2.96

type DeliveryIntentPlan struct {
	ID               string
	SessionID        string
	RunID            string
	Platform         string
	TargetID         string
	ReplyMessageID   string
	TransportContext json.RawMessage
	Status           string
	CreatedAt        time.Time
}

DeliveryIntentPlan freezes the run-level transport target and opaque reply context before the terminal transaction creates the durable outbox.

type DeliveryPlan added in v1.2.96

type DeliveryPlan struct {
	Intent     DeliveryIntentPlan
	Operations []OrderedDeliveryOperationPlan
}

DeliveryPlan is attached to the active DurableRun and persisted by its terminal transaction. Adapters may supply transport hooks but never write these rows directly.

func PlanDelivery added in v1.2.96

func PlanDelivery(request DeliveryPlanRequest) (DeliveryPlan, string, error)

PlanDelivery builds a deterministic run-level caption/upload/send/fallback sequence. It performs no persistence and no network I/O.

type DeliveryPlanRequest added in v1.2.96

type DeliveryPlanRequest struct {
	SessionID        string
	RunID            string
	Platform         string
	TargetID         string
	ReplyMessageID   string
	TransportContext json.RawMessage
	Caption          string
	Attachments      []SessionAttachment
	Capability       DeliveryCapability
	CreatedAt        time.Time
}

DeliveryPlanRequest contains the canonical result and the transport target needed to build deterministic ordered operations before terminal commit.

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 DeliveryResult added in v1.2.96

type DeliveryResult struct {
	Status            string
	ProviderAssetID   string
	ProviderMessageID string
	ProviderState     json.RawMessage
	FailureCode       string
	NextAttemptAt     *time.Time
}

DeliveryResult is the transport-neutral outcome reported by an adapter after it has used a claimed operation. Unknown provider outcomes must use Uncertain so recovery never blindly duplicates a possibly delivered message.

type DurableConversationTurnEventFinisher added in v1.2.92

type DurableConversationTurnEventFinisher interface {
	FinishRunAndConversationTurn(DurableRun, RunState, string, RunEvent) (string, error)
}

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
	// InputResourceIDs are Runtime-prepared resources that this admission must
	// bind to the Run in the same transaction as the intent, Run row, and start
	// event. Retries may reference resources already bound to the original Run;
	// the store preserves that canonical ownership.
	InputResourceIDs      []string
	SubmissionKeyHash     string
	SubmissionScope       string
	SubmissionFingerprint string
	UserEntryID           string
	UserMessage           *provider.Message
	AssistantEntryID      string
	AssistantMessage      *provider.Message
	DeliveryPlan          *DeliveryPlan
	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 DurableTerminalPersistenceStore added in v1.2.96

type DurableTerminalPersistenceStore interface {
	MarkTerminalizing(string, string) error
}

DurableTerminalPersistenceStore marks the explicit, still-non-terminal persistence window before the final Run/turn/event transaction. Stores that do not implement it retain the legacy behavior for embedded tests.

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 ExecutionAdmissionOptions added in v1.2.96

type ExecutionAdmissionOptions struct {
	Wait           bool
	PollInterval   time.Duration
	RecoveryPolicy RunRecoveryPolicy
	BeforeRecover  func(session.SessionRun) error
}

ExecutionAdmissionOptions controls how a frontend-neutral caller waits for ownership and how an orphan is reconciled before a new Run is admitted.

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

func (r *ExecutionRuntime) Begin(parent context.Context, runID string) (context.Context, error)

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) FinishDurableWithRetry added in v1.2.96

func (r *ExecutionRuntime) FinishDurableWithRetry(ctx context.Context, runID string, state RunState, message string, event RunEvent) error

FinishDurableWithRetry keeps the execution lease and local registration active while a transient terminal write is retried. The supplied context is bounded to the Runtime maximum so adapters cannot invent divergent retry policies or silently clear their projection after the first storage error.

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) SetAssistantMessage added in v1.2.96

func (r *ExecutionRuntime) SetAssistantMessage(runID, entryID string, message provider.Message) error

SetAssistantMessage stages the final assistant transcript entry for the active Run. Runtime-owned conversation terminalization commits this message atomically with the terminal Run/turn and delivery plan.

func (*ExecutionRuntime) SetDeliveryPlan added in v1.2.96

func (r *ExecutionRuntime) SetDeliveryPlan(runID string, plan DeliveryPlan) error

SetDeliveryPlan attaches a Runtime-planned outbox to the active durable Run. It must happen before terminalization so the Run/turn/event and delivery rows are committed by one store transaction.

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) SetTerminalObserver added in v1.2.96

func (r *ExecutionRuntime) SetTerminalObserver(observer func(string, RunState))

SetTerminalObserver installs a lightweight notification for adapters that keep protocol/session projections in memory. It is invoked only after the canonical durable terminal transition succeeds, including an asynchronous Runtime-owned retry. The observer must be idempotent and should avoid doing blocking work.

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 InputIngress added in v1.2.96

type InputIngress struct {
	Origin        string
	EventID       string
	ItemIndex     int
	Reference     string
	Kind          AttachmentKind
	FilenameHint  string
	MediaTypeHint string
	SizeHint      int64
	Open          func(context.Context) (InputStream, error)
}

InputIngress is the ephemeral adapter-to-Runtime handoff for one input resource. Reference and transport credentials are never persisted.

type InputMaterializer added in v1.2.96

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

InputMaterializer owns project-relative input files and their session-backed records. Artifact bytes deliberately use a different private store.

func NewInputMaterializer added in v1.2.96

func NewInputMaterializer(sessionDir, workDir string, policy InputPolicy) (*InputMaterializer, error)

func (*InputMaterializer) Cleanup added in v1.2.96

func (m *InputMaterializer) Cleanup(ctx context.Context, sessionID string, now time.Time) (int, error)

Cleanup removes expired unbound drafts, marks missing records, and leaves attached resources untouched. Filesystem deletion happens after the durable status transaction so a retry can safely finish interrupted cleanup.

func (*InputMaterializer) Delete added in v1.2.96

func (m *InputMaterializer) Delete(ctx context.Context, sessionID, resourceID string) error

Delete explicitly removes a resource, including one already attached to a Run. The record remains as an audit/replay tombstone.

func (*InputMaterializer) Discard added in v1.2.96

func (m *InputMaterializer) Discard(ctx context.Context, sessionID, resourceID string) error

Discard removes an unbound draft resource from the project input area while retaining a durable deleted record and canonical lifecycle event.

func (*InputMaterializer) Get added in v1.2.96

func (m *InputMaterializer) Get(ctx context.Context, sessionID, resourceID string) (InputResource, error)

func (*InputMaterializer) Prepare added in v1.2.96

func (m *InputMaterializer) Prepare(ctx context.Context, sessionID, runID string, ingress InputIngress) (InputResource, error)

Prepare streams one resource into .mothx/tmp/inputs and persists its canonical metadata. Stable platform items are idempotent across retries and concurrent deliveries.

type InputPolicy added in v1.2.96

type InputPolicy struct {
	MaxImageBytes  int64
	MaxFileBytes   int64
	MaxImagePixels int64
	DraftMaxAge    time.Duration
}

InputPolicy contains reliability limits applied before an input file enters the project workspace. It does not select file value or parse documents.

func DefaultInputPolicy added in v1.2.96

func DefaultInputPolicy() InputPolicy

type InputResource added in v1.2.96

type InputResource struct {
	ID           string
	SessionID    string
	RunID        string
	Origin       string
	EventID      string
	ItemIndex    int
	ItemKey      string
	Kind         AttachmentKind
	Filename     string
	MediaType    string
	Bytes        int64
	SHA256       string
	RelativePath string
	Status       string
	CreatedAt    time.Time
}

InputResource is the canonical persisted input file record.

func (InputResource) Prepared added in v1.2.96

func (r InputResource) Prepared() PreparedInput

type InputStream added in v1.2.96

type InputStream struct {
	Reader      io.ReadCloser
	Filename    string
	MediaType   string
	ContentSize int64
}

InputStream is the authenticated one-shot stream supplied by an adapter.

type InputSubmission added in v1.2.96

type InputSubmission struct {
	Text           string
	Resources      []PreparedInput
	IdempotencyKey string
}

InputSubmission is the only user-input contract consumed by SessionRuntime. IdempotencyKey carries the caller's submission identity. Resource item idempotency is enforced here; durable submission reservation and existing-Run reuse are handled by the Runtime admission layer.

func (InputSubmission) ResourceIDs added in v1.2.96

func (s InputSubmission) ResourceIDs() []string

ResourceIDs returns the canonical Runtime resource IDs in submission order. The slice is copied so callers cannot mutate the submission's ownership facts while durable admission is assembling its transaction.

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.

func (ModeResolver) Resolve

func (r ModeResolver) Resolve(sessionMode, requestedMode string) (string, error)

Resolve returns the effective mode for the resolver's policy.

type OrderedDeliveryOperationPlan added in v1.2.96

type OrderedDeliveryOperationPlan struct {
	ID             string
	OperationKey   string
	ArtifactID     string
	OperationKind  string
	Sequence       int
	DependsOn      string
	IdempotencyKey string
	PayloadDigest  string
	Status         string
	CreatedAt      time.Time
}

OrderedDeliveryOperationPlan is one deterministic outbox step. Provider state and lease fields are populated only by the delivery coordinator after terminal commit.

type Policy

type Policy = ExecutionPolicy

Policy is retained as a concise compatibility alias for ExecutionPolicy.

func (Policy) ForcedMode

func (p Policy) ForcedMode() string

ForcedMode returns the source-mandated mode, if any.

func (Policy) HasForcedMode

func (p Policy) HasForcedMode() bool

HasForcedMode reports whether a source has a non-overridable execution mode.

func (Policy) ResolveMode

func (p Policy) ResolveMode(sessionMode, requestedMode string) (string, error)

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 PreparedInput added in v1.2.96

type PreparedInput struct {
	ResourceID   string
	Kind         AttachmentKind
	RelativePath string
	Filename     string
	MediaType    string
	Bytes        int64
}

PreparedInput is the opaque resource reference carried by an input submission after Runtime has materialized and persisted it.

type ProviderCatalog added in v1.2.95

type ProviderCatalog map[string]provider.Provider

ProviderCatalog is the set of providers available to a session runtime. Providers are constructed by the adapter/runtime boundary and selected per session; the catalog is never exposed as a configuration API.

type PublishArtifactTool added in v1.2.96

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

PublishArtifactTool is the only Agent-facing way to declare a local file as a delivery artifact. It copies the file before reporting success, so later Agent writes cannot silently mutate a file that is about to be delivered.

func NewPublishArtifactTool added in v1.2.96

func NewPublishArtifactTool(collector *ArtifactCollector) *PublishArtifactTool

func (*PublishArtifactTool) Description added in v1.2.96

func (t *PublishArtifactTool) Description() string

func (*PublishArtifactTool) Execute added in v1.2.96

func (t *PublishArtifactTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*PublishArtifactTool) Name added in v1.2.96

func (t *PublishArtifactTool) Name() string

func (*PublishArtifactTool) Parameters added in v1.2.96

func (t *PublishArtifactTool) Parameters() json.RawMessage

func (*PublishArtifactTool) PromptGuidelines added in v1.2.96

func (t *PublishArtifactTool) PromptGuidelines() []string

func (*PublishArtifactTool) PromptSnippet added in v1.2.96

func (t *PublishArtifactTool) PromptSnippet() string

type RecoveryAction

type RecoveryAction string
const (
	RecoveryFailLocal  RecoveryAction = "fail_local"
	RecoveryKeepRemote RecoveryAction = "keep_remote"
)

func DefaultRunRecoveryPolicy

func DefaultRunRecoveryPolicy(run session.SessionRun) RecoveryAction

DefaultRunRecoveryPolicy fails local Agent loops, which cannot survive process termination. Provider-native remote execution must be retained only by a caller that has resolved a canonical remote run record and capability; Run.Source alone is not evidence that a provider task still exists.

type RecoveryCoordinator added in v1.2.96

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

RecoveryCoordinator periodically drives lease-first orphan convergence for one canonical Session database. Multiple processes may scan the same DB; AcquireRecovery's SQLite CAS elects exactly one worker per Session.

func NewRecoveryCoordinator added in v1.2.96

func NewRecoveryCoordinator(sessionDir string, options RecoveryCoordinatorOptions) *RecoveryCoordinator

func (*RecoveryCoordinator) ScanNow added in v1.2.96

ScanNow runs the same shared recovery path used by startup and the ticker.

func (*RecoveryCoordinator) Start added in v1.2.96

func (c *RecoveryCoordinator) Start(parent context.Context) error

Start performs the mandatory startup scan synchronously, then begins the periodic and wake-driven loop. A startup error is returned for diagnostics, while the coordinator remains active so transient failures can converge.

func (*RecoveryCoordinator) Stop added in v1.2.96

Stop terminates the loop and waits for an in-progress scan to return.

func (*RecoveryCoordinator) Wake added in v1.2.96

func (c *RecoveryCoordinator) Wake()

Wake coalesces notifications; SQLite remains the authority when the next scan runs, so lost or duplicated wake-ups do not affect correctness.

type RecoveryCoordinatorOptions added in v1.2.96

type RecoveryCoordinatorOptions struct {
	ScanInterval   time.Duration
	AttemptTimeout time.Duration
	Policy         RunRecoveryPolicy
	BeforeFail     func(session.SessionRun) error
	OnResult       func(RunRecoveryResult)
	OnError        func(error)
}

RecoveryCoordinatorOptions supplies policy hooks owned by the shared Runtime host. Adapters may clean up their protocol projections in BeforeFail, but they do not decide whether a valid lease can be displaced.

type RefreshOptions

type RefreshOptions struct {
	Workflows    bool
	Browser      bool
	ActiveSkills map[string]bool
}

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

type RegistryMutator func(*tools.Registry) error

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 RemoteStopRequest added in v1.2.96

type RemoteStopRequest struct {
	SessionID   string `json:"sessionId"`
	RunID       string `json:"runId"`
	RemoteRunID string `json:"remoteRunId"`
	Provider    string `json:"provider"`
	State       string `json:"state"`
}

RemoteStopRequest contains canonical provider execution identity. It never contains lease credentials: the Runtime acquires and revalidates those internally before invoking the provider hook.

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.

const (
	RetryNone             RetryMode = "none"
	RetryAutomatic        RetryMode = "automatic"
	RetryReconcile        RetryMode = "reconcile"
	RetryUser             RetryMode = "user"
	RetryDecisionRequired RetryMode = "decision_required"
)

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
	// Assistant fields are Runtime-only terminal transaction inputs. They are
	// not serialized into the generic event envelope or exposed to prompts.
	AssistantEntryID string
	AssistantMessage provider.Message
}

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 NewDeliveryPendingEvent(sessionID, runID, source, status, model, mode string, data any) RunEvent

func NewDeliveryReconciledEvent

func NewDeliveryReconciledEvent(sessionID, runID, source string, data json.RawMessage) RunEvent

type RunEventProjector

type RunEventProjector interface {
	Project(RunEvent, string) error
}

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

type RunEventSink interface {
	Record(RunEvent) (string, error)
}

RunEventSink persists run lifecycle events without exposing the adapter implementation to the Runtime.

type RunEventSinkFunc

type RunEventSinkFunc func(RunEvent) (string, error)

RunEventSinkFunc adapts a function to the adapter-neutral event sink.

func (RunEventSinkFunc) Record

func (f RunEventSinkFunc) Record(event RunEvent) (string, error)

type RunInput added in v1.2.96

type RunInput = InputSubmission

RunInput remains a source-compatible name while adapters migrate to the canonical InputSubmission name. It is an alias, not a second input model.

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
	Skipped []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.

func RecoverOrphanedSessionRun added in v1.2.96

func RecoverOrphanedSessionRun(sessionDir, sessionID string, policy RunRecoveryPolicy, beforeFail func(session.SessionRun) error) (RunRecoveryResult, error)

RecoverOrphanedSessionRun reconciles the one active Run for a session before a new local execution is admitted. It acquires its own purpose=recovery lease; callers must not pre-acquire a generic Session lease. A valid owner is skipped, not terminalized. Remotely resumable Runs are retained only when the supplied policy has verified their durable provider state.

func RecoverOrphanedSessionRunContext added in v1.2.96

func RecoverOrphanedSessionRunContext(ctx context.Context, sessionDir, sessionID string, policy RunRecoveryPolicy, beforeFail func(session.SessionRun) error) (RunRecoveryResult, error)

RecoverOrphanedSessionRunContext is the context-bounded admission recovery path used by Runtime callers.

func StopOrphanedSessionRun added in v1.2.96

func StopOrphanedSessionRun(sessionDir, sessionID string, beforeTerminalize func(session.SessionRun) error) (RunRecoveryResult, error)

StopOrphanedSessionRun performs the user-triggered form of orphan reconciliation. It uses the same recovery lease/fencing path as automatic recovery but records a cancelled terminal state and a distinct reason.

func StopOrphanedSessionRunContext added in v1.2.96

func StopOrphanedSessionRunContext(ctx context.Context, sessionDir, sessionID string, beforeTerminalize func(session.SessionRun) error) (RunRecoveryResult, error)

StopOrphanedSessionRunContext is the context-bounded user-triggered orphan convergence path.

func StopOrphanedSessionRunContextForRun added in v1.2.96

func StopOrphanedSessionRunContextForRun(ctx context.Context, sessionDir, sessionID, expectedRunID string, beforeTerminalize func(session.SessionRun) error) (RunRecoveryResult, error)

StopOrphanedSessionRunContextForRun is the target-scoped user-triggered orphan convergence path. An empty expectedRunID preserves the session-wide compatibility behavior; a non-empty value prevents a stale caller from terminalizing a newer Run admitted after its initial inspection.

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"
	RunStateTerminalizing   RunState = "terminalizing"
	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) ExecutionBinding added in v1.2.96

func (s RunStore) ExecutionBinding(sessionID, runID string) (session.RuntimeLeaseBinding, bool, error)

ExecutionBinding returns the exact local lease identity for a newly admitted Run. A durable lease row owned elsewhere is an error; absence of a lease row remains a compatibility path for embedded/test stores.

func (RunStore) Finish

func (s RunStore) Finish(runID string, state RunState, message 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 (s RunStore) FinishRunAndConversationTurn(run DurableRun, state RunState, message string, event RunEvent) (string, error)

func (RunStore) GetIntent

func (s RunStore) GetIntent(intentID string) (*ExecutionIntent, error)

func (RunStore) LeaseLost added in v1.2.92

func (s RunStore) LeaseLost(sessionID string) <-chan struct{}

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) MarkTerminalizing added in v1.2.96

func (s RunStore) MarkTerminalizing(runID, message string) error

func (RunStore) PrepareExistingExecution added in v1.2.96

func (s RunStore) PrepareExistingExecution(sessionID, runID string) error

PrepareExistingExecution promotes the current recovery/legacy lease before an existing durable Run is reattached to an in-memory ExecutionRuntime.

func (RunStore) Reopen

func (s RunStore) Reopen(runID string, state RunState, message string) error

Reopen explicitly reactivates a terminal run for provider recovery. It is intentionally separate from Update so ordinary lifecycle transitions remain monotonic.

func (RunStore) RetainExecutionLease added in v1.2.96

func (s RunStore) RetainExecutionLease(sessionID, runID string) (session.RuntimeLeaseBinding, func(), bool, error)

RetainExecutionLease transfers one reference of the current execution lease to the Runtime. The adapter's admission guard can then be released without revoking authority needed by a terminal-persistence retry.

func (RunStore) Update

func (s RunStore) Update(runID string, state RunState, message string) error

func (RunStore) UpdateErrorInfo

func (s RunStore) UpdateErrorInfo(runID string, info ErrorInfo) error

func (RunStore) UpdateProgress

func (s RunStore) UpdateProgress(runID string, progress RetryInfo) error

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 SessionAttachment added in v1.2.96

type SessionAttachment struct {
	ID         string
	SessionID  string
	RunID      string
	Origin     string
	Kind       AttachmentKind
	Filename   string
	MediaType  string
	Bytes      int64
	SHA256     string
	StorageKey string
	Status     string
	CreatedAt  time.Time
	ExpiresAt  time.Time
}

SessionAttachment is the canonical persisted attachment record. The content itself lives under StorageKey and is never embedded in a session entry.

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 provider, model, mode, and thinking catalogs when no provider catalog is available to the caller.

func SessionConfigOptionsWithProviders added in v1.2.95

func SessionConfigOptionsWithProviders(providerName string, providers ProviderCatalog, models []*provider.Model, model *provider.Model, mode string, thinking provider.ThinkingLevel) []SessionConfigOption

SessionConfigOptionsWithProviders builds provider, model, mode, and thinking catalogs. The model catalog is intentionally scoped to the current provider so selecting a provider cascades immediately to its models.

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 SessionExecutionSnapshot added in v1.2.96

type SessionExecutionSnapshot struct {
	SessionID            string                `json:"sessionId"`
	SessionExists        bool                  `json:"sessionExists"`
	ActiveRun            *SessionRunSummary    `json:"activeRun,omitempty"`
	State                SessionExecutionState `json:"state"`
	Phase                string                `json:"phase,omitempty"`
	Running              bool                  `json:"running"`
	Busy                 bool                  `json:"busy"`
	CanSubmit            bool                  `json:"canSubmit"`
	CanCancelLocal       bool                  `json:"canCancelLocal"`
	CanCancelRemote      bool                  `json:"canCancelRemote"`
	LeasePurpose         string                `json:"leasePurpose,omitempty"`
	LeaseEpoch           int64                 `json:"leaseEpoch,omitempty"`
	LeaseExpiresAt       *time.Time            `json:"leaseExpiresAt,omitempty"`
	LeaseOwnerInstanceID string                `json:"ownerInstanceId,omitempty"`
	LeaseOwnerPID        int                   `json:"ownerPid,omitempty"`
	LeaseTokenIdentity   string                `json:"leaseTokenIdentity,omitempty"`
	LinkageState         string                `json:"linkageState"`
	RecoveryAction       string                `json:"recoveryAction"`
	RecoveryAttempt      int                   `json:"recoveryAttempt,omitempty"`
	RecoveryLastError    string                `json:"recoveryLastError,omitempty"`
	RecoveryNextAt       *time.Time            `json:"recoveryNextAt,omitempty"`
	DisplayOwnerScope    string                `json:"ownerScope"`
	RemoteRunID          string                `json:"remoteRunId,omitempty"`
	RemoteProvider       string                `json:"remoteProvider,omitempty"`
	RemoteState          string                `json:"remoteState,omitempty"`
}

SessionExecutionSnapshot is the single Runtime-owned interpretation of the durable Run, SQLite lease, and current process execution registration.

func InspectSessionExecution added in v1.2.96

func InspectSessionExecution(sessionDir, sessionID string) (SessionExecutionSnapshot, error)

InspectSessionExecution resolves the canonical execution state without trusting adapter-local maps. Database read failures return an unknown snapshot together with the error so callers remain conservatively busy.

type SessionExecutionState added in v1.2.96

type SessionExecutionState string

SessionExecutionState is the adapter-neutral ownership state of a Session.

const (
	SessionExecutionIdle           SessionExecutionState = "idle"
	SessionExecutionReserved       SessionExecutionState = "reserved"
	SessionExecutionLocal          SessionExecutionState = "local"
	SessionExecutionExternal       SessionExecutionState = "external"
	SessionExecutionDetached       SessionExecutionState = "detached_remote"
	SessionExecutionOrphaned       SessionExecutionState = "orphaned"
	SessionExecutionRecoveryFailed SessionExecutionState = "recovery_failed"
	SessionExecutionInconsistent   SessionExecutionState = "inconsistent"
	SessionExecutionUnknown        SessionExecutionState = "unknown"
)

type SessionModelBinding added in v1.2.90

type SessionModelBinding struct {
	ProviderName string
	Model        *provider.Model
}

SessionModelBinding is the persisted/runtime model identity for one session.

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 SessionRunSummary added in v1.2.96

type SessionRunSummary struct {
	ID        string    `json:"runId"`
	Status    string    `json:"status"`
	Source    string    `json:"source,omitempty"`
	Model     string    `json:"model,omitempty"`
	Mode      string    `json:"mode,omitempty"`
	StartedAt time.Time `json:"startedAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

SessionRunSummary is the canonical non-terminal Run projection carried by a Session execution snapshot.

type SessionRuntime

type SessionRuntime struct {
	ID           string
	Source       RuntimeSource
	EntrySource  RuntimeSource
	Policy       ExecutionPolicy
	WorkDir      string
	Manager      *session.Manager
	Inputs       *InputMaterializer
	Attachments  *AttachmentService
	Registry     *tools.Registry
	SandboxMgr   *sandbox.Manager
	SkillsMgr    *skills.Manager
	MCPClients   []*mcp.Client
	ExtraContext string
	RuleContent  string
	LastUsed     time.Time
	Execution    *ExecutionRuntime
	Decisions    *DecisionService
	// Provider, Model, Mode, and ThinkingLevel are session-owned bindings used by
	// BuildAgent when adapters omit overrides. Providers contains the selectable
	// catalog and allows ACP sessions to switch credentials/models in-process.
	Provider              provider.Provider
	ProviderName          string
	Providers             ProviderCatalog
	Model                 *provider.Model
	Mode                  string
	ThinkingLevel         provider.ThinkingLevel
	AdditionalDirectories []string
	SandboxEnabled        bool
	BrowserEnabled        bool
	WebSearchEnabled      bool
	// 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) AcceptInput added in v1.2.96

func (r *SessionRuntime) AcceptInput(ctx context.Context, runID, text string, ingresses []InputIngress) (InputSubmission, error)

AcceptInput materializes every ephemeral resource and returns the canonical submission shape consumed by Agent Core.

func (*SessionRuntime) AcceptProviderAttachment added in v1.2.96

func (r *SessionRuntime) AcceptProviderAttachment(ctx context.Context, runID string, p provider.Provider, attachment provider.Attachment) (SessionAttachment, error)

AcceptProviderAttachment materializes a provider-declared output attachment into the same private session store used for inbound media. A URL or a filename alone is never an artifact: the provider must expose an authorized resolver for its opaque reference.

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) AttachPreparedInput added in v1.2.96

func (r *SessionRuntime) AttachPreparedInput(ctx context.Context, text string, resources []PreparedInput) (InputSubmission, error)

AttachPreparedInput validates staged Runtime resources and returns the canonical submission without copying or reconstructing adapter content.

func (*SessionRuntime) BeginArtifactCollection added in v1.2.96

func (r *SessionRuntime) BeginArtifactCollection(runID string) (*ArtifactCollector, error)

BeginArtifactCollection installs the Runtime-owned publication tool for one run. The caller must Close the collection after the Agent stream reaches a terminal state. It deliberately has no adapter-specific behavior.

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) BuildUserMessage added in v1.2.96

func (r *SessionRuntime) BuildUserMessage(ctx context.Context, input InputSubmission) (provider.Message, error)

BuildUserMessage emits only text plus a deterministic project-path manifest. It never reads input bytes or constructs provider image/file blocks.

func (*SessionRuntime) CapabilitySnapshot added in v1.2.95

func (r *SessionRuntime) CapabilitySnapshot() (sandboxEnabled, browserEnabled, webSearchEnabled bool)

CapabilitySnapshot returns the mutable session capabilities used by the shared config-options contract.

func (*SessionRuntime) CleanupInputResources added in v1.2.96

func (r *SessionRuntime) CleanupInputResources(ctx context.Context, now time.Time) (int, error)

CleanupInputResources runs the Runtime-owned draft/missing reconciliation.

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

ConfigSnapshot returns the current session configuration atomically.

func (*SessionRuntime) ConfigureCapabilities added in v1.2.95

func (r *SessionRuntime) ConfigureCapabilities(sandboxEnabled, browserEnabled, webSearchEnabled bool) error

ConfigureCapabilities applies adapter-selected defaults and replays the persisted browser/web-search capability state when a session has one.

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 initial per-session provider, model, mode, and 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) DiscardInput added in v1.2.96

func (r *SessionRuntime) DiscardInput(ctx context.Context, input InputSubmission)

DiscardInput removes only unbound Runtime resources in a submission. It is intended for adapter admission failures and is safe to retry.

func (*SessionRuntime) PrepareInput added in v1.2.96

func (r *SessionRuntime) PrepareInput(ctx context.Context, ingress InputIngress) (PreparedInput, error)

PrepareInput stages one resource before a Run exists, as used by editors and clipboard UIs. The resulting ID/path is the only state an adapter retains.

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) SetCapabilityOption added in v1.2.95

func (r *SessionRuntime) SetCapabilityOption(id string, enabled bool) error

SetCapabilityOption persists and applies one boolean session capability.

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 SessionStopCode added in v1.2.96

type SessionStopCode string

SessionStopCode is the adapter-neutral outcome of a stop request. Adapters map it to their protocol status without reimplementing ownership decisions.

const (
	SessionStopAccepted          SessionStopCode = "stop_accepted"
	SessionStopRemoteAccepted    SessionStopCode = "remote_stop_accepted"
	SessionStopRecoveryStarted   SessionStopCode = "recovery_started"
	SessionStopOwnedElsewhere    SessionStopCode = "session_run_owned_elsewhere"
	SessionStopRemoteUnsupported SessionStopCode = "remote_stop_unsupported"
	SessionStopReserved          SessionStopCode = "session_reserved"
	SessionStopNoActiveRun       SessionStopCode = "no_active_run"
	SessionStopStateUnavailable  SessionStopCode = "session_execution_state_unavailable"
	SessionStopRecoveryFailed    SessionStopCode = "session_recovery_failed"
	SessionStopRemoteFailed      SessionStopCode = "remote_stop_failed"
	SessionStopTargetChanged     SessionStopCode = "session_run_target_changed"
)

type SessionStopOptions added in v1.2.96

type SessionStopOptions struct {
	// ExpectedRunID scopes a stop request to the Run selected by the caller.
	// Runtime revalidates it before every local, remote, or orphan transition so
	// a stale Run API request cannot cancel a newer Run in the same Session.
	ExpectedRunID           string
	RemoteCancel            func(context.Context, RemoteStopRequest) error
	BeforeOrphanTerminalize func(session.SessionRun) error
	// LegacyLocalCancel is a migration bridge for embedded adapters that still
	// have a process-local run but no durable session_runs row. Runtime invokes
	// it only after the canonical snapshot proves that no durable Run exists;
	// it must never be used to override a durable or externally-owned Run.
	LegacyLocalCancel func() bool
}

SessionStopOptions supplies protocol/provider hooks while retaining all Run/lease ownership decisions in the shared Runtime.

type SessionStopResult added in v1.2.96

type SessionStopResult struct {
	Code      SessionStopCode          `json:"code"`
	Execution SessionExecutionSnapshot `json:"execution"`
}

SessionStopResult is returned for both accepted and rejected requests so an adapter can immediately project the latest canonical execution snapshot.

func RequestSessionStop added in v1.2.96

func RequestSessionStop(ctx context.Context, sessionDir, sessionID string, options SessionStopOptions) (SessionStopResult, error)

RequestSessionStop applies the canonical stop matrix. Snapshot data is an expectation only: local cancellation and recovery revalidate the exact Run/lease binding before making a durable change.

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

type ToolCallPolicyDecision struct {
	Block  bool
	Reason string
}

ToolCallPolicyDecision is the source policy result for one tool call.

Jump to

Keyboard shortcuts

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