Documentation
¶
Overview ¶
Package agentruntime contains front-end-neutral execution policy primitives.
Index ¶
- Constants
- Variables
- func ACPAgentProfileFromPreset(preset ACPAgentPreset) config.ACPAgentProfile
- func ACPCapabilityOverrideNames() []string
- func AcquireExecutionAdmission(ctx context.Context, sessionDir, sessionID string, ...) (*session.RuntimeLeaseGuard, error)
- func AcquireExecutionSubmission(ctx context.Context, sessionDir, sessionID, runID string, waitForExternal bool) (func(), error)
- func AcquireSessionMutation(ctx context.Context, sessionDir, sessionID string, ...) (*session.RuntimeLeaseGuard, error)
- func AcquireSessionMutationUnlessHeld(ctx context.Context, sessionDir, sessionID string, ...) (*session.RuntimeLeaseGuard, error)
- func AnnotateDurableRunError(ctx context.Context, sessionDir, runID, errMsg string) (bool, error)
- func ArtifactReclaimFloor(policy AttachmentPolicy, now time.Time) time.Time
- func ArtifactStorageDirectoryName() string
- func BuildRegistry(workDir string, sandboxMgr *sandbox.Manager, settings *config.Settings, ...) (*tools.Registry, error)
- func CloseMCPClients(clients []*mcp.Client)
- func CreateDurableRun(sessionDir string, run DurableRun) error
- func CreateSession(opts CreateSessionOptions) (*session.Manager, error)
- func DecisionEventEnvelope(record DecisionRecord) map[string]any
- func DecisionEventFields(record DecisionRecord, payload any) map[string]any
- func DefaultPlanToolPolicy(settings *config.Settings) *bool
- func DeleteSession(sessionDir, id string) error
- func DeleteSessionWithMutation(sessionDir, id string, guard *session.RuntimeLeaseGuard) error
- func DeliveryFailureRetryable(failureCode string) bool
- func DeliveryOperationText(raw []byte, operationKind string) string
- func DeliveryPendingData(responseRunID, responseID, state, assistantEntryID string, ...) map[string]any
- func DisplayErrorMessage(info ErrorInfo) string
- func FindIdempotentRun(ctx context.Context, sessionDir, sessionID, key, fingerprint, scope string) (*session.SessionRun, error)
- func FinishDurableRun(sessionDir, runID string, state RunState, message string) error
- func GetActiveDurableRun(ctx context.Context, sessionDir, sessionID string) (*session.SessionRun, error)
- func GetDurableRun(ctx context.Context, sessionDir, runID string) (*session.SessionRun, error)
- func IdempotencyKeyFingerprint(key string) string
- func InspectExpert(workDir, expertID string) (*expert.Bundle, error)
- func InspectSessionExecutions(sessionDir string, sessionIDs []string) map[string]SessionExecutionSnapshot
- func IsMaintenanceCronJobID(jobID string) bool
- func IsValidMode(mode string) bool
- func IsWorkerQuestionID(id string) bool
- func KnowledgeBaseCronJobID(knowledgeBaseID string) string
- func KnowledgeBaseIDFromCronJobID(jobID string) (string, bool)
- func KnowledgeLibrarianSessionID(baseID, rootDir string) string
- func ListExperts(workDir string) []expert.Summary
- func ListLatestDurableRunsBySessions(ctx context.Context, sessionDir string, sessionIDs []string) (map[string]session.SessionRun, error)
- func MaintenanceSessionStorageJobID() string
- func MaintenanceStorageReconcileJobID() string
- func ManagerBackedToolsEnabled(rt *SessionRuntime, multiAgent, delegate, workflows bool) bool
- func NewAgentManager(opts AgentManagerOptions) (*agent.AgentManager, error)
- func NormalizeAdditionalDirectories(directories []string) ([]string, error)
- func OpenSession(sessionDir, id string) (*session.Manager, error)
- func OpenSessionForWorkDir(workDir, sessionDir, id string) (*session.Manager, error)
- func RecordDecisionEvent(sink RunEventSink, t DecisionTransition) (string, error)
- func RecoverDurableRun(sessionDir string, run session.SessionRun, state RunState, message string, ...) error
- func RemoveWorkerMessages(sessionDir, sessionID string) error
- func ReplayDecisions(records []DecisionRecord) map[string]DecisionRecord
- func ReplayDecisionsAt(records []DecisionRecord, now time.Time) map[string]DecisionRecord
- func ReplayDeliveries(events []session.SessionRunEvent) map[string]DeliveryRecord
- func ReplayDeliveriesFromRunEvents(events []RunEvent) map[string]DeliveryRecord
- func ReplayRunEventsJSON(events []session.SessionRunEvent, runID string) ([]byte, error)
- func ResolveIterationBudget(policy agent.IterationBudgetPolicy, soft int) agent.IterationBudgetPolicy
- func ResolveUnattendedMode(sessionMode string) string
- func RunKnowledgeBaseCronJob(ctx context.Context, service *KnowledgeBaseService, jobID string) (bool, string, error)
- func RunMaintenanceCronJob(ctx context.Context, sessionDir, jobID string, policy MaintenancePolicy) (bool, string, error)
- func SessionHasTeamExpert(workDir string, manager *session.Manager) bool
- func SubAgentToolsEnabled(rt *SessionRuntime, requested bool) bool
- func SynchronizeToolGroups(rt *SessionRuntime, registry *tools.Registry, policy ToolGroupPolicy, ...)
- func UpdateDurableRun(sessionDir, runID string, state RunState, message string) error
- func ValidateThinkingLevel(value string) (provider.ThinkingLevel, error)
- func ValidateWorkDir(workDir string) (string, error)
- func WorkerMessageLogPath(sessionDir, sessionID string) (string, error)
- type ACPAgentPreset
- type ACPChildBackend
- type ACPWorkerBridge
- type ACPWorkerInvocation
- type ACPWorkerProfileDescriptor
- type ACPWorkerResult
- type AgentBuildOptions
- type AgentEventObservation
- type AgentManagerOptions
- type ArtifactCollector
- type ArtifactReconciliation
- type AttachedResources
- type AttachmentKind
- type AttachmentPolicy
- type AttachmentService
- func (s *AttachmentService) CleanupExpired(ctx context.Context) (int, error)
- func (s *AttachmentService) Get(ctx context.Context, sessionID, attachmentID string) (SessionAttachment, error)
- func (s *AttachmentService) Open(ctx context.Context, sessionID, attachmentID string) (SessionAttachment, io.ReadCloser, error)
- func (s *AttachmentService) Policy() AttachmentPolicy
- func (s *AttachmentService) ReconcileStorage(ctx context.Context, now time.Time) (ArtifactReconciliation, error)
- func (s *AttachmentService) SetStatus(ctx context.Context, sessionID, attachmentID, status string) error
- type BuildOptions
- type Builder
- type CommandRisk
- type ContextResources
- type CreateSessionOptions
- type CreateWorktreeRequest
- type DecisionKind
- type DecisionRecord
- func DecodeDecisionEvent(ev session.SessionRunEvent) (DecisionRecord, bool)
- func ExpiredDecisions(records []DecisionRecord, now time.Time) []DecisionRecord
- func LoadDecisionRecords(sessionDir, sessionID string) ([]DecisionRecord, error)
- func LoadDecisionRecordsContext(ctx context.Context, sessionDir, sessionID string) ([]DecisionRecord, error)
- func LoadRunDecisionRecords(sessionDir, sessionID, runID string) ([]DecisionRecord, error)
- func LoadRunDecisionRecordsContext(ctx context.Context, sessionDir, sessionID, runID string) ([]DecisionRecord, error)
- func NewDecisionRecord(request DecisionRequest, status, value string, payload any, ...) (DecisionRecord, error)
- func NewDecisionRequestRecord(request DecisionRequest, payload any) (DecisionRecord, error)
- func NewDecisionRequestRecordWithDeadline(request DecisionRequest, payload any, expiresAt time.Time) (DecisionRecord, error)
- func NewDecisionResolutionRecord(request DecisionRequest, resolution DecisionResolution, payload any) (DecisionRecord, error)
- type DecisionRequest
- type DecisionResolution
- type DecisionService
- func (s *DecisionService) Bind(id string, resolve func(string) error) error
- func (s *DecisionService) ClearRun(runID string) []DecisionRequest
- func (s *DecisionService) ClearRunWithValue(runID, value string) []DecisionRequest
- func (s *DecisionService) Discard(id string)
- func (s *DecisionService) Pending() []DecisionRequest
- func (s *DecisionService) Register(request DecisionRequest) error
- func (s *DecisionService) Rehydrate(records []DecisionRecord) ([]DecisionRequest, error)
- func (s *DecisionService) Resolve(resolution DecisionResolution) (DecisionRequest, error)
- func (s *DecisionService) ResolveWith(resolution DecisionResolution, commit func(DecisionRequest) error) (DecisionRequest, error)
- type DecisionTransition
- type DeliveryCapability
- type DeliveryCoordinator
- func (c *DeliveryCoordinator) Claim(ctx context.Context, operationID string, now time.Time) (*session.DeliveryOperation, error)
- func (c *DeliveryCoordinator) Complete(ctx context.Context, operation *session.DeliveryOperation, ...) error
- func (c *DeliveryCoordinator) Progress(ctx context.Context, operation *session.DeliveryOperation, ...) error
- func (c *DeliveryCoordinator) ReconcileDue(ctx context.Context, now time.Time, execute DeliveryExecutor) (int, error)
- type DeliveryExecutor
- type DeliveryIntentPlan
- type DeliveryPlan
- type DeliveryPlanRequest
- type DeliveryRecord
- type DeliveryResult
- type DurableConversationTurnEventFinisher
- type DurableConversationTurnFinisher
- type DurableConversationTurnStore
- type DurableIntentEventStore
- type DurableIntentStore
- type DurableRun
- type DurableRunEventStore
- type DurableRunMetadataStore
- type DurableRunStore
- type DurableRunUsageStore
- type DurableTerminalPersistenceStore
- type ErrorClassificationOptions
- type ErrorInfo
- type ExecutionAdmissionOptions
- type ExecutionCompletion
- type ExecutionHandle
- type ExecutionIntent
- type ExecutionPolicy
- type ExecutionRuntime
- func (r *ExecutionRuntime) Active() (string, bool)
- func (r *ExecutionRuntime) Begin(parent context.Context, runID string) (context.Context, error)
- func (r *ExecutionRuntime) BeginDurable(parent context.Context, run DurableRun, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) BeginIntentDurable(parent context.Context, intent ExecutionIntent, run DurableRun, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) BeginRetryDurable(parent context.Context, run DurableRun, event RunEvent) (*ExecutionIntent, context.Context, error)
- func (r *ExecutionRuntime) BeginWithEvent(parent context.Context, runID string, event RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) Cancel() bool
- func (r *ExecutionRuntime) CancelDurable(message string) (bool, error)
- func (r *ExecutionRuntime) Completion(runID string) <-chan struct{}
- func (r *ExecutionRuntime) Finish(runID string)
- func (r *ExecutionRuntime) FinishDurable(runID string, state RunState, message string, event RunEvent) error
- func (r *ExecutionRuntime) FinishDurableWithRetry(ctx context.Context, runID string, state RunState, message string, ...) error
- func (r *ExecutionRuntime) FinishWithEvent(runID string, state RunState, event RunEvent) error
- func (r *ExecutionRuntime) FinishWithState(runID string, state RunState) error
- func (r *ExecutionRuntime) ObserveAgentEvent(ev agent.Event) (AgentEventObservation, error)
- func (r *ExecutionRuntime) ReattachDurable(parent context.Context, runID string, state RunState) (context.Context, error)
- func (r *ExecutionRuntime) ReattachDurableRun(parent context.Context, run DurableRun, state RunState, startEvent RunEvent) (context.Context, error)
- func (r *ExecutionRuntime) RecordErrorInfo(info ErrorInfo) (ErrorInfo, error)
- func (r *ExecutionRuntime) RecordEvent(ev RunEvent) (string, error)
- func (r *ExecutionRuntime) RecordFailure(err error, opts ErrorClassificationOptions) (ErrorInfo, error)
- func (r *ExecutionRuntime) RecordUsage(runID string, usage, contextUsage json.RawMessage) error
- func (r *ExecutionRuntime) Resume(runID string) error
- func (r *ExecutionRuntime) SetAgent(a interface{ ... })
- func (r *ExecutionRuntime) SetAssistantMessage(runID, entryID string, message provider.Message) error
- func (r *ExecutionRuntime) SetDeliveryPlan(runID string, plan DeliveryPlan) error
- func (r *ExecutionRuntime) SetEventSink(sink RunEventSink)
- func (r *ExecutionRuntime) SetRunStore(store DurableRunStore)
- func (r *ExecutionRuntime) SetTerminalObserver(observer func(string, RunState))
- func (r *ExecutionRuntime) Shutdown(message string) error
- func (r *ExecutionRuntime) ShutdownContext(ctx context.Context, message string) error
- func (r *ExecutionRuntime) State() RunState
- func (r *ExecutionRuntime) UpdateDurable(runID string, state RunState, message string) error
- func (r *ExecutionRuntime) Wait(ctx context.Context) error
- func (r *ExecutionRuntime) WaitForApproval(runID string) error
- func (r *ExecutionRuntime) WaitForQuestion(runID string) error
- type ExpertBinding
- type FailureClass
- type ForkOptions
- type ForkResult
- type InputIngress
- type InputMaterializer
- func (m *InputMaterializer) Cleanup(ctx context.Context, sessionID string, now time.Time) (int, error)
- func (m *InputMaterializer) Delete(ctx context.Context, sessionID, resourceID string) error
- func (m *InputMaterializer) Discard(ctx context.Context, sessionID, resourceID string) error
- func (m *InputMaterializer) Get(ctx context.Context, sessionID, resourceID string) (InputResource, error)
- func (m *InputMaterializer) Prepare(ctx context.Context, sessionID, runID string, ingress InputIngress) (InputResource, error)
- func (m *InputMaterializer) Read(ctx context.Context, sessionID, resourceID string) (InputResource, []byte, error)
- type InputPolicy
- type InputResource
- type InputStream
- type InputSubmission
- type KnowledgeBaseIndexPolicy
- type KnowledgeBaseProviderFactory
- type KnowledgeBaseReference
- type KnowledgeBaseService
- func NewKnowledgeBaseService(sessionDir string, policy KnowledgeBaseIndexPolicy) (*KnowledgeBaseService, error)
- func NewKnowledgeBaseServiceWithProviderFactory(sessionDir string, policy KnowledgeBaseIndexPolicy, settings *config.Settings, ...) (*KnowledgeBaseService, error)
- func NewKnowledgeBaseServiceWithSettings(sessionDir string, policy KnowledgeBaseIndexPolicy, settings *config.Settings) (*KnowledgeBaseService, error)
- func (s *KnowledgeBaseService) ClearIndex(ctx context.Context, knowledgeBaseID string) error
- func (s *KnowledgeBaseService) Index(ctx context.Context, knowledgeBaseID string) (session.KnowledgeSnapshot, error)
- func (s *KnowledgeBaseService) IndexDurable(ctx context.Context, knowledgeBaseID string, source RuntimeSource) (session.KnowledgeSnapshot, error)
- func (s *KnowledgeBaseService) IndexDurableWithProgress(ctx context.Context, knowledgeBaseID string, source RuntimeSource, ...) (session.KnowledgeSnapshot, error)
- func (s *KnowledgeBaseService) IndexJob(knowledgeBaseID string) (*KnowledgeIndexJob, bool)
- func (s *KnowledgeBaseService) IndexProgress(knowledgeBaseID string) (KnowledgeIndexProgress, bool)
- func (s *KnowledgeBaseService) IndexRun(ctx context.Context, knowledgeBaseID, runID string) (KnowledgeIndexRun, error)
- func (s *KnowledgeBaseService) IndexRuns(ctx context.Context, knowledgeBaseID string, limit int) ([]KnowledgeIndexRun, error)
- func (s *KnowledgeBaseService) IndexWithRun(ctx context.Context, knowledgeBaseID, runID string) (session.KnowledgeSnapshot, error)
- func (s *KnowledgeBaseService) LibrarianCapsule(ctx context.Context, caller *SessionRuntime, base session.KnowledgeBase, ...) (KnowledgeCapsule, error)
- func (s *KnowledgeBaseService) Query(ctx context.Context, knowledgeBaseID, query string, limit int) (session.KnowledgeGraphQuery, error)
- func (s *KnowledgeBaseService) SetSettings(settings *config.Settings)
- func (s *KnowledgeBaseService) Sources(ctx context.Context, knowledgeBaseID string) ([]session.KnowledgeSource, error)
- func (s *KnowledgeBaseService) StartIndex(ctx context.Context, knowledgeBaseID string, source RuntimeSource) (*KnowledgeIndexJob, error)
- type KnowledgeCapsule
- type KnowledgeCitation
- type KnowledgeIndexJob
- type KnowledgeIndexProgress
- type KnowledgeIndexRun
- type KnowledgeMCPHandler
- type LocalSessionExecutionFacts
- type MCPConnectPolicy
- type MCPPolicy
- type MailboxWakeOptions
- type MailboxWakeRun
- type MaintenancePolicy
- type ManagerBackedToolsOptions
- type ManagerFactory
- type ModeResolver
- type MutationLeaseGroup
- type OrderedDeliveryOperationPlan
- type Policy
- type PreparedInput
- type ProviderCatalog
- type PublishArtifactTool
- func (t *PublishArtifactTool) Description() string
- func (t *PublishArtifactTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *PublishArtifactTool) Name() string
- func (t *PublishArtifactTool) Parameters() json.RawMessage
- func (t *PublishArtifactTool) PromptGuidelines() []string
- func (t *PublishArtifactTool) PromptSnippet() string
- type RecoveryAction
- type RecoveryCoordinator
- type RecoveryCoordinatorOptions
- type RefreshOptions
- type RegistryHook
- type RegistryMutator
- type RegistryPolicy
- type RemoteStopRequest
- type RetryInfo
- type RetryMode
- type RouterBinding
- type RouterProfileBinding
- type RunEvent
- type RunEventProjector
- type RunEventSink
- type RunEventSinkFunc
- type RunInput
- type RunPhase
- type RunRecoveryPolicy
- type RunRecoveryResult
- func RecoverOrphanedRuns(sessionDir string, policy RunRecoveryPolicy, ...) (RunRecoveryResult, error)
- func RecoverOrphanedSessionRun(sessionDir, sessionID string, policy RunRecoveryPolicy, ...) (RunRecoveryResult, error)
- func RecoverOrphanedSessionRunContext(ctx context.Context, sessionDir, sessionID string, policy RunRecoveryPolicy, ...) (RunRecoveryResult, error)
- func StopOrphanedSessionRun(sessionDir, sessionID string, beforeTerminalize func(session.SessionRun) error) (RunRecoveryResult, error)
- func StopOrphanedSessionRunContext(ctx context.Context, sessionDir, sessionID string, ...) (RunRecoveryResult, error)
- func StopOrphanedSessionRunContextForRun(ctx context.Context, sessionDir, sessionID, expectedRunID string, ...) (RunRecoveryResult, error)
- type RunReplay
- type RunState
- type RunStore
- func (s RunStore) Create(run DurableRun) error
- func (s RunStore) CreateIntentAndRun(intent ExecutionIntent, run DurableRun) error
- func (s RunStore) CreateIntentAndRunWithEvent(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateIntentAndRunWithEventAndTurn(intent ExecutionIntent, run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateRunWithEvent(run DurableRun, event RunEvent) (string, error)
- func (s RunStore) CreateRunWithEventAndTurn(run DurableRun, event RunEvent) (string, error)
- func (s RunStore) ExecutionBinding(sessionID, runID string) (session.RuntimeLeaseBinding, bool, error)
- func (s RunStore) Finish(runID string, state RunState, message string) error
- func (s RunStore) FinishConversationTurn(run DurableRun, state RunState, message string) error
- func (s RunStore) FinishRunAndConversationTurn(run DurableRun, state RunState, message string, event RunEvent) (string, error)
- func (s RunStore) GetIntent(intentID string) (*ExecutionIntent, error)
- func (s RunStore) LeaseLost(sessionID string) <-chan struct{}
- func (s RunStore) MarkTerminalizing(runID, message string) error
- func (s RunStore) PrepareExistingExecution(sessionID, runID string) error
- func (s RunStore) RetainExecutionLease(sessionID, runID string) (session.RuntimeLeaseBinding, func(), bool, error)
- func (s RunStore) Update(runID string, state RunState, message string) error
- func (s RunStore) UpdateErrorInfo(runID string, info ErrorInfo) error
- func (s RunStore) UpdateProgress(runID string, progress RetryInfo) error
- func (s RunStore) UpdateUsage(runID string, usage, contextUsage json.RawMessage) error
- type RuntimeChangeSetIntegrator
- type RuntimeSource
- type RuntimeWorkerQuestionResolver
- type SessionAttachment
- type SessionConfigOption
- func ExpertConfigOption(workDir, current string) SessionConfigOption
- func SessionConfigOptions(providerName string, models []*provider.Model, model *provider.Model, ...) []SessionConfigOption
- func SessionConfigOptionsWithProviders(providerName string, providers ProviderCatalog, models []*provider.Model, ...) []SessionConfigOption
- type SessionConfigOptionChoice
- type SessionExecutionSnapshot
- type SessionExecutionState
- type SessionModelBinding
- type SessionRunEventSink
- type SessionRunSummary
- type SessionRuntime
- func (r *SessionRuntime) AcceptInput(ctx context.Context, runID, text string, ingresses []InputIngress) (InputSubmission, error)
- func (r *SessionRuntime) AcceptProviderAttachment(ctx context.Context, runID string, p provider.Provider, ...) (SessionAttachment, error)
- func (r *SessionRuntime) ActivateRouter(ctx context.Context, sessionDir string, settings *config.Settings, ...) error
- func (r *SessionRuntime) AdditionalDirectoriesSnapshot() []string
- func (r *SessionRuntime) AppendSessionEventEntries(ctx context.Context, runID, turnID string, entries []interface{}) ([]string, error)
- func (r *SessionRuntime) ApplyRegistryHooks(hooks []RegistryHook) error
- func (r *SessionRuntime) ArtifactCapabilitySnapshot() bool
- func (r *SessionRuntime) AttachPreparedInput(ctx context.Context, text string, resources []PreparedInput) (InputSubmission, error)
- func (r *SessionRuntime) BeginArtifactCollection(runID string) (*ArtifactCollector, error)
- func (r *SessionRuntime) BindSession(manager *session.Manager, requested RuntimeSource) error
- func (r *SessionRuntime) BuildAgent(opts AgentBuildOptions) (*agent.Agent, error)
- func (r *SessionRuntime) BuildTransientAgent(registry *tools.Registry, opts AgentBuildOptions) (*agent.Agent, error)
- func (r *SessionRuntime) BuildUserMessage(ctx context.Context, input InputSubmission) (provider.Message, error)
- func (r *SessionRuntime) CapabilitySnapshot() (sandboxEnabled, browserEnabled, webSearchEnabled bool)
- func (r *SessionRuntime) CleanupInputResources(ctx context.Context, now time.Time) (int, error)
- func (r *SessionRuntime) Close()
- func (r *SessionRuntime) ConfigOptions() []SessionConfigOption
- func (r *SessionRuntime) ConfigSnapshot() (provider.Provider, string, *provider.Model, string, provider.ThinkingLevel)
- func (r *SessionRuntime) ConfigureCapabilities(sandboxEnabled, browserEnabled, webSearchEnabled bool) error
- func (r *SessionRuntime) ConfigureSession(p provider.Provider, providerName string, model *provider.Model, mode string, ...) error
- func (r *SessionRuntime) ConnectConfiguredMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) ConnectDeferredMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) ConnectMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) DisableMailboxWake()
- func (r *SessionRuntime) DiscardInput(ctx context.Context, input InputSubmission)
- func (r *SessionRuntime) EnableMailboxWake(ctx context.Context, options MailboxWakeOptions) error
- func (r *SessionRuntime) EventStoreWriteStats() (session.EventStoreStats, error)
- func (r *SessionRuntime) ExpertState() (*ExpertBinding, *agent.MemberMailbox)
- func (r *SessionRuntime) InspectExpert(expertID string) (*expert.Bundle, error)
- func (r *SessionRuntime) InspectSessionEventStore(ctx context.Context) (session.EventStoreInspection, error)
- func (r *SessionRuntime) ListExperts() []expert.Summary
- func (r *SessionRuntime) MCPConnectFailures() []string
- func (r *SessionRuntime) MCPDeferred() bool
- func (r *SessionRuntime) MarkWorkerMessageDelivered(messageID, runID string)
- func (r *SessionRuntime) PendingWorkerQuestions() ([]WorkerQuestionView, error)
- func (r *SessionRuntime) PersistedMode() string
- func (r *SessionRuntime) PrepareInput(ctx context.Context, ingress InputIngress) (PreparedInput, error)
- func (r *SessionRuntime) ReadCommittedSessionEvents(ctx context.Context) ([]session.EventBatch, error)
- func (r *SessionRuntime) ReconcileManagerBackedTools(opts ManagerBackedToolsOptions) (*agent.AgentManager, error)
- func (r *SessionRuntime) RefreshProviderCatalog(catalog ProviderCatalog) error
- func (r *SessionRuntime) RefreshResourceSettings(settings *config.Settings)
- func (r *SessionRuntime) RefreshResources(settings *config.Settings, opts RefreshOptions) error
- func (r *SessionRuntime) RefreshRouterTarget()
- func (r *SessionRuntime) ReloadAdditionalDirectories(manager *session.Manager) error
- func (r *SessionRuntime) ReloadConfiguredMCP(ctx context.Context, policy MCPPolicy) error
- func (r *SessionRuntime) ResolvePolicy(sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
- func (r *SessionRuntime) ResolveProviderModel(providerName, modelID string) (provider.Provider, string, *provider.Model, error)
- func (r *SessionRuntime) ResolveRouterACPProfile(settings *config.Settings) (config.ACPAgentProfile, RouterBinding, error)
- func (r *SessionRuntime) ResolveRouterACPProfileByID(settings *config.Settings, profileID string) (config.ACPAgentProfile, RouterBinding, error)
- func (r *SessionRuntime) ResolveRouterBinding(settings *config.Settings) (RouterBinding, error)
- func (r *SessionRuntime) ResolveWorkerQuestion(ctx context.Context, questionID, answer string) error
- func (r *SessionRuntime) RouterActive() bool
- func (r *SessionRuntime) RouterBinding() (RouterBinding, bool)
- func (r *SessionRuntime) SetAdditionalDirectories(directories []string) error
- func (r *SessionRuntime) SetArtifactEnabled(enabled bool) error
- func (r *SessionRuntime) SetCapabilityOption(id string, enabled bool) error
- func (r *SessionRuntime) SetConfigOption(id, value string) error
- func (r *SessionRuntime) SetDecisions(decisions *DecisionService)
- func (r *SessionRuntime) SetExecution(execution *ExecutionRuntime)
- func (r *SessionRuntime) SetExpert(expertID string) error
- func (r *SessionRuntime) SetMode(value string) error
- func (r *SessionRuntime) SetRouterBinding(binding RouterBinding) error
- func (r *SessionRuntime) SettingsSnapshot() *config.Settings
- func (r *SessionRuntime) Shutdown(ctx context.Context) error
- func (r *SessionRuntime) SubmissionCoordinator() *SubmissionCoordinator
- func (r *SessionRuntime) SynchronizeCoreTools(browserEnabled, webSearchEnabled bool)
- func (r *SessionRuntime) TeamExpertActive() bool
- func (r *SessionRuntime) UnbindSession() error
- func (r *SessionRuntime) WithKnowledgeContext(ctx context.Context, input InputSubmission, refs []KnowledgeBaseReference) (InputSubmission, error)
- func (r *SessionRuntime) WorkerMessageContext(ctx context.Context) ([]WorkerMessage, error)
- func (r *SessionRuntime) WorkerMessageLog() (*WorkerMessageLog, error)
- func (r *SessionRuntime) WorkerMessages() ([]WorkerMessage, error)
- func (r *SessionRuntime) WorkerSnapshot() (WorkerSnapshot, error)
- type SessionStopCode
- type SessionStopOptions
- type SessionStopResult
- type SideEffectState
- type Source
- type SourceConflictError
- type SourceResolution
- func ResolvePolicy(input SourceResolutionInput, sessionMode, requestedMode, defaultMode string) (SourceResolution, string, error)
- func ResolvePolicyFromSession(sessionDir, sessionID string, input SourceResolutionInput, ...) (SourceResolution, string, error)
- func ResolveSource(input SourceResolutionInput) SourceResolution
- func ResolveSourceFromSession(sessionDir, sessionID string, input SourceResolutionInput) (SourceResolution, error)
- type SourceResolutionInput
- type SubagentAttachment
- type SubagentDeliverable
- type SubagentRole
- type SubagentTaskContract
- type SubmissionAdmission
- type SubmissionAdmissionHandle
- type SubmissionCoordinator
- func (c *SubmissionCoordinator) Acquire(ctx context.Context, runID string, policy SubmitPolicy, ...) (*SubmissionAdmissionHandle, error)
- func (c *SubmissionCoordinator) Close()
- func (c *SubmissionCoordinator) CloseContext(ctx context.Context) error
- func (c *SubmissionCoordinator) QueueLen() int
- func (c *SubmissionCoordinator) Submit(ctx context.Context, runID string, policy SubmitPolicy, ...) (*ExecutionHandle, error)
- func (c *SubmissionCoordinator) Wake()
- type SubmissionEvent
- type SubmissionRunner
- type SubmissionState
- type SubmitPolicy
- type ToolCallPolicyDecision
- type ToolGroupPolicy
- type WorkerAskFunc
- type WorkerBridgeScope
- type WorkerBridgeServer
- func (s *WorkerBridgeServer) Available() bool
- func (s *WorkerBridgeServer) Close() error
- func (s *WorkerBridgeServer) EnsureStarted() (int, error)
- func (s *WorkerBridgeServer) Port() int
- func (s *WorkerBridgeServer) Register(scope *WorkerBridgeScope) (string, []any, error)
- func (s *WorkerBridgeServer) Revoke(token string)
- func (s *WorkerBridgeServer) RevokeChild(sessionID, childID string)
- func (s *WorkerBridgeServer) RevokeSession(sessionID string)
- func (s *WorkerBridgeServer) SetChildTerminal(sessionID, childID string, terminal bool)
- func (s *WorkerBridgeServer) SetIdleTimeout(timeout time.Duration)
- type WorkerMessage
- type WorkerMessageLog
- func (l *WorkerMessageLog) Close() error
- func (l *WorkerMessageLog) Compact() error
- func (l *WorkerMessageLog) Create(message WorkerMessage) (WorkerMessage, bool, error)
- func (l *WorkerMessageLog) Find(id string) (WorkerMessage, bool, error)
- func (l *WorkerMessageLog) List() ([]WorkerMessage, error)
- func (l *WorkerMessageLog) Mark(id, op, runID, reason string) error
- func (l *WorkerMessageLog) MessagesByChild(childID string) ([]WorkerMessage, error)
- func (l *WorkerMessageLog) Path() string
- type WorkerQuestionView
- type WorkerSnapshot
- type WorktreeEvent
- type WorktreeEventSink
- type WorktreeEventSinkFunc
- type WorktreeManager
- func (m *WorktreeManager) AuthorizeDirectory(directory string)
- func (m *WorktreeManager) AuthorizedDirectories() []string
- func (m *WorktreeManager) CaptureChangeSet(ctx context.Context, id, baseRevision string, patchLimit int) (worktree.ChangeSet, error)
- func (m *WorktreeManager) Create(ctx context.Context, req CreateWorktreeRequest) (session.Worktree, error)
- func (m *WorktreeManager) Get(ctx context.Context, id string) (session.Worktree, error)
- func (m *WorktreeManager) IsAuthorized(directory string) bool
- func (m *WorktreeManager) List(ctx context.Context, repositoryRoot, projectID string) ([]session.Worktree, error)
- func (m *WorktreeManager) Remove(ctx context.Context, id, directory string) error
- func (m *WorktreeManager) Reset(ctx context.Context, id, directory string) error
- func (m *WorktreeManager) ResolveOrCreate(ctx context.Context, baseCwd, key string) (string, error)
- func (m *WorktreeManager) ResolveOrCreateWorktree(ctx context.Context, baseCwd, key string) (session.Worktree, error)
- func (m *WorktreeManager) Revision(ctx context.Context, directory string) (string, error)
- func (m *WorktreeManager) Root() string
- func (m *WorktreeManager) Wait()
- func (m *WorktreeManager) WaitForReady(ctx context.Context, id string) (session.Worktree, error)
- type WorktreeManagerOptions
- type WorktreeProviderAdapter
Constants ¶
const ( ChangeSetIntegrationApplied = "applied" ChangeSetIntegrationConflict = "conflict" ChangeSetIntegrationRejected = "rejected" ChangeSetIntegrationFailed = "failed" ChangeSetIntegrationNotAttempted = "not_attempted" )
Integration evidence statuses. They describe one Runtime-owned application attempt, never a worker's claim about its own worktree.
const ( DecisionStatusPending = "pending" DecisionStatusRequested = "requested" DecisionStatusResolved = "resolved" DecisionStatusCancelled = "cancelled" DecisionStatusTimedOut = "timed_out" )
Decision statuses recorded in the durable ledger.
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.
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" // MaintenanceSessionStorageSchedule runs session-storage maintenance once a // day. With the default retention of 0 it only runs PRAGMA optimize and // reports storage; pruning and VACUUM are opt-in. MaintenanceSessionStorageSchedule = "@daily" // MaintenanceSessionStorageJobName labels the projected job. MaintenanceSessionStorageJobName = "Maintain session storage" )
const ( ModePlan = "plan" ModeAgent = "agent" ModeYolo = "yolo" ModeOS = "os" // ModeRouter is a lead-only orchestration mode. Its exact tool surface is // resolved by the Runtime and excludes local mutation/process tools. ModeRouter = "router" )
const ( DefaultRecoveryScanInterval = 5 * time.Second DefaultRecoveryAttemptTimeout = 10 * time.Second )
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.
const ( // DefaultWorkerAskTimeout bounds one blocking worker question. Runtime policy // may lower or raise it within MaxWorkerAskTimeout. DefaultWorkerAskTimeout = 10 * time.Minute MaxWorkerAskTimeout = 30 * time.Minute )
Worker bridge limits.
const ( WorkerMessageNotice = "notice" WorkerMessageProgress = "progress" WorkerMessageFinding = "finding" WorkerMessageQuestion = "question" WorkerMessageCompletion = "completion" )
Worker message kinds. They are the worker-facing vocabulary; only finding, question, and completion may enter the lead context or wake an idle lead.
const ( WorkerMessageStatusCreated = "created" WorkerMessageStatusDelivered = "delivered" WorkerMessageStatusObserved = "observed" WorkerMessageStatusExpired = "expired" WorkerMessageStatusCancelled = "cancelled" // WorkerMessageStatusSuperseded marks a queued finding that was replaced by // a newer finding from the same worker before the lead consumed it. WorkerMessageStatusSuperseded = "superseded" )
Worker message delivery states, folded from the append-only event log.
const ( MaxWorkerReportBytes = 8 << 10 MaxWorkerAskBytes = 4 << 10 MaxWorkerAskOptions = 8 // One option is a short choice label, not free-form context. Bounding both // the per-option size and the total keeps a hostile worker from turning the // options array into an unbounded payload for the durable decision log and // the lead mailbox. MaxWorkerAskOptionBytes = 512 MaxWorkerAskOptionsBytes = 2 << 10 )
Limits for one worker report/ask. They bound what a hostile or confused external Agent can append to the durable log and inject into the lead.
const ( WorktreeEventPending = "pending" WorktreeEventReady = "ready" WorktreeEventFailed = "failed" WorktreeEventRemoved = "removed" )
Worktree lifecycle event types. They describe the managed worktree resource, never a run terminal state.
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.
const (
DefaultTerminalPersistenceTimeout = 10 * time.Second
)
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.
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 ¶
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") )
var ErrDetachedRemoteExecution = errors.New("session has a recoverable detached remote execution")
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.
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.
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.
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.
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 ACPAgentProfileFromPreset ¶
func ACPAgentProfileFromPreset(preset ACPAgentPreset) config.ACPAgentProfile
ACPAgentProfileFromPreset expands a preset into a ready-to-edit profile with a non-blocking approval policy and enabled state. Role and write scope are supplied per delegation, never stored on the profile.
func ACPCapabilityOverrideNames ¶
func ACPCapabilityOverrideNames() []string
ACPCapabilityOverrideNames is the confirmation surface for the closed set of capability keys a profile may tighten. Management projections render exactly this vocabulary instead of duplicating it.
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 ¶
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 ¶
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 ¶
DefaultPlanToolPolicy returns the configured plan-tool setting.
func DeleteSession ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
IdempotencyKeyFingerprint keeps a client/platform key out of durable event data while retaining a stable equality token for reconciliation.
func InspectExpert ¶
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.
Fresh ownership-cache entries are projected without a database read. All remaining IDs share one read-only facts transaction and then funnel through the same projectSessionExecutionFromFacts used by the single-session path.
func IsMaintenanceCronJobID ¶
IsMaintenanceCronJobID reports whether a persisted job belongs to the maintenance namespace and therefore must be executed by RunMaintenanceCronJob.
func IsValidMode ¶
IsValidMode reports whether mode is one of the public execution modes.
func IsWorkerQuestionID ¶
IsWorkerQuestionID reports whether a decision ID belongs to a worker ask.
func KnowledgeBaseCronJobID ¶
KnowledgeBaseCronJobID derives the shared cron identity of one knowledge base's reindex schedule.
func KnowledgeBaseIDFromCronJobID ¶
KnowledgeBaseIDFromCronJobID extracts the knowledge base identity from a namespaced cron job ID.
func KnowledgeLibrarianSessionID ¶
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 ¶
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 MaintenanceSessionStorageJobID ¶ added in v1.3.107
func MaintenanceSessionStorageJobID() string
MaintenanceSessionStorageJobID is the stable identity of the session-storage maintenance job.
func MaintenanceStorageReconcileJobID ¶
func MaintenanceStorageReconcileJobID() string
MaintenanceStorageReconcileJobID is the stable identity of the attachment storage reconciliation job.
func ManagerBackedToolsEnabled ¶
func ManagerBackedToolsEnabled(rt *SessionRuntime, multiAgent, delegate, workflows bool) bool
ManagerBackedToolsEnabled reports whether this session exposes the manager-backed tool groups (sub-agent, delegate, workflow) and therefore needs an AgentManager plus a registered lead agent.
The lead agent must be registered into the manager before it can spawn a child: AgentManager.Create validates the parent ID against the registered agents and fails with "parent agent <id> not found" otherwise. Router mode installs the same delegation surface as a multi-agent session, so it must count here even when the adapter's multi-agent/delegate/workflow flags are all false. Every entry point must use this predicate so a session can never expose a delegation tool whose parent is unknown to the manager.
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 ¶
NormalizeAdditionalDirectories validates the ACP directory-root contract: absolute, cleaned, deterministic and duplicate-free paths.
func OpenSession ¶
OpenSession opens a persisted session by exact ID regardless of its workdir.
func OpenSessionForWorkDir ¶
OpenSessionForWorkDir opens a persisted session scoped to its working directory.
func 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 RemoveWorkerMessages ¶
RemoveWorkerMessages deletes one session's worker evidence log after its canonical session row has been removed. The shared sessions root and other sessions are never touched.
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 (the main loop pairs a 400 soft limit with a 600 hard ceiling; a supplied soft limit keeps the conventional 2x ceiling, with two renewals, a minimum interval of soft/10, and a 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 ¶
ResolveUnattendedMode derives the execution mode for unattended derived runs such as ESM role sub-agents. Unattended runs must never stop on interactive approval, so os and router preserve their intentionally narrow tool surfaces; 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 ¶
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 ¶
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
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.
func WorkerMessageLogPath ¶
WorkerMessageLogPath returns the per-session append-only log path. The session ID must be a single path component; explicit IDs supplied by an adapter are never allowed to escape the Runtime-private directory.
Types ¶
type ACPAgentPreset ¶
type ACPAgentPreset struct {
// ID is the profile ID suggested for the preset.
ID string
// Title is the human name shown in the picker.
Title string
// Command is the argv that starts the agent's ACP server.
Command []string
// Note explains a non-obvious installation or naming detail.
Note string
// Driver is the ACP flavor. It is generic-acp for every verified preset
// today; a flavor is only introduced when real interop exposes a protocol
// gap that generic ACP cannot describe.
Driver workerdriver.WorkerDriver
}
ACPAgentPreset is one well-known external ACP agent launch recipe. It exists so configuring a common worker is one keystroke instead of remembering which binary speaks ACP and which flags start it.
Command is argv and is written verbatim: a bare name is resolved through PATH at launch, exactly like any other process launch. The presets are launch recipes, not a trust decision — the user still owns the profile and can edit every field.
func ACPAgentPresets ¶
func ACPAgentPresets() []ACPAgentPreset
ACPAgentPresets returns the built-in launch recipes for well-known ACP agents.
Every entry was verified against the tool's own documentation or CLI help at the time of writing. Several popular CLIs do NOT start an ACP server themselves — `codex acp` and `claude acp` are not valid — so those entries use the official adapter packages instead. Getting that wrong is the single most common configuration mistake, which is why the notes exist.
func FindACPAgentPreset ¶
func FindACPAgentPreset(id string) (ACPAgentPreset, bool)
FindACPAgentPreset returns the preset whose ID matches, case-insensitively.
type ACPChildBackend ¶
type ACPChildBackend struct {
Runtime *SessionRuntime
Settings *config.Settings
// Worktrees is the Runtime-owned worktree manager used for child isolation
// and immutable change-set capture. It may be nil for headless tests.
Worktrees *WorktreeManager
// contains filtered or unexported fields
}
ACPChildBackend is the bridge between the shared AgentManager child graph and the ACP Worker Bridge. Agent Core only sees an extra agentpkg.Agent; it never imports ACP policy, profiles, or transport.
func (ACPChildBackend) ChildWorktree ¶
func (b ACPChildBackend) ChildWorktree(opts agentcore.AgentOptions) *agentcore.WorktreeSpec
ChildWorktree requests a managed worktree for an implementation worker before the AgentManager resolves it. Integration writes the base workspace directly, and read-only/test/review workers keep sharing the stable session workspace.
func (ACPChildBackend) CreateChild ¶
func (b ACPChildBackend) CreateChild(opts agentcore.AgentOptions) (agentpkg.Agent, bool, error)
CreateChild reports handled=false when the request is a normal local child. A requested external target always reports handled=true, including errors, so Agent Core can never fall back to a local child for a Router delegation.
func (ACPChildBackend) UpdateChildBackendRuntimeConfig ¶
func (b ACPChildBackend) UpdateChildBackendRuntimeConfig(settings *config.Settings)
UpdateChildBackendRuntimeConfig refreshes the settings snapshot used for future external children. The session directory stays Runtime-owned: a live settings pointer must not redirect child execution to another session DB.
type ACPWorkerBridge ¶
type ACPWorkerBridge struct{}
ACPWorkerBridge owns one ACP v1 worker connection. It is intentionally not an Agent, session store, or queue; Runtime supplies policy and consumes the typed protocol result.
func (ACPWorkerBridge) Open ¶
func (ACPWorkerBridge) Open(ctx context.Context, invocation ACPWorkerInvocation) (*acpRemoteWorker, error)
Open validates the invocation, obtains a pooled connection, then creates or loads exactly one remote session. A resume request never falls back to a new session: silently losing the remote transcript would be a policy change.
func (ACPWorkerBridge) Run ¶
func (ACPWorkerBridge) Run(ctx context.Context, invocation ACPWorkerInvocation) (ACPWorkerResult, error)
Run obtains one initialized ACP connection, creates one remote session, and runs one bounded prompt turn. A Runtime-owned pool may reuse the process for other sessions; standalone callers own the process for this invocation.
type ACPWorkerInvocation ¶
type ACPWorkerInvocation struct {
Profile config.ACPAgentProfile
Contract SubagentTaskContract
WorkDir string
AdditionalDirectories []string
// ResumeSessionID requests an explicit reconnect through session/resume or
// session/load (Runtime chooses from advertised capabilities). It is used
// only for an already-created remote session; the caller must not send a
// prompt through the old connection after this value is set.
ResumeSessionID string
Launcher acpclient.Launcher
ClientInfo acpclient.Implementation
// ReadTextFile advertises the Runtime-owned read-only filesystem bridge.
// WriteTextFile advertises the Runtime-owned scoped write bridge, and
// TerminalAccess opts into the profile-gated terminal bridge.
ReadTextFile bool
WriteTextFile bool
TerminalAccess bool
// MCPBridgeAvailable reports that this process has a live loopback worker
// bridge. The Runtime sets it when (and only when) the bridge is running;
// a false value degrades MCPHTTP without affecting the prompt.
MCPBridgeAvailable bool
// PrepareMCPServers is called after initialize negotiated the capability set.
// It returns the session/new mcpServers payload and a revoke function. A
// preparation failure only logs and degrades the bridge; the prompt proceeds.
PrepareMCPServers func(workerdriver.WorkerCapabilities) ([]any, func(), error)
HandleRequest acpclient.RequestHandler
OnNotification func(acpclient.Message)
// OnEvent receives canonical, non-terminal child events. The proxy owns the
// single EventRunFinished terminal event.
OnEvent func(agentpkg.Event)
// contains filtered or unexported fields
}
ACPWorkerInvocation is the already-authorized Runtime input to one external ACP worker turn. It contains no adapter state or provider content; Router task construction owns that conversion before this boundary.
type ACPWorkerProfileDescriptor ¶
type ACPWorkerProfileDescriptor struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Transport config.ACPAgentTransport `json:"transport"`
// Model is the external Agent's configured default model ID, or empty when
// the worker keeps its own default. It is display/management metadata only:
// the Runtime owns how it is applied to a worker session.
Model string `json:"model,omitempty"`
// Endpoint is the administrator-configured remote URL with any query or
// fragment removed. Empty for stdio profiles.
Endpoint string `json:"endpoint,omitempty"`
Enabled bool `json:"enabled"`
RouterEligible bool `json:"routerEligible"`
PermissionPolicy config.ACPPermissionPolicy `json:"permissionPolicy"`
MaxConcurrentChildren int `json:"maxConcurrentChildren"`
// MaxConcurrentChildrenEnforced is the live-worker ceiling actually applied by
// this release. It matches the configured ceiling.
MaxConcurrentChildrenEnforced int `json:"maxConcurrentChildrenEnforced"`
// ParallelBaseWorkspaceWrites reports that the profile opted into
// concurrent base-workspace writers. MothX cannot confine an external
// Agent's own tools to the declared write scope, so this is explicit
// operator trust and stays visible in every management projection.
ParallelBaseWorkspaceWrites bool `json:"parallelBaseWorkspaceWrites,omitempty"`
// Driver is the configured ACP flavor (default generic-acp). It is behavior
// metadata only; business code reads resolved capabilities instead.
Driver string `json:"driver"`
// MCPBridge is "auto" or "off". It reports intent, not reachability; remote
// profiles project an unreachable bridge in child metadata.
MCPBridge string `json:"mcpBridge"`
// CapabilityOverrides lists the capabilities this profile explicitly
// tightens. It is diagnostic: resolution applies the profile map directly.
CapabilityOverrides []string `json:"capabilityOverrides,omitempty"`
InvalidReason string `json:"invalidReason,omitempty"`
}
ACPWorkerProfileDescriptor is the safe, model/management-facing view of one configured external ACP worker. It never contains argv, environment names, credentials, query/fragment values, or configuration paths.
func ListACPWorkerProfiles ¶
func ListACPWorkerProfiles(settings *config.Settings) []ACPWorkerProfileDescriptor
ListACPWorkerProfiles is the shared Runtime catalog used by management projections. It is read-only and does not launch or probe an executable: executables are validated by `mothx doctor`.
type ACPWorkerResult ¶
type ACPWorkerResult struct {
AgentInfo acpclient.Implementation
SessionID string
StopReason string
Output string
Truncated bool
ToolCalls int
// DroppedUpdates counts session updates the Runtime discarded because the
// Agent emitted them faster than they could be projected. A non-zero value
// means the transcript is missing its beginning.
DroppedUpdates uint64
}
ACPWorkerResult is the protocol result of one remote worker turn. The proxy converts it into the single canonical terminal event.
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
// SyntheticContinuation starts a Runtime-owned continuation without a user
// submission. Its seed message is system-injected context, not a fake user
// entry, so the build must not reserve a run user-entry ID.
SyntheticContinuation bool
// 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 ¶
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
// WorkerBridge is the process-wide loopback MCP bridge. ACP and other
// attach-based entry points pass their one shared instance; nil disables it.
WorkerBridge *WorkerBridgeServer
}
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 ¶
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
// WorkerBridge is the process-wide loopback MCP bridge for Router workers.
// It is created by top-level assembly (TUI/CLI, serve, ACP) and shared by
// every session; nil disables the bridge without changing any task path.
WorkerBridge *WorkerBridgeServer
// 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 ¶
func (Builder) Build ¶
func (b Builder) Build(ctx context.Context, opts BuildOptions) (*SessionRuntime, error)
Build constructs context, skills, sandbox, tools and MCP connections for one session. The caller owns the returned runtime and must call Close on failures after successful construction or when the session is evicted.
type CommandRisk ¶
type CommandRisk string
CommandRisk is the unattended-execution risk assigned to a bash command.
const ( CommandRiskLow CommandRisk = "low" CommandRiskMedium CommandRisk = "medium" CommandRiskHigh CommandRisk = "high" )
func ClassifyBashCommand ¶
func ClassifyBashCommand(command string) CommandRisk
ClassifyBashCommand classifies command risk for unattended execution. High risk detection tokenizes shell control operators and executable paths so quoting, compound commands, and common flag variants cannot bypass it.
type ContextResources ¶
ContextResources are the shared context/skill inputs used by a session runtime.
func LoadContextResources ¶
func LoadContextResources(settings *config.Settings, workDir string, workflows, browserEnabled bool) (*ContextResources, error)
LoadContextResources loads context files, project/global skills, and rules. It is shared by all adapters; adapters choose only the requested capabilities.
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) Discard ¶
func (s *DecisionService) Discard(id string)
Discard removes a pending decision without resolving it. It is used when a caller has already recorded a terminal outcome in the durable ledger but the service could not commit that resolution: leaving the in-memory pending entry would let a reconnect project a decision the ledger says is finished.
Discard never removes a resolved decision and never invokes a resolver.
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 ¶
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 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 ¶
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 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 ¶
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.
func (*InputMaterializer) Read ¶
func (m *InputMaterializer) Read(ctx context.Context, sessionID, resourceID string) (InputResource, []byte, error)
Read returns one Runtime-owned input resource after checking session ownership, size, and content hash. It is the only handoff used when an authorized external worker needs bytes inlined into its own protocol prompt.
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 ¶
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 ¶
func (j *KnowledgeIndexJob) Progress() KnowledgeIndexProgress
Progress returns a consistent copy of the current progress view.
func (*KnowledgeIndexJob) Wait ¶
func (j *KnowledgeIndexJob) Wait(ctx context.Context) (session.KnowledgeSnapshot, error)
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 ¶
func (h *KnowledgeMCPHandler) ListTools(context.Context) ([]mcp.ServerTool, error)
func (*KnowledgeMCPHandler) ServerName ¶
func (h *KnowledgeMCPHandler) ServerName() string
ServerName keeps the knowledge MCP server's advertised identity stable now that the shared stdio protocol layer supports handler-provided names.
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 MailboxWakeOptions ¶
type MailboxWakeOptions struct {
Build AgentBuildOptions
OnStarted func(MailboxWakeRun)
OnEvent func(MailboxWakeRun, agent.Event)
OnArtifact func(MailboxWakeRun, SessionAttachment)
// OnAgent publishes the freshly built lead Agent so an adapter can answer
// Runtime-owned questions through its existing protocol hook. The Agent is
// already registered on the shared ExecutionRuntime and is never owned by
// the adapter.
OnAgent func(MailboxWakeRun, *agent.Agent)
// ConfigureBuild applies entry-point policy that must be read at wake time
// (capabilities, approvals, adapter hooks). It runs after the Runtime has
// overwritten the run identity/provider snapshot, so it cannot fork the
// canonical Run facts.
ConfigureBuild func(*AgentBuildOptions)
OnFinished func(MailboxWakeRun, RunState, error)
// Debounce coalesces a burst of completions into one admission attempt.
Debounce time.Duration
}
MailboxWakeOptions installs adapter policy hooks and projections around the one Runtime-owned continuation path. Build's RunID, turn identity, and ownership fields are overwritten per wake; adapters only supply policy such as Allow/approval handlers.
type MailboxWakeRun ¶
type MailboxWakeRun struct {
RunID string
SessionID string
Source string
Model string
Mode string
StartedAt time.Time
}
MailboxWakeRun is the immutable identity an adapter uses to attach its existing renderer to a Runtime-owned automatic continuation.
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
// ReclaimSessionStorage gates Runtime-owned session-storage maintenance.
ReclaimSessionStorage bool
// SessionStorageSchedule is the schedule expression for that maintenance.
SessionStorageSchedule string
// ToolExecutionRetention bounds completed/abandoned tool-execution
// idempotency records. Zero keeps them forever. Transcript messages are
// never governed by this field.
ToolExecutionRetention time.Duration
// VacuumSessionStorage opts into VACUUM after pruning.
VacuumSessionStorage bool
}
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 ManagerBackedToolsOptions ¶
type ManagerBackedToolsOptions struct {
// Registry overrides the Runtime registry. Nil uses the Runtime's Registry.
Registry *tools.Registry
// Policy is the adapter's resolved capability/tool-selection policy.
Policy ToolGroupPolicy
// Manager is the adapter's current manager handle.
Manager *agent.AgentManager
// Build creates a session-scoped manager. It is called only when the
// Runtime resolves that a manager-backed capability is active and either
// Manager is nil or Rebuild is true.
Build ManagerFactory
// Rebuild discards Manager before Build so manager-owned session state
// (expert roster/mailbox, Router worker binding, provider/model changes) is
// recreated instead of reusing a stale roster. Build is required when
// Rebuild is set and Manager is non-nil; the Runtime fails closed otherwise.
Rebuild bool
// RequireManager keeps a manager even when the capability predicate is
// false. The TUI and CLI use it because root-agent bookkeeping, ESM
// supervision, and the cron scheduler hold the manager handle independently
// of which manager-backed tools the model can see.
RequireManager bool
}
ManagerBackedToolsOptions is the adapter-supplied input to one Runtime-owned manager/tool reconciliation.
Adapters supply their resolved capability policy, the manager handle they currently hold, and a factory for a session-scoped manager. The Runtime owns whether a manager is required, when it must be rebuilt, and how the manager-backed tool groups are installed or removed. This is the single post-activation/refresh entry point for TUI, CLI, WebUI/API, ACP, and channels; adapters must not open-code the predicate plus installer pair.
type ManagerFactory ¶
type ManagerFactory func() (*agent.AgentManager, error)
ManagerFactory constructs the session-scoped AgentManager used by the manager-backed tool groups. A factory may return (nil, nil) when the session deliberately has no usable manager (for example no configured provider); the Runtime then reconciles the registry to an empty manager-backed surface.
type ModeResolver ¶
type ModeResolver struct {
Policy ExecutionPolicy
}
ModeResolver applies an execution policy consistently at every adapter boundary.
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 ¶
ForcedMode returns the source-mandated mode, if any.
func (Policy) HasForcedMode ¶
HasForcedMode reports whether a source has a non-overridable execution mode.
func (Policy) ResolveMode ¶
ResolveMode returns the one effective mode for UI display, agent construction, run records, approvals, and recovery. Bound WeChat and Feishu sessions always execute in yolo mode; a request or persisted capability cannot downgrade them.
type 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 ¶
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 ¶
func (c *RecoveryCoordinator) ScanNow(ctx context.Context) (RunRecoveryResult, error)
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 ¶
func (c *RecoveryCoordinator) Stop(ctx context.Context) error
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 ¶
RefreshOptions are mutable resource-affecting session capabilities.
type RegistryHook ¶
type RegistryHook func(*SessionRuntime) error
RegistryHook injects adapter-specific tools into a fully initialized shared runtime. Hooks run after core tools are registered and before MCP connects, so MCP tools see the final registry without owning Runtime lifecycle.
type RegistryMutator ¶
RegistryMutator is an adapter policy callback for tools that cannot yet be represented as core Runtime capabilities.
type RegistryPolicy ¶
type RegistryPolicy struct {
RegisterDefaults bool
EnablePlanTool *bool
SkillsMgr *skills.Manager
Browser bool
// 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.
type RouterBinding ¶
type RouterBinding struct {
ACPProfileID string
ApprovalStrategy config.ACPPermissionPolicy
Profiles []RouterProfileBinding
PolicyRevision string
}
RouterBinding is the Runtime-owned selection of one or more configured external ACP workers for a Router-mode session. ACPProfileID/ApprovalStrategy remain the primary/default selection for compatibility; Profiles is the ordered allowlist the model may choose from. It contains identifiers and policy only; executable argv and environment remain global configuration.
func (RouterBinding) ProfileIDs ¶
func (binding RouterBinding) ProfileIDs() []string
ProfileIDs returns the ordered bound worker IDs.
type RouterProfileBinding ¶
type RouterProfileBinding struct {
ProfileID string
ApprovalStrategy config.ACPPermissionPolicy
}
RouterProfileBinding is one configured external ACP worker a Router session may target, together with the non-blocking strategy recorded at activation.
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 NewDeliveryReconciledEvent ¶
func NewDeliveryReconciledEvent(sessionID, runID, source string, data json.RawMessage) RunEvent
type RunEventProjector ¶
RunEventProjector is an optional live-transport hook used when an event was persisted as part of an atomic admission transaction. It must not write a second durable row; it only fans the already committed event out to clients.
type RunEventSink ¶
RunEventSink persists run lifecycle events without exposing the adapter implementation to the Runtime.
type RunEventSinkFunc ¶
RunEventSinkFunc adapts a function to the adapter-neutral event sink.
type 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) FinishConversationTurn ¶
func (s RunStore) FinishConversationTurn(run DurableRun, state RunState, message string) error
func (RunStore) FinishRunAndConversationTurn ¶
func (RunStore) LeaseLost ¶
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 (RunStore) PrepareExistingExecution ¶
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) UpdateErrorInfo ¶
func (RunStore) UpdateProgress ¶
func (RunStore) UpdateUsage ¶
func (s RunStore) UpdateUsage(runID string, usage, contextUsage json.RawMessage) error
type RuntimeChangeSetIntegrator ¶
type RuntimeChangeSetIntegrator struct {
Runtime *SessionRuntime
Worktrees *WorktreeManager
}
RuntimeChangeSetIntegrator is the single owner of applying immutable child change-set snapshots to the Router session workspace. It reads only durable child evidence and snapshot bytes; it never copies a mutable child worktree.
func (*RuntimeChangeSetIntegrator) IntegrateChangeSets ¶
func (i *RuntimeChangeSetIntegrator) IntegrateChangeSets(ctx context.Context, selections []agent.ChangeSetSelection) (agent.ChangeSetIntegrationResult, error)
IntegrateChangeSets validates every selection first, acquires the exclusive base-workspace lane, then applies snapshots in request order. A conflict is returned as structured evidence with a nil error so the lead can inspect and recover; setup failures and unsafe snapshots return an 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 RuntimeWorkerQuestionResolver ¶
type RuntimeWorkerQuestionResolver struct {
Runtime *SessionRuntime
}
RuntimeWorkerQuestionResolver adapts the shared DecisionService to Agent Core's WorkerQuestionResolver. It is installed once during manager assembly, at the same layer as the change-set integrator, so internal/agent never imports agentruntime.
func (RuntimeWorkerQuestionResolver) ResolveWorkerQuestion ¶
func (r RuntimeWorkerQuestionResolver) ResolveWorkerQuestion(ctx context.Context, questionID, answer string) error
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 ¶
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
// WorkerBridge is the process-wide loopback MCP bridge shared by sessions. It
// is injected by top-level assembly; a nil bridge simply degrades every ACP
// worker to mcpBridge=unavailable.
WorkerBridge *WorkerBridgeServer
// 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) ActivateRouter ¶
func (r *SessionRuntime) ActivateRouter(ctx context.Context, sessionDir string, settings *config.Settings, binding RouterBinding) error
ActivateRouter is the single activation entry point for TUI and CLI. It validates the selected profile against global configuration and source policy, requires an idle session, then persists the Router binding and mode through the normal replay entries.
Ordering is deliberate: the binding is persisted first. A failure or crash before the mode append leaves a session that is not in Router mode, which resolves as "not Router" and fails closed. The inverse order would expose Router's read-only tool surface without an eligible worker.
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 ¶
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 ¶
func (r *SessionRuntime) ConfigSnapshot() (provider.Provider, string, *provider.Model, string, provider.ThinkingLevel)
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) DisableMailboxWake ¶
func (r *SessionRuntime) DisableMailboxWake()
DisableMailboxWake stops the scheduler and waits for its current admission attempt to unwind.
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) EnableMailboxWake ¶
func (r *SessionRuntime) EnableMailboxWake(ctx context.Context, options MailboxWakeOptions) error
EnableMailboxWake starts the Runtime-owned continuation scheduler. Pending mailbox items are drained only after submission admission; a burst observed before admission therefore becomes one lead Run carrying every item. Repeated calls while the scheduler is active are idempotent.
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) MarkWorkerMessageDelivered ¶
func (r *SessionRuntime) MarkWorkerMessageDelivered(messageID, runID string)
MarkWorkerMessageDelivered records that a queued message was consumed by a lead Run. Callers own the Run identity; the log only records the projection.
func (*SessionRuntime) PendingWorkerQuestions ¶
func (r *SessionRuntime) PendingWorkerQuestions() ([]WorkerQuestionView, error)
PendingWorkerQuestions projects the still-pending worker questions from the durable decision ledger. Worker questions are identified by the Runtime-owned ID prefix, so a lead approval/question is never mistaken for a worker ask.
func (*SessionRuntime) PersistedMode ¶
func (r *SessionRuntime) PersistedMode() string
PersistedMode returns the session's persisted Router/Plan/Agent mode as resolved through the shared source/mode policy, or "" when the session never persisted one. It is the single projection adapters use to adopt a resumed session's mode instead of deriving their own; the durable entry is owned by the session and the resolution by ResolvePolicy.
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) ReconcileManagerBackedTools ¶
func (r *SessionRuntime) ReconcileManagerBackedTools(opts ManagerBackedToolsOptions) (*agent.AgentManager, error)
ReconcileManagerBackedTools is the one Runtime entry point for the "ensure the session manager, then synchronize the manager-backed tool groups" sequence. It decides from resolved Runtime capability (including a bound expert team and Router mode) whether a manager is required, builds or reuses one, and installs/removes the tool groups against that exact manager.
On a build error the current manager handle is preserved and returned with the error so the caller can keep its previous projection instead of silently discarding a manager that is still running children. Passing a nil factory with no current manager is valid: the tool groups are removed. A Rebuild with no factory is an error because silently reusing the handle would defeat the caller's explicit request to discard stale manager state.
When the capability is off the tool groups are always removed, but a manager that still owns a running child is handed back instead of dropped so the adapter can keep observing and cancelling it.
func (*SessionRuntime) RefreshProviderCatalog ¶ added in v1.3.107
func (r *SessionRuntime) RefreshProviderCatalog(catalog ProviderCatalog) error
RefreshProviderCatalog replaces the selectable provider catalog and rebinds this session's current provider/model to the matching fresh catalog instance when one exists. It preserves mode, thinking, and persisted selections; only the constructed provider objects change. Adapters call it after a process-level provider write so an already-open session does not keep using credentials or endpoints from the startup snapshot until a restart.
func (*SessionRuntime) RefreshResourceSettings ¶ added in v1.3.107
func (r *SessionRuntime) RefreshResourceSettings(settings *config.Settings)
RefreshResourceSettings replaces the settings snapshot that backs mutable registry tools, then re-applies the session's current capability flags. It is the settings-only counterpart to RefreshResources for adapters whose settings changed without changing context, Skills, or MCP resources.
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) RefreshRouterTarget ¶
func (r *SessionRuntime) RefreshRouterTarget()
RefreshRouterTarget republishes the current Router target from Runtime facts. The ACP child proxy calls it after a real worker initialize so the latest capability advertisement reaches delegate_worker_mgr without waiting for an adapter-side tool-group synchronization. It is a no-op outside Router mode, and the tool description is read lazily when the next prompt is frozen.
func (*SessionRuntime) ReloadAdditionalDirectories ¶
func (r *SessionRuntime) ReloadAdditionalDirectories(manager *session.Manager) error
ReloadAdditionalDirectories applies the latest persisted directory binding.
func (*SessionRuntime) ReloadConfiguredMCP ¶
func (r *SessionRuntime) ReloadConfiguredMCP(ctx context.Context, policy MCPPolicy) error
ReloadConfiguredMCP reconnects the configured MCP servers and replaces their tools on the shared registry without restarting the process. It is the Runtime-owned hot-reload path: an entry point only decides when to reload and how to project the outcome.
The reload is safe against a live run. A running Agent keeps the tool surface it froze at build time, so replacing the registry entries cannot change an in-flight turn. The next build observes the new tool set.
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) ResolveRouterACPProfile ¶
func (r *SessionRuntime) ResolveRouterACPProfile(settings *config.Settings) (config.ACPAgentProfile, RouterBinding, error)
ResolveRouterACPProfile joins the persisted Router binding with global executable configuration. It is the only Runtime entry point that turns the session's opaque profile ID into an executable ACP profile.
func (*SessionRuntime) ResolveRouterACPProfileByID ¶
func (r *SessionRuntime) ResolveRouterACPProfileByID(settings *config.Settings, profileID string) (config.ACPAgentProfile, RouterBinding, error)
ResolveRouterACPProfileByID resolves one worker from the session's bound allowlist. A Router session may bind several eligible profiles; the model may choose only one of those IDs.
func (*SessionRuntime) ResolveRouterBinding ¶
func (r *SessionRuntime) ResolveRouterBinding(settings *config.Settings) (RouterBinding, error)
ResolveRouterBinding validates every selected worker against current global configuration and returns the normalized multi-profile binding.
func (*SessionRuntime) ResolveWorkerQuestion ¶
func (r *SessionRuntime) ResolveWorkerQuestion(ctx context.Context, questionID, answer string) error
ResolveWorkerQuestion answers a pending worker question. Only the owning session may answer, and a repeated identical answer is idempotent through the DecisionService. The durable resolution event is committed before the pending entry is consumed.
func (*SessionRuntime) RouterActive ¶
func (r *SessionRuntime) RouterActive() bool
RouterActive reports whether this session currently resolves to Router mode. It is the Runtime-owned mode predicate adapters must use instead of re-deriving Router from their own mode field: Router is a Runtime fact resolved from the persisted mode entry plus the activated worker binding.
func (*SessionRuntime) RouterBinding ¶
func (r *SessionRuntime) RouterBinding() (RouterBinding, bool)
RouterBinding returns the persisted Router selection, if this session has one. A copied value prevents adapters from mutating Runtime policy.
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) SetMode ¶
func (r *SessionRuntime) SetMode(value string) error
SetMode applies one requested session mode through the shared resolver, persists the canonical mode entry, and updates the Runtime binding. It is the single mode-mutation entry point for every adapter: mode selection does not depend on a provider/model catalog, so this is deliberately separate from SetConfigOption.
func (*SessionRuntime) SetRouterBinding ¶
func (r *SessionRuntime) SetRouterBinding(binding RouterBinding) error
SetRouterBinding persists one Router worker selection before exposing it in Runtime. Callers must switch the session to ModeRouter separately through applyModeOption/SetMode so mode and binding retain their existing independent replay entries.
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, webSearchEnabled bool)
SynchronizeCoreTools applies mutable registry tools that have no adapter dependency and records the capability state that produced them, so later context/expert refreshes keep the same tools. 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.
func (*SessionRuntime) WorkerMessageContext ¶
func (r *SessionRuntime) WorkerMessageContext(ctx context.Context) ([]WorkerMessage, error)
WorkerMessageContext is a small read-only projection used by adapters that need bridge state without waking the session.
func (*SessionRuntime) WorkerMessageLog ¶
func (r *SessionRuntime) WorkerMessageLog() (*WorkerMessageLog, error)
WorkerMessageLog returns the session's append-only worker message log, creating it on first use. It is Runtime-owned; adapters may read the folded projection but must not write it.
func (*SessionRuntime) WorkerMessages ¶
func (r *SessionRuntime) WorkerMessages() ([]WorkerMessage, error)
WorkerMessages returns the folded worker message projection for this session. It is read-only: unlike WorkerMessageLog it never creates the JSONL file, so a UI projection for a session that never used the bridge has no side effect.
func (*SessionRuntime) WorkerSnapshot ¶
func (r *SessionRuntime) WorkerSnapshot() (WorkerSnapshot, error)
WorkerSnapshot returns the session's read-only worker message and pending question projection. It never mutates decision state.
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" 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 SubagentAttachment ¶
type SubagentAttachment struct {
ID string `json:"id"`
Filename string `json:"filename"`
MediaType string `json:"mediaType"`
Kind AttachmentKind `json:"kind"`
RelativePath string `json:"relativePath"`
Bytes int64 `json:"bytes"`
// Data is the verified attachment payload used only to build the ACP prompt.
// It must never enter a persisted event, task contract projection, or log.
Data []byte `json:"-"`
}
SubagentAttachment is one Runtime-owned input resource authorized for the external worker prompt. Data is already integrity-checked and bounded by the input policy; it is never sourced from model text or an adapter path.
type SubagentDeliverable ¶
type SubagentDeliverable string
SubagentDeliverable is what the worker must return to the lead. The Runtime validates the declaration; it never infers deliverables by parsing prose.
const ( SubagentDeliverableFindings SubagentDeliverable = "findings" SubagentDeliverableChangedFiles SubagentDeliverable = "changed-files" SubagentDeliverableTestEvidence SubagentDeliverable = "test-evidence" SubagentDeliverableReview SubagentDeliverable = "review" )
type SubagentRole ¶
type SubagentRole string
SubagentRole is the declared intent of one delegated Router task. It is a prompt/audit and admission hint, not a filesystem sandbox or a profile capability ceiling. An external Agent is a separately trusted executable and runs its own tools, so MothX cannot confine its writes to the role.
const ( SubagentRoleInvestigate SubagentRole = "investigate" SubagentRoleImplement SubagentRole = "implement" SubagentRoleTest SubagentRole = "test" SubagentRoleReview SubagentRole = "review" SubagentRoleIntegrate SubagentRole = "integrate" )
type SubagentTaskContract ¶
type SubagentTaskContract struct {
Objective string `json:"objective"`
Role SubagentRole `json:"role"`
ReadScope []string `json:"readScope,omitempty"`
WriteScope []string `json:"writeScope,omitempty"`
ExpectedDeliverables []SubagentDeliverable `json:"expectedDeliverables"`
Verification string `json:"verification,omitempty"`
StopConditions []string `json:"stopConditions,omitempty"`
TargetProfile string `json:"targetProfile"`
SystemPromptExtra string `json:"systemPromptExtra,omitempty"`
Attachments []SubagentAttachment `json:"attachments,omitempty"`
}
SubagentTaskContract is the Runtime-owned normalization of a Router delegation. The model supplies the values; Validate bounds them and checks internal consistency. Role and write scope are per-delegation metadata, not profile authorization. Rendering the bounded worker prompt is a separate Runtime step so no adapter builds its own string.
func (SubagentTaskContract) EffectiveRole ¶
func (c SubagentTaskContract) EffectiveRole() SubagentRole
EffectiveRole returns the task role, defaulting to investigate when the model omitted the optional hint.
func (SubagentTaskContract) RenderPrompt ¶
func (c SubagentTaskContract) RenderPrompt(workDir string) string
RenderPrompt builds one bounded text task for the external worker. The contract is already validated; this function only shapes the message and adds MothX-owned child instructions. It never forwards parent prompts, hidden policy, conversation history, or credentials. Attachment identifiers and workspace-relative paths are named, but their bytes are delivered only through the capability-negotiated ACP content blocks.
func (SubagentTaskContract) Validate ¶
func (c SubagentTaskContract) Validate(profile config.ACPAgentProfile) error
Validate bounds a model-supplied task contract and checks its internal consistency. It does not narrow role or write scope against profile settings: those settings no longer grant authority over an external Agent.
type SubmissionAdmission ¶ added in v1.3.105
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
func (h *SubmissionAdmissionHandle) Wait(ctx context.Context) error
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
func (c *SubmissionCoordinator) Acquire(ctx context.Context, runID string, policy SubmitPolicy, admit SubmissionAdmission) (*SubmissionAdmissionHandle, error)
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
func (c *SubmissionCoordinator) Submit(ctx context.Context, runID string, policy SubmitPolicy, admit SubmissionAdmission, run SubmissionRunner) (*ExecutionHandle, error)
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
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
SubmitPolicy controls whether a request may wait behind an execution owned by this Runtime. External ownership is never queued by this coordinator.
type ToolCallPolicyDecision ¶
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
// Mode optionally overrides the mode used for Router-only availability. An
// adapter that projects a locally edited mode (for example the TUI /mode
// command) passes it here instead of duplicating registration logic. Empty
// means use the Runtime's persisted/resolved mode.
Mode string
}
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 WorkerAskFunc ¶
type WorkerAskFunc func(ctx context.Context, question string, options []string, timeout time.Duration) (answer string, status string)
WorkerAskFunc resolves one worker question. Runtime installs the concrete DecisionService-backed implementation; the bridge only blocks on it.
type WorkerBridgeScope ¶
type WorkerBridgeScope struct {
SessionID string
ChildID string
ParentRunID string
ProfileID string
WorkDir string
TaskPrompt string
Capabilities workerdriver.WorkerCapabilities
Messages *WorkerMessageLog
// Notify receives a finding that should enter lead context. It must not
// block; the bridge handler already owns request serialization.
Notify func(WorkerMessage)
// Ask, when installed by Runtime, resolves a blocking worker question.
Ask WorkerAskFunc
// contains filtered or unexported fields
}
WorkerBridgeScope is the per-child authorization and state bound to one MCP token. It contains no enumerable session or child parameter: the token is the only way a request can name a scope.
type WorkerBridgeServer ¶
type WorkerBridgeServer struct {
// contains filtered or unexported fields
}
WorkerBridgeServer owns the process-wide loopback MCP listener and the token registry. It is created by top-level assembly and shared by every session in the process; a session only registers child scopes and revokes them on shutdown.
func NewWorkerBridgeServer ¶
func NewWorkerBridgeServer() *WorkerBridgeServer
NewWorkerBridgeServer creates a bridge server. The listener is lazy: the first worker registration binds a tcp4 loopback port selected by the kernel.
func (*WorkerBridgeServer) Available ¶
func (s *WorkerBridgeServer) Available() bool
Available reports whether this process can expose a bridge. A nil bridge is not available; a created-but-not-yet-started bridge can still be started on demand, so it reports true.
func (*WorkerBridgeServer) Close ¶
func (s *WorkerBridgeServer) Close() error
Close stops the listener and drops every token. It is idempotent and owned by top-level process shutdown, not by a session.
func (*WorkerBridgeServer) EnsureStarted ¶
func (s *WorkerBridgeServer) EnsureStarted() (int, error)
EnsureStarted binds 127.0.0.1:0 on demand. Using an ephemeral tcp4 port means several mothx processes (TUI, serve, ACP Desktop, tests) never collide.
func (*WorkerBridgeServer) Port ¶
func (s *WorkerBridgeServer) Port() int
Port returns the bound loopback port, or zero before the first start.
func (*WorkerBridgeServer) Register ¶
func (s *WorkerBridgeServer) Register(scope *WorkerBridgeScope) (string, []any, error)
Register issues an opaque per-child token and returns the authorized session/new mcpServers payload. A previous token for the same child is revoked: one child has exactly one live bridge credential.
func (*WorkerBridgeServer) Revoke ¶
func (s *WorkerBridgeServer) Revoke(token string)
Revoke removes one token. It is safe on an unknown or already-revoked token.
func (*WorkerBridgeServer) RevokeChild ¶
func (s *WorkerBridgeServer) RevokeChild(sessionID, childID string)
RevokeChild removes one session-scoped child's live bridge credential.
func (*WorkerBridgeServer) RevokeSession ¶
func (s *WorkerBridgeServer) RevokeSession(sessionID string)
RevokeSession removes every credential belonging to one session. Session shutdown calls this; the shared listener stays up for other sessions.
func (*WorkerBridgeServer) SetChildTerminal ¶
func (s *WorkerBridgeServer) SetChildTerminal(sessionID, childID string, terminal bool)
SetChildTerminal records whether the child's current turn has reached a terminal state. A call after the terminal event is rejected as child_terminal; a follow-up turn marks the scope active again.
func (*WorkerBridgeServer) SetIdleTimeout ¶
func (s *WorkerBridgeServer) SetIdleTimeout(timeout time.Duration)
SetIdleTimeout overrides the idle shutdown window. It is intended for tests and diagnostics; a non-positive value restores the default.
type WorkerMessage ¶
type WorkerMessage struct {
ID string `json:"id"`
SessionID string `json:"sessionId"`
ChildID string `json:"childId"`
ParentRunID string `json:"parentRunId,omitempty"`
Direction string `json:"direction"`
Kind string `json:"kind"`
Body string `json:"body"`
DedupeKey string `json:"dedupeKey,omitempty"`
DecisionID string `json:"decisionId,omitempty"`
Status string `json:"status"`
RunID string `json:"runId,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt,omitempty"`
Reason string `json:"reason,omitempty"`
}
WorkerMessage is the folded, read-only projection of one worker message.
func ReadWorkerMessages ¶
func ReadWorkerMessages(sessionDir, sessionID string) ([]WorkerMessage, error)
ReadWorkerMessages folds one existing session's worker message log without creating it. A missing file is an empty projection, and rows belonging to a different session are never projected.
type WorkerMessageLog ¶
type WorkerMessageLog struct {
// contains filtered or unexported fields
}
WorkerMessageLog is the single-writer append-only log for one session. It owns no SQL state; the canonical pending decision remains a DecisionRecord.
func OpenWorkerMessageLog ¶
func OpenWorkerMessageLog(sessionDir, sessionID string) (*WorkerMessageLog, error)
OpenWorkerMessageLog opens (and creates) the session's worker message log. A crash may leave an incomplete final line; reads tolerate it.
func (*WorkerMessageLog) Close ¶
func (l *WorkerMessageLog) Close() error
Close releases one reference to the shared append handle. It is safe to call more than once; the file is closed when the last opener releases it.
func (*WorkerMessageLog) Compact ¶
func (l *WorkerMessageLog) Compact() error
Compact rewrites the log as one created row per current message when it grows past the threshold. The replacement is atomic (temp file + rename), so a crash leaves either the old complete log or the new complete log.
func (*WorkerMessageLog) Create ¶
func (l *WorkerMessageLog) Create(message WorkerMessage) (WorkerMessage, bool, error)
Create appends one created event. A duplicate (child, dedupeKey) returns the existing message instead of appending a second row.
func (*WorkerMessageLog) Find ¶
func (l *WorkerMessageLog) Find(id string) (WorkerMessage, bool, error)
Find returns one folded message by ID.
func (*WorkerMessageLog) List ¶
func (l *WorkerMessageLog) List() ([]WorkerMessage, error)
List folds the event log into the current message state, oldest first.
func (*WorkerMessageLog) Mark ¶
func (l *WorkerMessageLog) Mark(id, op, runID, reason string) error
Mark appends one state transition. The log is append-only: an event for an unknown ID is retained but ignored by the fold, so a stale worker cannot create a phantom message.
func (*WorkerMessageLog) MessagesByChild ¶
func (l *WorkerMessageLog) MessagesByChild(childID string) ([]WorkerMessage, error)
MessagesByChild returns the folded messages for one child, oldest first.
func (*WorkerMessageLog) Path ¶
func (l *WorkerMessageLog) Path() string
Path returns the log path for diagnostics only; it is never exposed to a worker or persisted in child metadata.
type WorkerQuestionView ¶
type WorkerQuestionView struct {
ID string `json:"id"`
SessionID string `json:"sessionId"`
RunID string `json:"runId,omitempty"`
ChildID string `json:"childId,omitempty"`
Question string `json:"question"`
Options []string `json:"options,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
WorkerQuestionView is the read-only adapter projection of one pending worker question. The authoritative state remains the durable DecisionRecord; a UI may render this but must not answer through it.
type WorkerSnapshot ¶
type WorkerSnapshot struct {
Messages []WorkerMessage `json:"messages"`
PendingQuestions []WorkerQuestionView `json:"pendingQuestions"`
}
WorkerSnapshot is the read-only worker projection shared by every adapter. Messages are the JSONL evidence log; PendingQuestions derive from the authoritative durable decision ledger. Neither field carries a token.
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) CaptureChangeSet ¶
func (m *WorktreeManager) CaptureChangeSet(ctx context.Context, id, baseRevision string, patchLimit int) (worktree.ChangeSet, error)
CaptureChangeSet captures a bounded snapshot for a registered worktree. The registry is the ownership authority, so an arbitrary path not created by the Runtime is rejected even if it happens to be a git worktree.
func (*WorktreeManager) Create ¶ added in v1.3.103
func (m *WorktreeManager) Create(ctx context.Context, req CreateWorktreeRequest) (session.Worktree, error)
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
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) ResolveOrCreateWorktree ¶
func (m *WorktreeManager) ResolveOrCreateWorktree(ctx context.Context, baseCwd, key string) (session.Worktree, error)
ResolveOrCreateWorktree is ResolveOrCreate with the Runtime-owned identity of the resolved worktree retained for child-history and change-set recording.
func (*WorktreeManager) Revision ¶
Revision resolves the commit currently checked out by a managed 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
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.
func (*WorktreeProviderAdapter) ResolveWorktreeMetadata ¶
func (p *WorktreeProviderAdapter) ResolveWorktreeMetadata(baseCwd string, spec agent.WorktreeSpec) (agent.WorktreeResolution, error)
ResolveWorktreeMetadata implements agent.WorktreeMetadataProvider.
Source Files
¶
- acp_child.go
- acp_process.go
- acp_process_unix.go
- acp_worker_bridge.go
- acp_worker_decisions.go
- acp_worker_fs.go
- acp_worker_pool.go
- acp_worker_remote.go
- acp_worker_terminal.go
- acp_worker_workspace.go
- agent_build.go
- agent_manager.go
- artifact.go
- attach.go
- change_set_integration.go
- child_run_history.go
- decision.go
- decision_events.go
- decision_record.go
- decision_replay.go
- delivery.go
- delivery_coordinator.go
- delivery_events.go
- delivery_replay.go
- durable_ops.go
- error_info.go
- execution.go
- execution_admission.go
- execution_events.go
- execution_local_projection.go
- execution_observation.go
- execution_ownership_projection.go
- execution_persistence.go
- execution_snapshot.go
- execution_stop.go
- expert.go
- fork.go
- idempotency.go
- input.go
- input_materializer.go
- knowledge_calls.go
- knowledge_configured_by.go
- knowledge_context.go
- knowledge_cron.go
- knowledge_document_relations.go
- knowledge_imports.go
- knowledge_index_job.go
- knowledge_indexer.go
- knowledge_librarian.go
- knowledge_mcp.go
- knowledge_supersedes.go
- knowledgebase.go
- mailbox_wake.go
- maintenance_cron.go
- policy.go
- recovery_coordinator.go
- registry.go
- router.go
- router_presets.go
- router_profiles.go
- router_role_playbook.go
- router_task_contract.go
- run_event.go
- run_queries.go
- run_recovery.go
- run_replay.go
- run_store.go
- session_directories.go
- session_event_store.go
- session_lifecycle.go
- session_options.go
- session_runtime.go
- source.go
- storage_reconcile.go
- submission_coordinator.go
- tool_fence.go
- tool_policy.go
- tool_sync.go
- worker_bridge.go
- worker_capabilities.go
- worker_messages.go
- worker_questions.go
- worker_runtime.go
- worktrees.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package workerdriver resolves the typed capability surface of one external ACP worker.
|
Package workerdriver resolves the typed capability surface of one external ACP worker. |