agentruntime

package
v1.3.105-pre-4 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 50 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	DecisionStatusPending   = "pending"
	DecisionStatusRequested = "requested"
	DecisionStatusResolved  = "resolved"
	DecisionStatusCancelled = "cancelled"
	DecisionStatusTimedOut  = "timed_out"
)

Decision statuses recorded in the durable ledger.

View Source
const (
	KnowledgeIndexPhaseScanning   = "scanning"
	KnowledgeIndexPhaseIndexing   = "indexing"
	KnowledgeIndexPhaseEnriching  = "enriching"
	KnowledgeIndexPhaseCommitting = "committing"
)

Knowledge indexing phases projected to management surfaces. They describe where a background scan currently is; callers poll them periodically and never block a transport while a scan runs.

View Source
const (
	// MaintenanceStorageReconcileSchedule reclaims unreferenced attachment
	// storage once a day. Reclamation is already age-bounded by the attachment
	// retention window, so a daily pass is enough to keep a long-running host
	// from accumulating bytes it can no longer address, and frequent passes would
	// only add directory walks.
	MaintenanceStorageReconcileSchedule = "@daily"
	// MaintenanceStorageReconcileJobName labels the projected job for logs and
	// direct store inspection.
	MaintenanceStorageReconcileJobName = "Reclaim unreferenced attachment storage"
)
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"
	// ConfigOptionExpert selects the Runtime-owned expert bundle for a
	// session. Replacing one non-empty value is deliberately rejected by
	// SetExpert; adapters must create a fork with ForkWithExpert instead.
	ConfigOptionExpert = "expert"
)

SessionConfigOption IDs are stable protocol-neutral identifiers.

View Source
const (
	WorktreeEventPending = "pending"
	WorktreeEventReady   = "ready"
	WorktreeEventFailed  = "failed"
	WorktreeEventRemoved = "removed"
)

Worktree lifecycle event types. They describe the managed worktree resource, never a run terminal state.

View Source
const DefaultDeliveryRetryWindow = 10 * time.Minute

DefaultDeliveryRetryWindow bounds how long a transient delivery failure keeps being retried. Platform transports can be disconnected or rate-limited for minutes, and a small attempt count would abandon the reply long before that.

View Source
const (
	DefaultTerminalPersistenceTimeout = 10 * time.Second
)
View Source
const KnowledgeBaseCronJobPrefix = "knowledge-base-index:"

KnowledgeBaseCronJobPrefix namespaces scheduled reindex jobs inside the shared cron store. The store is keyed only by sessionDir, so every scheduler process (ACP, serve) can claim a namespaced job; each must route it through RunKnowledgeBaseCronJob instead of executing the job prompt as an ordinary agent run inside the knowledge source directory.

View Source
const MaintenanceCronJobPrefix = "mothx-maintenance:"

MaintenanceCronJobPrefix namespaces Runtime-owned maintenance jobs inside the shared cron store. The scheduler claims and completes them exactly like any other job (same claim, stale-recovery, status, and next-run lifecycle), but their work is executed by the Runtime instead of an agent prompt, so no adapter can turn maintenance into a scheduled model run.

These jobs carry no session ID, which keeps them out of every session-scoped cron listing and out of the cron tool: they are host maintenance, not user tasks the front-ends should offer to edit.

Variables

View Source
var (
	ErrSubmissionLocalBusy    = errors.New("session has a local execution in progress")
	ErrSubmissionExternalBusy = errors.New("session execution is owned elsewhere")
	ErrSubmissionClosed       = errors.New("session submission coordinator is closed")
	ErrSubmissionCancelled    = errors.New("session submission was cancelled")
)
View Source
var ErrDetachedRemoteExecution = errors.New("session has a recoverable detached remote execution")
View Source
var ErrExpertSwitchRequiresFork = errors.New("switching an expert requires a session fork")

ErrExpertSwitchRequiresFork preserves identity/history boundaries: replacing one non-empty expert binding with another must create a forked session. Binding a fresh session and unbinding an existing one remain supported.

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 ErrKnowledgeIndexerModelUnavailable = errors.New("knowledge base indexer model is unavailable")

ErrKnowledgeIndexerModelUnavailable marks an index pass that could not build the configured Indexer provider/model. Management surfaces map it to the stable knowledge_base_model_unavailable code instead of leaking the raw provider error text.

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

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. A busy lease still held by this process for an execution that already selected its terminal state is draining, not contended: admission waits for the Runtime-owned terminal persistence to release it (bounded by ctx) so a queued same-process successor keeps the session in this process instead of failing with a misleading cross-process busy error.

func AcquireExecutionSubmission added in v1.3.105

func AcquireExecutionSubmission(ctx context.Context, sessionDir, sessionID, runID string, waitForExternal bool) (func(), error)

AcquireExecutionSubmission is the synchronous adapter bridge for background executions that already own their Agent/Run lifecycle. The coordinator owns FIFO ordering, lease admission, external ownership waiting, and release; the caller only runs its existing durable execution between the returned admission and release functions.

func AcquireSessionMutation

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 AcquireSessionMutationUnlessHeld added in v1.3.103

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

AcquireSessionMutationUnlessHeld acquires the shared mutation lease unless this process already holds a live lease for the session (for example an in-run administrative patch): the held lease already fences the durable writes, and a second acquisition would trip the process-local lock with a false busy. A nil guard with a nil error means "proceed under the already-held lease"; the caller must release a non-nil guard.

func AnnotateDurableRunError

func AnnotateDurableRunError(ctx context.Context, sessionDir, runID, errMsg string) (bool, error)

AnnotateDurableRunError records a terminal error reason on a canonical Run row that reached a terminal status without one, for example a background run abandoned after interrupted tool execution whose finalizer could no longer persist the reason. It never changes the run status, never revives a terminal run, and is a no-op when the run is missing, still active, or already carries an error. It reports whether the annotation was applied.

func ArtifactReclaimFloor

func ArtifactReclaimFloor(policy AttachmentPolicy, now time.Time) time.Time

ArtifactReclaimFloor returns the modification time an unreferenced artifact directory must predate before ReconcileArtifactStorage may reclaim it. It is exported so a caller can state the rule it applied instead of restating the retention and grace window the Runtime owns.

func ArtifactStorageDirectoryName

func ArtifactStorageDirectoryName() string

ArtifactStorageDirectoryName returns the session-directory subtree that holds Runtime-private attachment content. It is exported so a caller can label what a reset left behind without duplicating the layout rule this package owns.

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 DecisionEventEnvelope

func DecisionEventEnvelope(record DecisionRecord) map[string]any

DecisionEventEnvelope is the minimal durable decision envelope: the record under the canonical key. Writers that persist only a decision use it directly; DecisionEventFields adds an adapter payload.

func DecisionEventFields

func DecisionEventFields(record DecisionRecord, payload any) map[string]any

DecisionEventFields is the canonical durable decision envelope. record is the Runtime-owned identity and payload is the optional adapter protocol body.

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 DeleteSessionWithMutation

func DeleteSessionWithMutation(sessionDir, id string, guard *session.RuntimeLeaseGuard) error

DeleteSessionWithMutation removes a session while the caller already holds its shared mutation lease. It is the multi-session counterpart of DeleteSession and keeps cascade deletion on the same Runtime-owned lifecycle without reacquiring a process-local lock.

func DeliveryFailureRetryable

func DeliveryFailureRetryable(failureCode string) bool

DeliveryFailureRetryable reports whether a failed delivery operation may be reopened for another retry window (reconnect recovery or an explicit operator retry). The canonical definition lives in dao.TransientDeliveryFailureCodes, which also backs the ReopenTransientFailure SQL fence, so the operator entry cannot authorize a reopen the persistence guard would refuse.

func DeliveryOperationText

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

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

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

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

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

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 InspectExpert

func InspectExpert(workDir, expertID string) (*expert.Bundle, error)

InspectExpert loads one bundle for Runtime consumers that need a display or validation preflight. Binding still belongs exclusively to SetExpert or ForkWithExpert; this function deliberately has no persistence side effect.

func InspectSessionExecutions added in v1.3.103

func InspectSessionExecutions(sessionDir string, sessionIDs []string) map[string]SessionExecutionSnapshot

InspectSessionExecutions projects the canonical execution state for a bounded batch of sessions, intended for adapter list/page views (TUI session dialog, ACP session list). Sessions whose facts cannot be read are omitted so one unreadable session degrades to "no badge" instead of failing the whole listing; adapters must treat a missing entry as unknown, never idle.

func IsMaintenanceCronJobID

func IsMaintenanceCronJobID(jobID string) bool

IsMaintenanceCronJobID reports whether a persisted job belongs to the maintenance namespace and therefore must be executed by RunMaintenanceCronJob.

func IsValidMode

func IsValidMode(mode string) bool

IsValidMode reports whether mode is one of the public execution modes.

func KnowledgeBaseCronJobID

func KnowledgeBaseCronJobID(knowledgeBaseID string) string

KnowledgeBaseCronJobID derives the shared cron identity of one knowledge base's reindex schedule.

func KnowledgeBaseIDFromCronJobID

func KnowledgeBaseIDFromCronJobID(jobID string) (string, bool)

KnowledgeBaseIDFromCronJobID extracts the knowledge base identity from a namespaced cron job ID.

func KnowledgeLibrarianSessionID

func KnowledgeLibrarianSessionID(baseID, rootDir string) string

KnowledgeLibrarianSessionID derives the deterministic dedicated-session identity for one knowledge base. It is exported so cross-package contract tests can pin the derivation that index/librarian Run provenance and same-base admission mutual exclusion depend on.

func ListExperts

func ListExperts(workDir string) []expert.Summary

ListExperts is the front-end-neutral discovery boundary for a work directory. It does not mutate a session or construct an Agent, so adapters can render an expert picker before a user chooses a binding.

func ListLatestDurableRunsBySessions

func ListLatestDurableRunsBySessions(ctx context.Context, sessionDir string, sessionIDs []string) (map[string]session.SessionRun, error)

ListLatestDurableRunsBySessions loads the most recent canonical Run row per session as a read-only projection keyed by session ID. Sessions without any Run are absent from the result. Like GetDurableRun, this is an inspection boundary for adapters (for example ACP session/list lastRun status); durable lifecycle writes remain owned by ExecutionRuntime/RunStore.

func MaintenanceStorageReconcileJobID

func MaintenanceStorageReconcileJobID() string

MaintenanceStorageReconcileJobID is the stable identity of the attachment storage reconciliation job.

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

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 RecordDecisionEvent

func RecordDecisionEvent(sink RunEventSink, t DecisionTransition) (string, error)

RecordDecisionEvent persists a transition through sink. A nil sink is a no-op.

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 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 ResolveIterationBudget

func ResolveIterationBudget(policy agent.IterationBudgetPolicy, soft int) agent.IterationBudgetPolicy

ResolveIterationBudget returns the normalized iteration-budget policy for a run whose soft iteration limit is soft. It is the single owner of the budget defaults (hard = 2x soft, two renewals, minimum interval = soft/10, 16h wall clock); adapters only supply the soft limit (MaxIterations/MaxTurns) and may pre-set IterationBudget to override the defaults. The result is always enabled.

func ResolveUnattendedMode

func ResolveUnattendedMode(sessionMode string) string

ResolveUnattendedMode derives the execution mode for unattended derived runs such as ESM role sub-agents. Unattended runs must never stop on interactive approval, so only os is inherited from the session mode and every other session mode (plan/agent/yolo/empty/unknown) falls back to yolo. Hard high-risk-command protections remain mode-independent.

func RunKnowledgeBaseCronJob

func RunKnowledgeBaseCronJob(ctx context.Context, service *KnowledgeBaseService, jobID string) (bool, string, error)

RunKnowledgeBaseCronJob wakes one namespaced reindex through the same background job machinery as manual scans, so Cron only records the scheduling outcome while the canonical durable Run stays Runtime-owned. It reports handled=false for job IDs outside the knowledge namespace so a shared scheduler falls back to its own execution path. Passing the process-wide cached service keeps scheduled scans deduplicated against manual scans and visible to progress polling.

func RunMaintenanceCronJob

func RunMaintenanceCronJob(ctx context.Context, sessionDir, jobID string, policy MaintenancePolicy) (bool, string, error)

RunMaintenanceCronJob executes one namespaced maintenance job against a session directory and reports the outcome as a cron job response.

It always claims any ID inside the maintenance namespace, including ones it does not recognize: an unknown maintenance job must fail with a status instead of falling through to the ordinary agent path, where its prompt would be run as a model turn. handled is false only for job IDs outside the namespace, so a shared scheduler can keep routing its other work.

func SessionHasTeamExpert

func SessionHasTeamExpert(workDir string, manager *session.Manager) bool

SessionHasTeamExpert reports whether the session's persisted expert binding resolves to a valid team bundle. Adapters call this at registry construction time, before a SessionRuntime exists; BuildAgent and NewAgentManager still resolve the authoritative binding once the runtime is assembled. Resolution failures report false here: an invalid or missing bundle is surfaced as a hard error by the runtime assembly path, never silently tolerated there.

func SubAgentToolsEnabled

func SubAgentToolsEnabled(rt *SessionRuntime, requested bool) bool

SubAgentToolsEnabled is the runtime-owned predicate for registering the sub-agent tool set: the adapter-requested capability OR a team expert binding forcing it. Adapters must call this instead of checking their own flag so expert sessions get identical tools on every entry point.

func SynchronizeToolGroups

func SynchronizeToolGroups(rt *SessionRuntime, registry *tools.Registry, policy ToolGroupPolicy, manager *agent.AgentManager)

SynchronizeToolGroups reconciles the registry's optional tool groups against the policy and the current AgentManager. It is idempotent and owns the whole lifecycle: installing a group, removing a disabled group, re-installing after a manager replacement (so tool instances always reference the current manager), and trimming per-tool selections that an ordinary multi-agent session switched off. A nil manager (or runtime with no team binding) removes every group tool.

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

func ValidateThinkingLevel(value string) (provider.ThinkingLevel, error)

ValidateThinkingLevel validates a config option value without making provider-specific assumptions.

func ValidateWorkDir added in v1.3.105

func ValidateWorkDir(workDir string) (string, error)

ValidateWorkDir verifies that a Runtime session is bound to a directory that exists now. A session header is a durable fact: accepting a deleted path at creation or rebinding time would persist an unusable session and defer the failure to unrelated tools, MCP setup, or a later prompt.

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
	// IterationBudget overrides the Runtime-resolved iteration-budget policy for
	// this build. The zero value uses the policy resolved by the SessionRuntime
	// (source-aware defaults); only a conversational lead receives renewal.
	IterationBudget      agent.IterationBudgetPolicy
	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
	// AuxiliaryRole marks a build that is not the session's conversational lead
	// even though it runs on the session's own manager (the legacy knowledge
	// librarian query bridge). Such a build never receives the team member
	// mailbox hooks: it must not wait for the session's members nor consume
	// member notifications that belong to the lead.
	AuxiliaryRole bool
}

AgentBuildOptions are per-run inputs supplied by an adapter after Runtime has resolved its source, policy, session resources, and effective mode.

func AgentBuildOptionsFromConfig

func AgentBuildOptionsFromConfig(cfg agent.Config) AgentBuildOptions

AgentBuildOptionsFromConfig converts the legacy Agent.Config shape used by provider-specific drivers into Runtime-owned build inputs.

type AgentEventObservation

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
	// Worktree, when set, lets sub-agents run in an on-demand isolated worktree
	// (tool parameter or member declaration). WorktreePerChild additionally makes
	// every sub-agent get its own worktree (policy trigger).
	Worktree         *WorktreeManager
	WorktreePerChild bool
}

AgentManagerOptions binds provider-specific execution dependencies to a shared SessionRuntime. Adapter-specific event and approval handling remains outside this type.

type ArtifactCollector

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

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

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

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.

func (*ArtifactCollector) SetObserver

func (c *ArtifactCollector) SetObserver(observer func(SessionAttachment))

SetObserver installs an optional adapter projection hook. The observer is called with each artifact record after it has been successfully copied and persisted, so projections never announce content that does not exist. It is additive and nil-safe: a nil observer removes any previously installed hook, and an observer panic is contained so it can never affect the registration flow that owns the durable artifact state.

type ArtifactReconciliation

type ArtifactReconciliation struct {
	// Scanned counts the entries found directly under the artifact store.
	Scanned int
	// Removed counts the directories reclaimed in this pass.
	Removed int
	// Freed is the total size of the reclaimed content.
	Freed int64
	// SkippedReferenced counts directories a durable row still claims.
	SkippedReferenced int
	// SkippedYoung counts unreferenced directories still inside the retention
	// plus grace floor.
	SkippedYoung int
	// SkippedUnrecognized counts entries that are not artifact storage this
	// function may interpret - an unexpected name, a file, or a symlink.
	SkippedUnrecognized int
	// AgeFloor is the modification time a directory must be older than to be
	// reclaimable. It is reported so callers can state the rule they applied.
	AgeFloor time.Time
}

ArtifactReconciliation reports one private-store reconciliation pass. The counters are deliberately explicit: an operator has to be able to tell "the store was already clean" apart from "everything was too young to reclaim".

func ReconcileArtifactStorage

func ReconcileArtifactStorage(ctx context.Context, sessionDir string, policy AttachmentPolicy, now time.Time) (ArtifactReconciliation, error)

ReconcileArtifactStorage reclaims artifact directories that no durable attachment row references any more and that are already past retention plus the grace window. Orphans reach this state through three independent paths - an intake whose row write failed after its content was committed, a session deletion (which removes rows only), and a sessions database that was archived away by `mothx pure` - and none of them is visible to the row-driven expiry path, which is why a directory-driven pass is needed beside it.

It fails closed: an unreadable or missing sessions database returns an error and deletes nothing, because an empty reference set is indistinguishable from a store whose every object is orphaned. Only plain directories named like a generated attachment ID, containing only regular files, are ever considered.

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
	// Settings and capability flags describe the shared resource assembly policy
	// for this compatibility bridge. When present, AttachSessionResources uses
	// them to reload context/skills with the persisted expert package included.
	Settings        *config.Settings
	Workflows       bool
	Browser         bool
	ArtifactEnabled bool
}

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

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

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

func DefaultAttachmentPolicy() AttachmentPolicy

type AttachmentService

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

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

func (*AttachmentService) CleanupExpired

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

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

Get returns one attachment record belonging to sessionID.

func (*AttachmentService) Open

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

func (s *AttachmentService) Policy() AttachmentPolicy

func (*AttachmentService) ReconcileStorage

func (s *AttachmentService) ReconcileStorage(ctx context.Context, now time.Time) (ArtifactReconciliation, error)

ReconcileStorage runs the private-store reconciliation for this service's own session directory under its own policy. Adapters call it to report or reclaim; they never walk the store themselves.

func (*AttachmentService) SetStatus

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
	ArtifactEnabled bool
	RegistryHooks   []RegistryHook
	// MCP controls how configured MCP servers are connected during build. The
	// zero value preserves strict, synchronous connection; an interactive entry
	// point defers it so a slow server cannot freeze first paint.
	MCP MCPConnectPolicy
}

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.

func LoadContextResourcesWithExpert

func LoadContextResourcesWithExpert(settings *config.Settings, workDir string, workflows, browserEnabled bool, expertBundle *expert.Bundle) (*ContextResources, error)

LoadContextResourcesWithExpert additionally loads skills packaged with a resolved expert bundle. Expert skills are session-scoped Runtime resources: they shadow ordinary project/global skills of the same name without creating an adapter-owned skills path. Embedded bundles are read directly from their fs.FS, so packaged binaries do not depend on a source checkout.

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 CreateWorktreeRequest added in v1.3.103

type CreateWorktreeRequest struct {
	BaseCwd      string
	Name         string
	Detached     bool
	StartCommand string
	ProjectID    string
}

CreateWorktreeRequest describes an on-demand worktree creation.

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 DecodeDecisionEvent

func DecodeDecisionEvent(ev session.SessionRunEvent) (DecisionRecord, bool)

DecodeDecisionEvent decodes a run event that belongs to the decision ledger, defaulting session/run identity from the persisted row. ok is false for unrelated events or a malformed envelope.

func ExpiredDecisions

func ExpiredDecisions(records []DecisionRecord, now time.Time) []DecisionRecord

func LoadDecisionRecords

func LoadDecisionRecords(sessionDir, sessionID string) ([]DecisionRecord, error)

LoadDecisionRecords returns the decoded decision ledger for a session in durable order.

func LoadDecisionRecordsContext

func LoadDecisionRecordsContext(ctx context.Context, sessionDir, sessionID string) ([]DecisionRecord, error)

LoadDecisionRecordsContext is the cancellable form used by recovery paths.

func LoadRunDecisionRecords

func LoadRunDecisionRecords(sessionDir, sessionID, runID string) ([]DecisionRecord, error)

LoadRunDecisionRecords returns the decision ledger for a single run. An empty runID returns the whole session ledger.

func LoadRunDecisionRecordsContext

func LoadRunDecisionRecordsContext(ctx context.Context, sessionDir, sessionID, runID string) ([]DecisionRecord, error)

LoadRunDecisionRecordsContext is the cancellable form used by recovery paths.

func NewDecisionRecord

func NewDecisionRecord(request DecisionRequest, status, value string, payload any, expiresAt time.Time) (DecisionRecord, error)

NewDecisionRecord is the single owner of the request/resolution record shape: a pending status becomes a request record carrying the optional deadline, any other status a resolution record.

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 DecisionTransition

type DecisionTransition struct {
	Request   DecisionRequest
	Status    string
	Value     string
	Payload   any
	ExpiresAt time.Time
	Source    string
	Model     string
	Mode      string
}

DecisionTransition is one durable decision state change.

type DeliveryCapability

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

type DeliveryCoordinator struct {
	SessionDir string
	Owner      string
	Lease      time.Duration
	// RetryWindow is the wall-clock budget for transient failures. Zero uses
	// DefaultDeliveryRetryWindow.
	RetryWindow time.Duration
	// MaxRetries is an optional hard attempt cap in addition to RetryWindow.
	// Zero disables it (the window is the production bound).
	MaxRetries int
}

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

func NewDeliveryCoordinator

func NewDeliveryCoordinator(sessionDir, owner string) *DeliveryCoordinator

func (*DeliveryCoordinator) Claim

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

func (*DeliveryCoordinator) Complete

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

func (*DeliveryCoordinator) Progress

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

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

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

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

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

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

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

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

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

type DurableConversationTurnFinisher

type DurableConversationTurnFinisher interface {
	FinishConversationTurn(DurableRun, RunState, string) error
}

type DurableConversationTurnStore

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

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

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 ExecutionCompletion added in v1.3.105

type ExecutionCompletion struct {
	SubmissionID string
	RunID        string
	Error        error
}

type ExecutionHandle added in v1.3.105

type ExecutionHandle struct {
	SubmissionID string
	RunID        string
	Completed    <-chan ExecutionCompletion
	Events       <-chan SubmissionEvent
	// contains filtered or unexported fields
}

func (*ExecutionHandle) Cancel added in v1.3.105

func (h *ExecutionHandle) Cancel()

Cancel cancels a queued submission or requests cancellation of an active runner. The runner remains responsible for its durable terminal transition.

func (*ExecutionHandle) State added in v1.3.105

func (h *ExecutionHandle) State() SubmissionState

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
	// IterationBudget governs model-requested iteration renewal for this run's
	// conversational lead. It is resolved once together with the source/mode
	// policy so agent construction, run records, and UI projections share one
	// budget. The zero value resolves to the Runtime defaults when a run is built
	// (see ResolveIterationBudget); renewal is a lead-only capability, so
	// sub-agents and team members keep their capability ceiling.
	IterationBudget agent.IterationBudgetPolicy
}

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) Completion added in v1.3.105

func (r *ExecutionRuntime) Completion(runID string) <-chan struct{}

Completion returns the Runtime-owned completion barrier for runID. The channel closes only after the durable terminal transition, local execution deregistration, and retained lease release have completed. Adapters may use it for projection sequencing but must not use Agent terminal events as an admission signal.

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

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

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

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

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 ExpertBinding

type ExpertBinding struct {
	ID   string // expert bundle name (= session header expertId)
	Type string // expert.TypeAgent | expert.TypeTeam
	// Team is true for team-type bindings; it forces multi-agent capability
	// for the session (single resolution, adapters may not downgrade).
	Team           bool
	Bundle         *expert.Bundle
	IdentityPrompt string
	RosterPrompt   string
	MemberDefs     []*agent.MemberDef
}

ExpertBinding is the resolved expert identity of one session. It is owned by SessionRuntime, resolved once from the persisted session header binding, and consumed by BuildAgent/NewAgentManager so every adapter shares the same identity prompt, roster, member definitions, and team capability decision.

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

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

type ForkResult = session.ForkResult

func Fork

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.

func ForkWithExpert

func ForkWithExpert(ctx context.Context, sessionDir string, options ForkOptions, expertID string) (ForkResult, error)

ForkWithExpert is the Runtime-owned expert switch operation. It preserves the source session's identity and history while applying expertID only to the child branch; an empty expertID deliberately creates an unbound child.

type InputIngress

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

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

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

func (*InputMaterializer) Cleanup

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

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

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

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

func (*InputMaterializer) Prepare

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

type InputPolicy struct {
	MaxImageBytes  int64
	MaxFileBytes   int64
	MaxImagePixels int64
	// MaxInlineMediaBytes caps the audio/video payload BuildUserMessage may
	// inline into a provider request. Larger media stay workspace files with a
	// manifest note because OpenAI-compatible base64 media inputs are limited
	// (Qwen-Omni accepts at most a 10MB base64 payload).
	MaxInlineMediaBytes 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

func DefaultInputPolicy() InputPolicy

type InputResource

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

func (r InputResource) Prepared() PreparedInput

type InputStream

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

type InputSubmission struct {
	Text                    string
	Resources               []PreparedInput
	KnowledgeBaseReferences []KnowledgeBaseReference
	KnowledgeCapsules       []KnowledgeCapsule
	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

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 KnowledgeBaseIndexPolicy

type KnowledgeBaseIndexPolicy struct {
	MaxFiles      int
	MaxFileBytes  int64
	MaxChunkBytes int
}

KnowledgeBaseIndexPolicy is intentionally deterministic. LLM-based graph enrichment is a later Runtime step; this policy first guarantees a local, reproducible file/chunk/graph snapshot that no adapter needs to rebuild.

func DefaultKnowledgeBaseIndexPolicy

func DefaultKnowledgeBaseIndexPolicy() KnowledgeBaseIndexPolicy

type KnowledgeBaseProviderFactory

type KnowledgeBaseProviderFactory func(*config.Settings, string, string) (provider.Provider, *provider.Model, error)

KnowledgeBaseProviderFactory creates the configured provider/model for an optional Indexer role. It keeps provider construction in Runtime and makes the graph-enrichment path deterministic to test without an adapter-owned provider builder.

type KnowledgeBaseReference

type KnowledgeBaseReference struct {
	KnowledgeBaseID string `json:"knowledgeBaseId"`
	Required        bool   `json:"required,omitempty"`
}

KnowledgeBaseReference is the front-end-neutral input reference to one Desktop-managed knowledge base. Adapters pass only this ID and dependency preference; Runtime resolves snapshots, graph hits and source excerpts.

type KnowledgeBaseService

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

KnowledgeBaseService is Runtime-owned indexing and graph-query plumbing for Desktop-configured directory knowledge bases. It contains no Desktop UI, ACP protocol or provider-message construction.

func NewKnowledgeBaseService

func NewKnowledgeBaseService(sessionDir string, policy KnowledgeBaseIndexPolicy) (*KnowledgeBaseService, error)

func NewKnowledgeBaseServiceWithProviderFactory

func NewKnowledgeBaseServiceWithProviderFactory(sessionDir string, policy KnowledgeBaseIndexPolicy, settings *config.Settings, factory KnowledgeBaseProviderFactory) (*KnowledgeBaseService, error)

NewKnowledgeBaseServiceWithProviderFactory is the testable constructor for Runtime-owned provider selection. Production callers should use NewKnowledgeBaseServiceWithSettings.

func NewKnowledgeBaseServiceWithSettings

func NewKnowledgeBaseServiceWithSettings(sessionDir string, policy KnowledgeBaseIndexPolicy, settings *config.Settings) (*KnowledgeBaseService, error)

NewKnowledgeBaseServiceWithSettings enables the configured Indexer Agent role. Directory scanning and graph persistence remain the same Runtime service regardless of whether enrichment is enabled.

func (*KnowledgeBaseService) ClearIndex added in v1.3.103

func (s *KnowledgeBaseService) ClearIndex(ctx context.Context, knowledgeBaseID string) error

ClearIndex removes the active snapshot and graph rows, keeping configuration and the source directory.

func (*KnowledgeBaseService) Index

func (s *KnowledgeBaseService) Index(ctx context.Context, knowledgeBaseID string) (session.KnowledgeSnapshot, error)

func (*KnowledgeBaseService) IndexDurable

func (s *KnowledgeBaseService) IndexDurable(ctx context.Context, knowledgeBaseID string, source RuntimeSource) (session.KnowledgeSnapshot, error)

IndexDurable performs one scan/index pass under the canonical durable Run lifecycle. The maintenance Run belongs to the same dedicated knowledge-base role session used by the Librarian Agent and has no conversation turn. When a provider/model is configured, its bounded Indexer Agent runs inside this same durable Run after deterministic extraction. SourceCron is used for scheduled scans; SourceACP is used by explicit Desktop management scans.

func (*KnowledgeBaseService) IndexDurableWithProgress

func (s *KnowledgeBaseService) IndexDurableWithProgress(ctx context.Context, knowledgeBaseID string, source RuntimeSource, job *KnowledgeIndexJob) (session.KnowledgeSnapshot, error)

IndexDurableWithProgress behaves like IndexDurable but reports scan/index progress into job while the pass runs. It is the entry point used by background scans; interactive callers return before the pass completes.

func (*KnowledgeBaseService) IndexJob

func (s *KnowledgeBaseService) IndexJob(knowledgeBaseID string) (*KnowledgeIndexJob, bool)

IndexJob returns the current (or most recent) index job for a base.

func (*KnowledgeBaseService) IndexProgress

func (s *KnowledgeBaseService) IndexProgress(knowledgeBaseID string) (KnowledgeIndexProgress, bool)

IndexProgress reports the live progress of a running scan, if any.

func (*KnowledgeBaseService) IndexRun added in v1.3.103

func (s *KnowledgeBaseService) IndexRun(ctx context.Context, knowledgeBaseID, runID string) (KnowledgeIndexRun, error)

IndexRun loads one index attempt scoped to its knowledge base. It returns ErrKnowledgeBaseUnindexed when the Run is unknown or is not an index Run for this base.

func (*KnowledgeBaseService) IndexRuns added in v1.3.103

func (s *KnowledgeBaseService) IndexRuns(ctx context.Context, knowledgeBaseID string, limit int) ([]KnowledgeIndexRun, error)

IndexRuns projects recent index attempts for one knowledge base from its canonical durable Runs, newest first.

func (*KnowledgeBaseService) IndexWithRun

func (s *KnowledgeBaseService) IndexWithRun(ctx context.Context, knowledgeBaseID, runID string) (session.KnowledgeSnapshot, error)

IndexWithRun builds and commits the deterministic graph baseline. The durable IndexDurable path may enrich that graph with separately verified Agent-selected links before committing it.

func (*KnowledgeBaseService) LibrarianCapsule

func (s *KnowledgeBaseService) LibrarianCapsule(ctx context.Context, caller *SessionRuntime, base session.KnowledgeBase, graph session.KnowledgeGraphQuery, question string, budget int) (KnowledgeCapsule, error)

LibrarianCapsule asks the knowledge base's configured ordinary Agent role to distill indexed evidence for one caller question. The Agent receives its own durable Run and a dedicated session rooted at the knowledge base directory; it never shares the caller's conversation or execution lease.

A base without a provider/model remains on the deterministic graph capsule path. That preserves existing knowledge bases created before the Librarian configuration was introduced, while every configured base uses this normal Agent execution path.

func (*KnowledgeBaseService) Query

func (s *KnowledgeBaseService) Query(ctx context.Context, knowledgeBaseID, query string, limit int) (session.KnowledgeGraphQuery, error)

func (*KnowledgeBaseService) SetSettings

func (s *KnowledgeBaseService) SetSettings(settings *config.Settings)

SetSettings replaces the settings snapshot used to resolve the optional Indexer role. A management surface that caches one service for the process calls it when settings.json changes, so a later scan uses the new provider/model without losing the in-flight background job registry. The stored value is a private copy and the previous copy is never mutated, so a concurrent reader may keep the pointer it already obtained.

func (*KnowledgeBaseService) Sources added in v1.3.103

func (s *KnowledgeBaseService) Sources(ctx context.Context, knowledgeBaseID string) ([]session.KnowledgeSource, error)

Sources projects the active snapshot's file-level provenance.

func (*KnowledgeBaseService) StartIndex

func (s *KnowledgeBaseService) StartIndex(ctx context.Context, knowledgeBaseID string, source RuntimeSource) (*KnowledgeIndexJob, error)

StartIndex launches (or reuses) the background index job for one knowledge base and returns immediately. Validation of the base happens synchronously because it is inexpensive; the scan itself never runs on the caller's goroutine. Concurrent starts for the same base share one job, and any trigger that arrives while a scan is running is coalesced into a single follow-up pass so the newest changes are still indexed without queueing a run per trigger.

type KnowledgeCapsule

type KnowledgeCapsule struct {
	KnowledgeBaseID   string              `json:"knowledgeBaseId"`
	KnowledgeBaseName string              `json:"knowledgeBaseName"`
	SnapshotID        string              `json:"snapshotId"`
	Text              string              `json:"text"`
	Citations         []KnowledgeCitation `json:"citations"`
}

KnowledgeCapsule is a bounded Runtime-prepared reference packet. A configured knowledge base is distilled by its dedicated Librarian Agent; the graph-backed baseline remains available for bases that predate an Agent provider/model configuration. Both paths preserve this same contract and citations.

func PrepareKnowledgeContext

func PrepareKnowledgeContext(ctx context.Context, sessionDir, query string, refs []KnowledgeBaseReference) ([]KnowledgeCapsule, error)

PrepareKnowledgeContext resolves graph-backed capsules from an immutable active snapshot. It reads no source file and runs no provider directly; callers get the same Runtime input shape regardless of their transport.

type KnowledgeCitation

type KnowledgeCitation struct {
	ChunkID      string `json:"chunkId"`
	RelativePath string `json:"relativePath"`
	StartLine    int    `json:"startLine"`
	EndLine      int    `json:"endLine"`
}

KnowledgeCitation lets a response/UI project the exact source location of a bounded knowledge capsule without receiving the source directory itself.

type KnowledgeIndexJob

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

KnowledgeIndexJob tracks one asynchronous scan/index pass. Scans always run in their own goroutine so neither the ACP transport nor any management RPC handler can be blocked by a long index; observers poll Progress or Wait.

func (*KnowledgeIndexJob) Done

func (j *KnowledgeIndexJob) Done() <-chan struct{}

Done exposes the completion channel of the job.

func (*KnowledgeIndexJob) Progress

Progress returns a consistent copy of the current progress view.

func (*KnowledgeIndexJob) Wait

Wait blocks until the job finishes or ctx expires. It is used by cron job execution, which needs the terminal result; interactive callers return immediately after StartIndex and poll Progress instead.

type KnowledgeIndexProgress

type KnowledgeIndexProgress struct {
	Running    bool      `json:"running"`
	Phase      string    `json:"phase,omitempty"`
	FilesTotal int64     `json:"filesTotal"`
	FilesDone  int64     `json:"filesDone"`
	Chunks     int64     `json:"chunks"`
	StartedAt  time.Time `json:"startedAt,omitempty"`
	RunID      string    `json:"runId,omitempty"`
	Error      string    `json:"error,omitempty"`
}

KnowledgeIndexProgress is a point-in-time view of one background index job.

type KnowledgeIndexRun added in v1.3.103

type KnowledgeIndexRun struct {
	RunID        string     `json:"runId"`
	SnapshotID   string     `json:"snapshotId,omitempty"`
	Status       string     `json:"status"`
	StartedAt    time.Time  `json:"startedAt"`
	FinishedAt   *time.Time `json:"finishedAt,omitempty"`
	ErrorCode    string     `json:"errorCode,omitempty"`
	ErrorSummary string     `json:"errorSummary,omitempty"`
	FileCount    int        `json:"fileCount"`
	ChunkCount   int        `json:"chunkCount"`
	NodeCount    int        `json:"nodeCount"`
	EdgeCount    int        `json:"edgeCount"`
	Active       bool       `json:"active"`
}

KnowledgeIndexRun is a bounded projection of one canonical index Run plus the snapshot statistics it produced. It is derived from canonical Run rows and the graph snapshot table, never from a second run store.

type KnowledgeMCPHandler

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

KnowledgeMCPHandler is the protocol adapter for a configured Knowledge MCP server. It delegates storage/query work to KnowledgeBaseService and returns only bounded, snapshot-backed evidence.

func NewKnowledgeMCPHandler

func NewKnowledgeMCPHandler(sessionDir string, knowledgeBaseIDs []string) (*KnowledgeMCPHandler, error)

NewKnowledgeMCPHandler exposes only explicitly configured knowledge bases. At least one ID is required so a model cannot enumerate arbitrary local knowledge bases through MCP.

func (*KnowledgeMCPHandler) CallTool

func (h *KnowledgeMCPHandler) CallTool(ctx context.Context, name string, arguments json.RawMessage) (mcp.ServerToolResult, error)

func (*KnowledgeMCPHandler) ListTools

type LocalSessionExecutionFacts added in v1.3.103

type LocalSessionExecutionFacts struct {
	SessionID     string
	SessionExists bool
	// Active means a durable run is registered as executing in this process.
	Active    bool
	RunID     string
	RunStatus string
	// LegacyBusy carries the pre-durable "running" bit of embedded fixtures.
	LegacyBusy bool
}

LocalSessionExecutionFacts are the process-local facts an adapter owns for a session that has no shared session root (for example an embedded fixture). The adapter supplies only these facts; the snapshot projection stays here so no adapter ever assembles a SessionExecutionSnapshot itself.

type MCPConnectPolicy added in v1.3.105

type MCPConnectPolicy struct {
	// Deferred skips connecting configured servers during build. The entry point
	// connects them later through ConnectDeferredMCP, keeping an interactive
	// surface responsive while a slow server starts.
	Deferred bool
	// Optional tolerates individual server failures instead of aborting build.
	// Tolerated failures are exposed through MCPConnectFailures.
	Optional bool
	// OverallTimeout bounds the whole connection group independently of the
	// per-operation timeouts. Zero uses only the per-operation timeouts.
	OverallTimeout time.Duration
}

MCPConnectPolicy controls how the shared Runtime connects configured MCP servers during build.

type MCPPolicy

type MCPPolicy struct {
	Servers   []mcp.ServerConfig
	Callbacks mcp.Callbacks
	Optional  bool
	// OverallTimeout bounds the whole connection group. Zero uses only the
	// per-operation timeouts. It lets an entry point cap how long a set of slow
	// configured servers may collectively delay a run without changing the
	// per-server timeout semantics.
	OverallTimeout time.Duration
	OnError        func(error)
}

MCPPolicy describes adapter-specific MCP transport behavior while Runtime owns client connection and release.

type MaintenancePolicy

type MaintenancePolicy struct {
	// ReclaimAttachmentStorage gates the private attachment-store reconciliation.
	ReclaimAttachmentStorage bool
	// StorageReconcileSchedule is the schedule expression the scheduler should
	// project for that reconciliation. It is validated where the schedule grammar
	// lives (internal/cron), not here.
	StorageReconcileSchedule string
}

MaintenancePolicy is the resolved intent for Runtime-owned maintenance work. It is produced once from configuration (`MaintenancePolicyFromSettings`) and then carried by whoever schedules or executes the work, so no layer decides separately whether maintenance runs or how often.

func DefaultMaintenancePolicy

func DefaultMaintenancePolicy() MaintenancePolicy

DefaultMaintenancePolicy is what applies when configuration says nothing: daily attachment storage reclamation.

func MaintenancePolicyFromSettings

func MaintenancePolicyFromSettings(settings *config.Settings) MaintenancePolicy

MaintenancePolicyFromSettings resolves maintenance configuration into one policy. A nil settings object is not an error: it means every default.

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 MutationLeaseGroup added in v1.3.103

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

MutationLeaseGroup owns mutation leases across several sessions for one coordinated mutation. Guard resolves the lease acquired for one session ID; Release relinquishes every lease in reverse acquisition order and is idempotent.

func AcquireSessionMutationGroup added in v1.3.103

func AcquireSessionMutationGroup(ctx context.Context, sessionDir string, sessionIDs []string, options ExecutionAdmissionOptions) (*MutationLeaseGroup, error)

AcquireSessionMutationGroup acquires mutation leases for every given session in the same stable sorted order as session.AcquireMutations, so a cross-session operation cannot deadlock another caller taking the same set, while applying the shared orphan-run reconciliation per session. Earlier leases are released when a later acquisition fails.

func (*MutationLeaseGroup) Guard added in v1.3.103

func (g *MutationLeaseGroup) Guard(sessionID string) *session.RuntimeLeaseGuard

func (*MutationLeaseGroup) Release added in v1.3.103

func (g *MutationLeaseGroup) Release()

type OrderedDeliveryOperationPlan

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

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

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

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

func NewPublishArtifactTool(collector *ArtifactCollector) *PublishArtifactTool

func (*PublishArtifactTool) Description

func (t *PublishArtifactTool) Description() string

func (*PublishArtifactTool) Execute

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

func (*PublishArtifactTool) Name

func (t *PublishArtifactTool) Name() string

func (*PublishArtifactTool) Parameters

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

func (*PublishArtifactTool) PromptGuidelines

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

func (*PublishArtifactTool) PromptSnippet

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

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

func NewRecoveryCoordinator(sessionDir string, options RecoveryCoordinatorOptions) *RecoveryCoordinator

func (*RecoveryCoordinator) ScanNow

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

func (*RecoveryCoordinator) Start

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

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

func (*RecoveryCoordinator) Wake

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

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
	// ImageGeneration exposes the image-generation tool when settings enable
	// it. Entries opt in; the settings gate remains the shared owner of the
	// switch, so resource refresh can reconcile it.
	ImageGeneration bool
	// Question exposes the interactive question tool. Entries map it to their
	// protocol surface (for example ACP request_permission); it is not part of
	// the default tool surface.
	Question bool
	Mutators []RegistryMutator
}

RegistryPolicy controls shared registry construction without letting adapters own its sandbox, workdir, or lifecycle.

type RemoteStopRequest

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 BuildDecisionEvent

func BuildDecisionEvent(t DecisionTransition) (RunEvent, error)

BuildDecisionEvent builds the canonical durable run event for a transition.

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

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

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

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

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

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

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

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

func (s RunStore) CreateRunWithEventAndTurn(run DurableRun, event RunEvent) (string, error)

func (RunStore) ExecutionBinding

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

func (s RunStore) FinishConversationTurn(run DurableRun, state RunState, message string) error

func (RunStore) FinishRunAndConversationTurn

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

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

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

func (RunStore) PrepareExistingExecution

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) RetainExecutionLease

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.

func (RuntimeSource) WaitsForMembers

func (s RuntimeSource) WaitsForMembers() bool

WaitsForMembers reports whether a source keeps a conversational lead's run open for its still-running members (see agent.ComposeFollowUps). Only sources with an attentive human in the loop qualify: a member's completion or question can be answered within the same run. On headless or asynchronous sources (CLI, cron, messaging channels) member notifications are delivered at the next iteration or the next run instead, so a single run never blocks for minutes unattended. A bound expert team always waits regardless of source.

type SessionAttachment

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

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 ExpertConfigOption

func ExpertConfigOption(workDir, current string) SessionConfigOption

ExpertConfigOption projects the shared expert catalog for a work directory without creating or mutating a session. It lets adapters render the initial session picker while Runtime remains the sole discovery authority.

func SessionConfigOptions

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

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

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

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"`
	// Source records how the projection was produced ("db" from a SQLite read or
	// "cache" from the synchronized ownership view). It is a projection-authority
	// marker, never an authorization input.
	Source string `json:"source,omitempty"`
}

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

func InspectLocalSessionExecution added in v1.3.103

func InspectLocalSessionExecution(facts LocalSessionExecutionFacts) SessionExecutionSnapshot

InspectLocalSessionExecution projects the execution state for a session with no shared session root. It is the Runtime-owned replacement for adapter-local snapshot assembly.

func InspectSessionExecution

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.

func UnknownSessionExecution added in v1.3.103

func UnknownSessionExecution(sessionID string) SessionExecutionSnapshot

UnknownSessionExecution returns the conservative unknown projection used when a session cannot be inspected at all. Adapters must use this instead of mutating an existing snapshot's Busy/CanSubmit/state fields.

type SessionExecutionState

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

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

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
	ArtifactEnabled       bool
	// Expert is the resolved expert binding (nil when the session has no
	// expert identity). Mailbox is the runtime-owned member completion queue
	// drained into steering at run input boundaries. ExpertCenter resolves
	// bundle names for this session's project directory.
	Expert       *ExpertBinding
	Mailbox      *agent.MemberMailbox
	ExpertCenter *expert.Center
	Submissions  *SubmissionCoordinator
	// 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

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

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

func (r *SessionRuntime) AdditionalDirectoriesSnapshot() []string

AdditionalDirectoriesSnapshot returns a copy of the current session roots.

func (*SessionRuntime) AppendSessionEventEntries added in v1.3.105

func (r *SessionRuntime) AppendSessionEventEntries(ctx context.Context, runID, turnID string, entries []interface{}) ([]string, error)

AppendSessionEventEntries is the Runtime-owned content write boundary. The caller supplies already-normalized canonical entries; lease fencing, EventStore fsync, intent commit, and metadata projection remain in session.

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) ArtifactCapabilitySnapshot

func (r *SessionRuntime) ArtifactCapabilitySnapshot() bool

ArtifactCapabilitySnapshot reports whether this entry point permits agents to publish generated files for the current session.

func (*SessionRuntime) AttachPreparedInput

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

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

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

BuildUserMessage emits text plus a deterministic project-path manifest and, for models with native audio/video understanding, the inline media content blocks of eligible audio/video inputs. It never reads image or document bytes and never constructs provider image/file blocks: those stay workspace files the model inspects with tools. Inline media is the only user-input content conversion, so adapters never build provider media blocks.

func (*SessionRuntime) CapabilitySnapshot

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

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

func (*SessionRuntime) CleanupInputResources

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

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

ConfigSnapshot returns the current session configuration atomically.

func (*SessionRuntime) ConfigureCapabilities

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

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 the standard global/project MCP configuration, appends explicitly negotiated protocol servers, and applies the same strict/optional connection behavior as ConnectMCP. This keeps adapters from creating a second configuration resolution path while still honoring ACP's standard mcpServers request field.

func (*SessionRuntime) ConnectDeferredMCP added in v1.3.105

func (r *SessionRuntime) ConnectDeferredMCP(ctx context.Context, policy MCPPolicy) error

ConnectDeferredMCP connects the configured servers a deferred build skipped. It is the Runtime-owned deferred path: the entry point only decides when to run it and how to project the result. On success it clears the deferred flag and records any tolerated failures for MCPConnectFailures. When the caller does not pass an overall timeout, the one supplied to the deferred build is reused so the connect always terminates.

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

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) EventStoreWriteStats added in v1.3.105

func (r *SessionRuntime) EventStoreWriteStats() (session.EventStoreStats, error)

EventStoreWriteStats projects process-local EventStore pressure telemetry through Runtime. The counters are observational only and never authorize a write, lease change, or recovery action.

func (*SessionRuntime) ExpertState

func (r *SessionRuntime) ExpertState() (*ExpertBinding, *agent.MemberMailbox)

ExpertState returns the resolved binding and the session member mailbox under the runtime lock. Both may be nil (no expert bound / no mailbox).

func (*SessionRuntime) InspectExpert

func (r *SessionRuntime) InspectExpert(expertID string) (*expert.Bundle, error)

InspectExpert resolves one expert bundle for display or preflight validation. It intentionally does not bind the bundle; callers must use SetExpert or ForkWithExpert for the persistent identity transition.

func (*SessionRuntime) InspectSessionEventStore added in v1.3.105

func (r *SessionRuntime) InspectSessionEventStore(ctx context.Context) (session.EventStoreInspection, error)

InspectSessionEventStore is the Runtime-owned read boundary for session content consistency. Adapters must not open event-store files directly.

func (*SessionRuntime) ListExperts

func (r *SessionRuntime) ListExperts() []expert.Summary

ListExperts projects the discoverable expert bundles for this Runtime's work directory. It performs no binding or resource mutation: frontends use this to render a picker while SetExpert remains the sole binding operation.

func (*SessionRuntime) MCPConnectFailures added in v1.3.105

func (r *SessionRuntime) MCPConnectFailures() []string

MCPConnectFailures returns descriptions of configured MCP servers that failed to connect during the last tolerant connection. It is a read-only projection for an entry point's warning surface.

func (*SessionRuntime) MCPDeferred added in v1.3.105

func (r *SessionRuntime) MCPDeferred() bool

MCPDeferred reports whether configured MCP servers were intentionally skipped at build time and are expected to be connected later by the entry point.

func (*SessionRuntime) PrepareInput

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) ReadCommittedSessionEvents added in v1.3.105

func (r *SessionRuntime) ReadCommittedSessionEvents(ctx context.Context) ([]session.EventBatch, error)

ReadCommittedSessionEvents exposes only replayable, SQLite-committed content through the shared Runtime boundary. In-doubt batches never reach adapters.

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. It always resolves the current persisted expert binding before loading resources, so lazy session attachment and expert bind/unbind cannot leave package skills or prompts from a previous session behind. Adapter-specific AgentManager and optional tools are deliberately outside this method.

func (*SessionRuntime) ReloadAdditionalDirectories

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) ResolveProviderModel

func (r *SessionRuntime) ResolveProviderModel(providerName, modelID string) (provider.Provider, string, *provider.Model, error)

ResolveProviderModel resolves an optional derived-role provider/model pair from the Runtime-owned provider catalog. Empty values retain this session's configured provider and model. It is intentionally a Runtime method so adapters do not create providers or duplicate model-compatibility logic for role-specific executions.

func (*SessionRuntime) SetAdditionalDirectories

func (r *SessionRuntime) SetAdditionalDirectories(directories []string) error

SetAdditionalDirectories persists and applies a complete replacement of the session's additional directory roots.

func (*SessionRuntime) SetArtifactEnabled

func (r *SessionRuntime) SetArtifactEnabled(enabled bool) error

SetArtifactEnabled updates the entry-point policy used by subsequent runs. An already active collector retains ownership until that run terminates.

func (*SessionRuntime) SetCapabilityOption

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

SetCapabilityOption persists and applies one boolean session capability.

func (*SessionRuntime) SetConfigOption

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) SetExpert

func (r *SessionRuntime) SetExpert(expertID string) error

SetExpert binds or unbinds the session expert (empty string unbinds) and persists the header binding. Callers rebuild the Agent afterwards so the identity section, roster, and team capability take effect (same lifecycle as capability toggles such as /delegate).

func (*SessionRuntime) SettingsSnapshot

func (r *SessionRuntime) SettingsSnapshot() *config.Settings

SettingsSnapshot returns a copy of the Runtime resource settings for a Runtime-owned derived execution. The copy prevents a caller from mutating the active session's shared configuration while still letting derived roles inherit the same compaction and tool-execution defaults.

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) SubmissionCoordinator added in v1.3.105

func (r *SessionRuntime) SubmissionCoordinator() *SubmissionCoordinator

SubmissionCoordinator returns the Runtime-owned local FIFO for this Session. It is created once per SessionRuntime and closed by Shutdown.

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) TeamExpertActive

func (r *SessionRuntime) TeamExpertActive() bool

TeamExpertActive reports whether this session is bound to a team expert. It is the single capability predicate adapters must use (together with SubAgentToolsEnabled) instead of re-deriving expert state locally.

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.

func (*SessionRuntime) WithKnowledgeContext

func (r *SessionRuntime) WithKnowledgeContext(ctx context.Context, input InputSubmission, refs []KnowledgeBaseReference) (InputSubmission, error)

WithKnowledgeContext attaches Runtime-owned reference results to a prepared submission. It must be called before BuildUserMessage so adapters cannot construct provider messages or retain a parallel text-only path.

type SessionStopCode

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

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

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

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 SubmissionAdmission added in v1.3.105

type SubmissionAdmission func(context.Context) (release func(), err error)

SubmissionAdmission acquires the admission lease. The coordinator owns the returned release function and invokes it only after the runner has returned. This keeps adapter code from becoming a second lease owner.

type SubmissionAdmissionHandle added in v1.3.105

type SubmissionAdmissionHandle struct {
	Submission *ExecutionHandle
	Ready      <-chan struct{}
	// contains filtered or unexported fields
}

SubmissionAdmissionHandle represents a Runtime-owned admission that keeps its lease until Release is called by the execution owner. It lets synchronous adapters migrate to the coordinator without taking ownership of the queue or implementing their own Wait:true polling loop.

func (*SubmissionAdmissionHandle) Release added in v1.3.105

func (h *SubmissionAdmissionHandle) Release()

func (*SubmissionAdmissionHandle) Wait added in v1.3.105

Wait blocks until the submission acquires its admission lease or reaches a terminal state. A failed, cancelled, or interrupted submission returns that terminal error instead of leaving the caller blocked forever.

type SubmissionCoordinator added in v1.3.105

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

SubmissionCoordinator serializes submissions for one SessionRuntime. It is intentionally independent of Agent construction and Run persistence: those remain owned by the existing Runtime execution path.

func NewSubmissionCoordinator added in v1.3.105

func NewSubmissionCoordinator(sessionArgs ...string) *SubmissionCoordinator

func (*SubmissionCoordinator) Acquire added in v1.3.105

Acquire queues an admission and holds its lease until the returned handle is released. The caller may wait for Ready, perform its existing execution path, and then Release; all ordering and external ownership decisions stay in the shared coordinator.

func (*SubmissionCoordinator) Close added in v1.3.105

func (c *SubmissionCoordinator) Close()

Close cancels the active runner and deterministically completes all queued submissions. The active runner is allowed to finish its own durable cleanup.

func (*SubmissionCoordinator) CloseContext added in v1.3.105

func (c *SubmissionCoordinator) CloseContext(ctx context.Context) error

CloseContext cancels the active runner, completes queued submissions, and waits for the active runner only as long as ctx permits. The runner remains responsible for its own durable cleanup if the wait expires.

func (*SubmissionCoordinator) QueueLen added in v1.3.105

func (c *SubmissionCoordinator) QueueLen() int

func (*SubmissionCoordinator) Submit added in v1.3.105

Submit accepts a request and starts it immediately when the coordinator is idle. A request accepted behind a local execution is never dropped because the admission lease is temporarily busy.

func (*SubmissionCoordinator) Wake added in v1.3.105

func (c *SubmissionCoordinator) Wake()

Wake is advisory. It never changes admission state; it only causes a waiting submission to re-read SQLite and retry its fenced admission.

type SubmissionEvent added in v1.3.105

type SubmissionEvent struct {
	SubmissionID string
	RunID        string
	State        SubmissionState
	Error        error
}

type SubmissionRunner added in v1.3.105

type SubmissionRunner func(context.Context) error

SubmissionRunner performs one complete execution, including its durable terminal transition. It must return only after the execution completion barrier is ready to close.

type SubmissionState added in v1.3.105

type SubmissionState string
const (
	SubmissionAccepted    SubmissionState = "accepted"
	SubmissionQueued      SubmissionState = "queued"
	SubmissionAdmitting   SubmissionState = "admitting"
	SubmissionRunning     SubmissionState = "running"
	SubmissionCompleting  SubmissionState = "completing"
	SubmissionCompleted   SubmissionState = "completed"
	SubmissionFailed      SubmissionState = "failed"
	SubmissionCancelled   SubmissionState = "cancelled"
	SubmissionInterrupted SubmissionState = "interrupted"
)

type SubmitPolicy added in v1.3.105

type SubmitPolicy struct {
	QueueBehindLocal bool
	WaitForExternal  bool
}

SubmitPolicy controls whether a request may wait behind an execution owned by this Runtime. External ownership is never queued by this coordinator.

type ToolCallPolicyDecision

type ToolCallPolicyDecision struct {
	Block  bool
	Reason string
}

ToolCallPolicyDecision is the source policy result for one tool call.

type ToolGroupPolicy

type ToolGroupPolicy struct {
	// MultiAgent enables the async sub-agent toolset. A bound expert team
	// forces it on regardless (see SubAgentToolsEnabled).
	MultiAgent bool
	// SubAgentTools optionally narrows the sub-agent set by tool name for
	// ordinary multi-agent sessions. It is ignored while a team is bound: the
	// team capability is authoritative and never drops tools. Nil means the
	// full canonical set.
	SubAgentTools map[string]bool
	// Delegate enables the blocking single sub-agent delegation tool.
	Delegate bool
	// Workflows enables the workflow toolset.
	Workflows bool
	// WorkflowTools optionally narrows the workflow set by tool name with the
	// same team semantics as SubAgentTools. Nil means the full canonical set.
	WorkflowTools map[string]bool
}

ToolGroupPolicy describes the optional tool groups resolved from session capabilities. Adapters supply policy and the current manager handle; installation, removal, and manager-swap re-installation are Runtime-owned so every entry point (TUI, CLI, WebUI/API, ACP, Channel) shares one behavior.

type WorktreeEvent added in v1.3.103

type WorktreeEvent struct {
	Type      string
	ID        string
	Name      string
	Branch    string
	Directory string
	Message   string
}

WorktreeEvent is a canonical worktree lifecycle event. Adapters project it onto their own wire format.

type WorktreeEventSink added in v1.3.103

type WorktreeEventSink interface {
	EmitWorktreeEvent(event WorktreeEvent)
}

WorktreeEventSink receives canonical worktree lifecycle events.

type WorktreeEventSinkFunc added in v1.3.103

type WorktreeEventSinkFunc func(WorktreeEvent)

WorktreeEventSinkFunc adapts a function to WorktreeEventSink.

func (WorktreeEventSinkFunc) EmitWorktreeEvent added in v1.3.103

func (f WorktreeEventSinkFunc) EmitWorktreeEvent(event WorktreeEvent)

type WorktreeManager added in v1.3.103

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

WorktreeManager is the single Runtime owner of managed worktree orchestration: it resolves the repository root, plans a unique worktree, registers it, materializes it, authorizes its directory, emits canonical events and keeps the registry reconciled with git. Git mechanics live in internal/worktree; SQL lives in internal/dao behind internal/session.

func NewDefaultWorktreeManager added in v1.3.103

func NewDefaultWorktreeManager(settings *config.Settings) (*WorktreeManager, error)

NewDefaultWorktreeManager builds a WorktreeManager from shared settings: default worktree root, the configured branch prefix/start command and the resolved sandbox level for start commands. Adapter entry points use it so every host shares one construction path instead of repeating options.

func NewWorktreeManager added in v1.3.103

func NewWorktreeManager(opts WorktreeManagerOptions) (*WorktreeManager, error)

NewWorktreeManager builds a WorktreeManager.

func (*WorktreeManager) AuthorizeDirectory added in v1.3.103

func (m *WorktreeManager) AuthorizeDirectory(directory string)

AuthorizeDirectory marks a directory as a Runtime-granted workspace root so the shared workspace resolver can accept it as a session cwd.

func (*WorktreeManager) AuthorizedDirectories added in v1.3.103

func (m *WorktreeManager) AuthorizedDirectories() []string

AuthorizedDirectories returns the sorted set of Runtime-granted worktree directories.

func (*WorktreeManager) Create added in v1.3.103

Create resolves the repository root of BaseCwd, registers and materializes a new worktree, authorizes its directory synchronously and populates it asynchronously. The returned projection is pending until population completes (a ready/failed event follows).

func (*WorktreeManager) Get added in v1.3.103

Get returns the registered worktree projection for id, or a zero Worktree when it does not exist.

func (*WorktreeManager) IsAuthorized added in v1.3.103

func (m *WorktreeManager) IsAuthorized(directory string) bool

IsAuthorized reports whether a directory is a Runtime-granted worktree root.

func (*WorktreeManager) List added in v1.3.103

func (m *WorktreeManager) List(ctx context.Context, repositoryRoot, projectID string) ([]session.Worktree, error)

List returns registered worktrees (optionally filtered), reconciled with git: rows git no longer knows are marked removed, and unregistered git worktrees of an explicitly requested repository are returned as read-only external items. A repository whose root is unavailable does not fail the whole list.

func (*WorktreeManager) Remove added in v1.3.103

func (m *WorktreeManager) Remove(ctx context.Context, id, directory string) error

Remove deletes a registered worktree (by id or directory). It proves the directory is a worktree of the repository before deleting anything, then removes the registry row.

func (*WorktreeManager) Reset added in v1.3.103

func (m *WorktreeManager) Reset(ctx context.Context, id, directory string) error

Reset returns a registered worktree to the repository's default branch.

func (*WorktreeManager) ResolveOrCreate added in v1.3.103

func (m *WorktreeManager) ResolveOrCreate(ctx context.Context, baseCwd, key string) (string, error)

ResolveOrCreate returns the directory of an existing registered worktree named key for baseCwd's repository, or creates one. It lets a workstream (for example an ESM objective's worker/critic/audit roles) share a single worktree.

func (*WorktreeManager) Root added in v1.3.103

func (m *WorktreeManager) Root() string

Root returns the directory managed worktrees live under.

func (*WorktreeManager) Wait added in v1.3.103

func (m *WorktreeManager) Wait()

Wait blocks until in-flight asynchronous population completes. It exists for deterministic shutdown and tests.

func (*WorktreeManager) WaitForReady added in v1.3.103

func (m *WorktreeManager) WaitForReady(ctx context.Context, id string) (session.Worktree, error)

WaitForReady blocks until the worktree reaches a terminal lifecycle state and returns its projection. A failed/removed worktree is reported as an error so callers never start work in an unusable directory.

type WorktreeManagerOptions added in v1.3.103

type WorktreeManagerOptions struct {
	// SessionDir is the shared sessions.db root that owns the worktree registry.
	SessionDir string
	// Root overrides the default worktree root (<data-dir>/worktrees).
	Root string
	// BranchPrefix is the default branch prefix ("mothx" when empty).
	BranchPrefix string
	// Git overrides the git mechanism (tests).
	Git *worktree.Manager
	// EventSink receives lifecycle events. Optional.
	EventSink WorktreeEventSink
	// DefaultStartCommand is applied to a worktree whose request does not
	// specify one. Empty means no start command runs.
	DefaultStartCommand string
	// SandboxOptions is the sandbox policy used to execute a worktree start
	// command. Start commands never run outside the sandbox.
	SandboxOptions sandbox.Options
	// SandboxLevel is the resolved sandbox level for start commands. Nil means
	// LevelNone (direct execution).
	SandboxLevel *sandbox.Level
}

WorktreeManagerOptions configures a WorktreeManager.

type WorktreeProviderAdapter added in v1.3.103

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

WorktreeProviderAdapter adapts the WorktreeManager to the internal/agent WorktreeProvider contract. It materializes (or reuses) a worktree and waits until it is usable before returning its directory.

func NewWorktreeProviderAdapter added in v1.3.103

func NewWorktreeProviderAdapter(mgr *WorktreeManager) *WorktreeProviderAdapter

func (*WorktreeProviderAdapter) ResolveWorktree added in v1.3.103

func (p *WorktreeProviderAdapter) ResolveWorktree(baseCwd string, spec agent.WorktreeSpec) (string, error)

ResolveWorktree implements agent.WorktreeProvider.

Jump to

Keyboard shortcuts

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