daemon

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: MIT Imports: 98 Imported by: 0

Documentation

Overview

Package daemon wires the AGH runtime packages into a single long-lived process.

Index

Constants

View Source
const (
	// RestartOperationEnvKey carries the restart operation id from the helper to the replacement daemon.
	RestartOperationEnvKey = "AGH_INTERNAL_RESTART_OPERATION_ID"
)

Variables

View Source
var (
	// ErrAlreadyRunning reports that another daemon process currently owns the singleton lock.
	ErrAlreadyRunning = errors.New("daemon: already running")
)
View Source
var (
	// ErrRestartOperationNotFound reports a missing persisted restart operation.
	ErrRestartOperationNotFound = errors.New("daemon: restart operation not found")
)

Functions

func RemoveInfo

func RemoveInfo(path string) error

RemoveInfo removes daemon.json if it exists.

func RunRelaunchHelper

func RunRelaunchHelper(ctx context.Context, cfg RelaunchHelperConfig) error

RunRelaunchHelper runs the detached helper that waits for daemon shutdown resources to release and then launches the replacement daemon.

func WriteInfo

func WriteInfo(path string, info Info) (returnErr error)

WriteInfo writes daemon.json atomically via temp file and rename.

Types

type BridgeSecretResolver

type BridgeSecretResolver interface {
	ResolveBridgeSecret(ctx context.Context, binding bridgepkg.BridgeSecretBinding) (string, error)
}

BridgeSecretResolver resolves daemon-owned bound secret material for one persisted bridge secret binding.

type ComposedAssembler

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

ComposedAssembler assembles selected startup prompt sections around the base agent prompt.

func NewComposedAssembler

func NewComposedAssembler(opts ...ComposedAssemblerOption) *ComposedAssembler

NewComposedAssembler constructs a ComposedAssembler from startup section descriptors.

func (*ComposedAssembler) Assemble

func (a *ComposedAssembler) Assemble(
	ctx context.Context,
	agent aghconfig.AgentDef,
	workspace *workspacepkg.ResolvedWorkspace,
) (string, error)

Assemble renders the selected startup sections using a baseline startup context for callers that only know about the legacy assembler seam.

func (*ComposedAssembler) AssembleStartup

func (a *ComposedAssembler) AssembleStartup(
	ctx context.Context,
	startup session.StartupPromptContext,
	agent aghconfig.AgentDef,
	workspace *workspacepkg.ResolvedWorkspace,
) (string, error)

AssembleStartup renders eligible prepend sections, the trimmed base prompt, and eligible append sections into one composed startup system prompt.

type ComposedAssemblerOption

type ComposedAssemblerOption func(*ComposedAssembler)

ComposedAssemblerOption customizes the prompt section chain for a ComposedAssembler.

func WithAppendPromptProviders

func WithAppendPromptProviders(providers ...session.PromptProvider) ComposedAssemblerOption

WithAppendPromptProviders preserves the legacy append provider option by wrapping providers in explicit append descriptors.

func WithPrependPromptProviders

func WithPrependPromptProviders(providers ...session.PromptProvider) ComposedAssemblerOption

WithPrependPromptProviders preserves the legacy prepend provider option by wrapping providers in explicit prepend descriptors.

func WithPromptSectionDescriptors

func WithPromptSectionDescriptors(descriptors ...PromptSectionDescriptor) ComposedAssemblerOption

WithPromptSectionDescriptors appends explicit startup prompt section descriptors to the assembler.

func WithSectionSelector

func WithSectionSelector(selector *SectionSelector) ComposedAssemblerOption

WithSectionSelector installs the daemon-owned startup section selector.

type ConfigLoader

type ConfigLoader func() (aghconfig.Config, error)

ConfigLoader resolves the daemon-level runtime configuration.

type CoordinatorConfigResolver

type CoordinatorConfigResolver interface {
	ResolveCoordinatorConfig(ctx context.Context, workspaceID string) (aghconfig.CoordinatorConfig, error)
}

CoordinatorConfigResolver resolves coordinator policy without starting coordinator behavior.

type Daemon

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

Daemon is the sole AGH composition root.

func New

func New(opts ...Option) (*Daemon, error)

New constructs the daemon composition root.

func (*Daemon) Boundaries

func (d *Daemon) Boundaries(context.Context) error

Boundaries performs a best-effort import boundary verification for local source checkouts.

func (*Daemon) GetRestartOperation

func (d *Daemon) GetRestartOperation(_ context.Context, operationID string) (RestartOperation, error)

GetRestartOperation reads one persisted restart operation by id.

func (*Daemon) RequestRestart

func (d *Daemon) RequestRestart(ctx context.Context) (RestartOperation, error)

RequestRestart creates the persisted restart operation, launches the detached relaunch helper, and signals the running daemon to enter its normal graceful shutdown path.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context) error

Run boots the daemon, blocks until signal or context cancellation, then performs graceful shutdown.

func (*Daemon) Shutdown

func (d *Daemon) Shutdown(ctx context.Context) error

Shutdown gracefully tears down the daemon in the required order.

type DetachedRunMetadata

type DetachedRunMetadata struct {
	TaskID    string
	TaskRunID string
}

DetachedRunMetadata carries detached task-runtime correlation fields.

type DetachedRunMode

type DetachedRunMode string

DetachedRunMode identifies detached task-runtime behavior for the resolved policy.

const (
	// DetachedRunModeNone means detached task-runtime behavior is not enabled.
	DetachedRunModeNone DetachedRunMode = "none"
	// DetachedRunModeTaskRuntime means detached work reuses the existing task runtime.
	DetachedRunModeTaskRuntime DetachedRunMode = "task_runtime"
)

type DreamTrigger

type DreamTrigger = core.DreamTrigger

DreamTrigger exposes consolidation controls and health state to transport layers.

type HarnessAugmenter

type HarnessAugmenter string

HarnessAugmenter identifies a prompt input augmenter managed by harness policy.

const (
	// HarnessAugmenterSituation injects fresh bounded AGH situation context.
	HarnessAugmenterSituation HarnessAugmenter = "situation"
	// HarnessAugmenterSkills injects the current effective skills catalog.
	HarnessAugmenterSkills HarnessAugmenter = "skills"
	// HarnessAugmenterDurableMemory enables the durable memory recall augmenter.
	HarnessAugmenterDurableMemory HarnessAugmenter = "durable_memory"
)

type HarnessContextResolver

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

HarnessContextResolver derives harness policy from durable session state plus turn-origin metadata.

func NewHarnessContextResolver

func NewHarnessContextResolver(runtime HarnessRuntimeSignals) *HarnessContextResolver

NewHarnessContextResolver constructs a daemon-owned harness context resolver.

func (*HarnessContextResolver) Resolve

Resolve derives one authoritative harness context from explicit inputs.

func (*HarnessContextResolver) ResolvePrompt

func (r *HarnessContextResolver) ResolvePrompt(
	info *session.Info,
	source session.TurnSource,
	meta acp.PromptMeta,
) (ResolvedHarnessContext, error)

ResolvePrompt resolves one live prompt-turn policy from session metadata.

func (*HarnessContextResolver) ResolveStartup

ResolveStartup resolves startup policy from durable session context.

type HarnessPromptSection

type HarnessPromptSection string

HarnessPromptSection identifies a startup prompt section managed by harness policy.

const (
	// HarnessPromptSectionRuntimeIdentity injects the daemon-owned AGH runtime envelope.
	HarnessPromptSectionRuntimeIdentity HarnessPromptSection = "runtime_identity"
	// HarnessPromptSectionSituation injects the bounded AGH situation context.
	HarnessPromptSectionSituation HarnessPromptSection = "situation"
	// HarnessPromptSectionMemory injects durable memory prompt context.
	HarnessPromptSectionMemory HarnessPromptSection = "memory"
	// HarnessPromptSectionSkills injects the active skills catalog prompt context.
	HarnessPromptSectionSkills HarnessPromptSection = "skills"
	// HarnessPromptSectionTools injects AGH-native tool discovery and invocation guidance.
	HarnessPromptSectionTools HarnessPromptSection = "tools"
	// HarnessPromptSectionNetwork injects the bundled AGH network startup section.
	HarnessPromptSectionNetwork HarnessPromptSection = "network"
)

type HarnessResolutionInput

type HarnessResolutionInput struct {
	Surface ResolutionSurface
	Session HarnessSessionInput
	Turn    HarnessTurnRequest
}

HarnessResolutionInput captures one resolver request.

type HarnessRuntimeSignals

type HarnessRuntimeSignals struct {
	RuntimeIdentityPromptSectionEnabled bool
	SituationPromptSectionEnabled       bool
	MemoryPromptSectionEnabled          bool
	SkillsPromptSectionEnabled          bool
	ToolsPromptSectionEnabled           bool
	SkillsAugmenter                     bool
	SituationAugmenter                  bool
	DurableMemoryAugmenter              bool
	SyntheticTurnsEnabled               bool
	DetachedTaskRuntimeEnabled          bool
}

HarnessRuntimeSignals captures daemon-owned capability flags available to the resolver.

type HarnessSessionContext

type HarnessSessionContext struct {
	Type         session.Type
	SessionClass SessionClass
	Channel      string
	ChannelBound bool
	WorkspaceID  string
	Workspace    string
	AgentName    string
}

HarnessSessionContext is the normalized durable session context emitted by the resolver.

type HarnessSessionInput

type HarnessSessionInput struct {
	Type        session.Type
	Channel     string
	WorkspaceID string
	Workspace   string
	AgentName   string
}

HarnessSessionInput carries durable session metadata into the resolver.

type HarnessTurnContext

type HarnessTurnContext struct {
	Origin     TurnOrigin
	PromptMeta acp.PromptMeta
	Synthetic  *SyntheticTurnMetadata
	Detached   *DetachedRunMetadata
}

HarnessTurnContext is the normalized turn context emitted by the resolver.

type HarnessTurnRequest

type HarnessTurnRequest struct {
	Source     session.TurnSource
	PromptMeta acp.PromptMeta
	Synthetic  *SyntheticTurnMetadata
	Detached   *DetachedRunMetadata
}

HarnessTurnRequest carries turn-time metadata into the resolver.

type Info

type Info struct {
	PID       int          `json:"pid"`
	Port      int          `json:"port"`
	StartedAt time.Time    `json:"started_at"`
	Network   *NetworkInfo `json:"network,omitempty"`
}

Info is the persisted daemon discovery record written to daemon.json.

func ReadInfo

func ReadInfo(path string) (Info, error)

ReadInfo loads daemon.json from disk.

func (Info) Validate

func (i Info) Validate() error

Validate ensures the persisted daemon info remains usable for discovery.

type Lock

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

Lock owns the singleton daemon file lock.

func AcquireLock

func AcquireLock(path string, pid int) (*Lock, error)

AcquireLock acquires the singleton daemon lock and records the current PID in the lock file.

func (*Lock) Path

func (l *Lock) Path() string

Path reports the on-disk daemon lock file path.

func (*Lock) Release

func (l *Lock) Release() error

Release clears the lock file contents and releases the advisory file lock.

func (*Lock) StalePID

func (l *Lock) StalePID() int

StalePID reports the recovered stale daemon PID, if any.

type NetworkInfo

type NetworkInfo struct {
	Enabled      bool   `json:"enabled"`
	Status       string `json:"status"`
	ListenerHost string `json:"listener_host,omitempty"`
	ListenerPort int    `json:"listener_port,omitempty"`
}

NetworkInfo is the persisted daemon-safe network diagnostics snapshot.

func (NetworkInfo) Validate

func (n NetworkInfo) Validate() error

Validate ensures the persisted network diagnostics remain usable.

type Observer

type Observer interface {
	core.Observer
	session.Notifier
	Reconcile(ctx context.Context) (store.ReconcileResult, error)
}

Observer is the daemon observer surface used for transport wiring and reconciliation.

type Option

type Option func(*Daemon)

Option customizes daemon construction.

func WithBoundaryVerification

func WithBoundaryVerification(enabled bool) Option

WithBoundaryVerification enables best-effort import boundary verification on boot.

func WithBridgeSecretResolver

func WithBridgeSecretResolver(resolver BridgeSecretResolver) Option

WithBridgeSecretResolver injects the daemon-owned resolver used to convert bridge secret bindings into launch-time bound secret material. When this option is not supplied, daemon boot wires the canonical vault-backed resolver.

func WithConfig

func WithConfig(cfg *aghconfig.Config) Option

WithConfig overrides daemon-level configuration loading.

func WithConfigLoader

func WithConfigLoader(loader ConfigLoader) Option

WithConfigLoader overrides daemon-level configuration loading.

func WithHTTPServerFactory

func WithHTTPServerFactory(factory ServerFactory) Option

WithHTTPServerFactory overrides HTTP server construction.

func WithHomePaths

func WithHomePaths(homePaths aghconfig.HomePaths) Option

WithHomePaths overrides the resolved AGH home layout.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger injects the daemon logger.

func WithNow

func WithNow(now func() time.Time) Option

WithNow overrides the daemon clock, mainly for tests.

func WithSignalBridge

func WithSignalBridge(ch <-chan os.Signal) Option

WithSignalBridge overrides OS signal delivery, mainly for tests.

func WithUDSServerFactory

func WithUDSServerFactory(factory ServerFactory) Option

WithUDSServerFactory overrides UDS server construction.

type PromptSectionBudgetBehavior

type PromptSectionBudgetBehavior string

PromptSectionBudgetBehavior controls how an oversized section is handled.

const (
	// PromptSectionBudgetBehaviorTrim truncates the section to its declared budget.
	PromptSectionBudgetBehaviorTrim PromptSectionBudgetBehavior = "trim"
	// PromptSectionBudgetBehaviorOmit drops the section when it exceeds budget.
	PromptSectionBudgetBehaviorOmit PromptSectionBudgetBehavior = "omit"
)

type PromptSectionDescriptor

type PromptSectionDescriptor struct {
	Name             string
	Position         PromptSectionPosition
	Order            int
	Budget           int
	BudgetBehavior   PromptSectionBudgetBehavior
	Provider         session.PromptProvider
	Predicate        SectionPredicate
	StartupPredicate StartupSectionPredicate
}

PromptSectionDescriptor describes one startup prompt section provider plus its ordering, policy eligibility, and budget behavior.

type PromptSectionPosition

type PromptSectionPosition string

PromptSectionPosition identifies whether a startup section renders before or after the base agent prompt.

const (
	// PromptSectionPositionPrepend renders the section before the base prompt.
	PromptSectionPositionPrepend PromptSectionPosition = "prepend"
	// PromptSectionPositionAppend renders the section after the base prompt.
	PromptSectionPositionAppend PromptSectionPosition = "append"
)

type ReentryMode

type ReentryMode string

ReentryMode identifies how a resolved policy participates in synthetic reentry.

const (
	// ReentryModeNone means the turn is not synthetic reentry.
	ReentryModeNone ReentryMode = "none"
	// ReentryModeSynthetic means the turn is a validated synthetic reentry path.
	ReentryModeSynthetic ReentryMode = "synthetic"
)

type Registry

Registry is the narrowed global database surface shared by observe and workspace.

type RelaunchHelperConfig

type RelaunchHelperConfig struct {
	HomePaths      aghconfig.HomePaths
	OperationID    string
	Executable     func() (string, error)
	Sandbox        []string
	PollInterval   time.Duration
	ReleaseTimeout time.Duration
	ReadyTimeout   time.Duration
	ExitDrainWait  time.Duration
}

RelaunchHelperConfig configures one internal `agh daemon relaunch` execution.

type ResolutionSurface

type ResolutionSurface string

ResolutionSurface identifies which runtime seam is consuming the resolver.

const (
	// ResolutionSurfaceStartup resolves startup prompt policy.
	ResolutionSurfaceStartup ResolutionSurface = "startup"
	// ResolutionSurfaceTurn resolves live prompt-turn policy.
	ResolutionSurfaceTurn ResolutionSurface = "turn"
)

type ResolvedHarnessContext

type ResolvedHarnessContext struct {
	Surface ResolutionSurface
	Session HarnessSessionContext
	Turn    HarnessTurnContext
	Policy  ResolvedHarnessPolicy
}

ResolvedHarnessContext captures the normalized inputs plus the derived policy.

type ResolvedHarnessPolicy

type ResolvedHarnessPolicy struct {
	SessionClass      SessionClass
	TurnOrigin        TurnOrigin
	IncludeSections   []HarnessPromptSection
	EnableAugmenters  []HarnessAugmenter
	ReentryMode       ReentryMode
	DetachedRunMode   DetachedRunMode
	DiagnosticLabel   string
	ObservabilityTags map[string]string
}

ResolvedHarnessPolicy is the authoritative daemon-owned harness runtime policy.

type RestartOperation

type RestartOperation struct {
	OperationID        string        `json:"operation_id"`
	Status             RestartStatus `json:"status"`
	OldPID             int           `json:"old_pid"`
	OldStartedAt       time.Time     `json:"old_started_at"`
	OldSocketPath      string        `json:"old_socket_path"`
	NewPID             int           `json:"new_pid,omitempty"`
	ActiveSessionCount int           `json:"active_session_count"`
	FailureReason      string        `json:"failure_reason,omitempty"`
	StartedAt          time.Time     `json:"started_at"`
	UpdatedAt          time.Time     `json:"updated_at"`
	CompletedAt        *time.Time    `json:"completed_at,omitempty"`
}

RestartOperation is the persisted restart status record stored under ~/.agh/restarts/.

func (RestartOperation) Validate

func (o RestartOperation) Validate() error

Validate ensures the persisted restart operation is structurally usable.

type RestartStatus

type RestartStatus string

RestartStatus is the durable lifecycle state of one daemon restart operation.

const (
	RestartStatusPending        RestartStatus = "pending"
	RestartStatusStopping       RestartStatus = "stopping"
	RestartStatusWaitingRelease RestartStatus = "waiting_release"
	RestartStatusStarting       RestartStatus = "starting"
	RestartStatusReady          RestartStatus = "ready"
	RestartStatusFailed         RestartStatus = "failed"
)

type RuntimeDeps

type RuntimeDeps struct {
	Config              aghconfig.Config
	HomePaths           aghconfig.HomePaths
	Logger              *slog.Logger
	Sessions            SessionManager
	Tasks               taskpkg.Manager
	Network             core.NetworkService
	ToolRegistry        toolspkg.Registry
	Toolsets            core.ToolsetRegistry
	ToolApprovals       toolspkg.ApprovalTokenIssuer
	HostedMCP           *mcppkg.HostedService
	Observer            Observer
	Automation          core.AutomationManager
	Bridges             core.BridgeService
	Notifications       core.NotificationPresetService
	Registry            Registry
	MemoryStore         *memory.Store
	MemoryExtractor     core.MemoryExtractorService
	MemoryProviders     core.MemoryProviderService
	MemorySessionLedger core.MemorySessionLedgerService
	WorkspaceResolver   workspacepkg.RuntimeResolver
	WorkspaceService    core.WorkspaceService
	AgentCatalog        core.AgentCatalog
	ModelCatalog        core.ModelCatalogService
	AgentContext        *situation.Service
	SoulAuthoring       core.SoulAuthoringService
	SoulRefresher       core.SoulRefresher
	HeartbeatAuthor     core.HeartbeatAuthoringService
	HeartbeatStatus     core.HeartbeatStatusService
	HeartbeatWake       core.HeartbeatWakeService
	SessionHealth       core.SessionHealthReader
	WakeEvents          core.HeartbeatWakeEventReader
	CoordinatorConfig   CoordinatorConfigResolver
	SkillsRegistry      core.SkillsRegistry
	DreamTrigger        DreamTrigger
	Settings            core.SettingsService
	SettingsRestart     core.SettingsRestartController
	SettingsUpdate      core.SettingsUpdateController
	SupportBundles      core.SupportBundleService
	Vault               core.VaultService
	Extensions          udsapi.ExtensionService
	Bundles             core.BundleService
	Resources           core.ResourceService
	StartedAt           time.Time
}

RuntimeDeps captures the composition-root dependencies available to server factories.

type SectionPredicate

type SectionPredicate func(ResolvedHarnessPolicy) bool

SectionPredicate decides whether a prompt section is eligible for one resolved startup policy.

type SectionSelector

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

SectionSelector resolves startup policy and selects eligible startup prompt sections before final assembly.

func NewSectionSelector

func NewSectionSelector(
	resolver *HarnessContextResolver,
	recorder *harnessLifecycleRecorder,
) *SectionSelector

NewSectionSelector constructs a daemon-owned startup section selector.

func (*SectionSelector) Select

Select resolves startup policy for the provided startup context and returns the eligible startup sections in deterministic order without duplicates.

type Server

type Server interface {
	Start(ctx context.Context) error
	Shutdown(ctx context.Context) error
}

Server is a daemon-owned runtime component with explicit start and shutdown phases.

type ServerFactory

type ServerFactory func(ctx context.Context, deps RuntimeDeps) (Server, error)

ServerFactory constructs runtime components such as HTTP and UDS servers.

type SessionClass

type SessionClass string

SessionClass is the session-side harness axis derived from durable session metadata rather than a top-level profile enum.

const (
	// SessionClassInteractive identifies user-owned interactive sessions.
	SessionClassInteractive SessionClass = "interactive"
	// SessionClassDream identifies dream consolidation sessions.
	SessionClassDream SessionClass = "dream"
	// SessionClassSystem identifies daemon-owned system sessions.
	SessionClassSystem SessionClass = "system"
	// SessionClassCoordinator identifies daemon-owned workspace coordinator sessions.
	SessionClassCoordinator SessionClass = "coordinator"
	// SessionClassSpawned identifies bounded child worker sessions.
	SessionClassSpawned SessionClass = "spawned"
)

type SessionManager

type SessionManager = core.SessionManager

SessionManager is the shared transport-facing session surface consumed by daemon/.

type SessionManagerDeps

type SessionManagerDeps struct {
	HomePaths            aghconfig.HomePaths
	Logger               *slog.Logger
	Notifier             session.Notifier
	Hooks                session.HookSet
	PromptAssembler      session.PromptAssembler
	StartupPromptOverlay session.StartupPromptOverlay
	PromptInputAugmenter session.PromptInputAugmenter
	MemoryStore          *memory.Store
	LedgerMaterializer   session.LedgerMaterializer
	AgentResolver        session.AgentResolver
	SkillRegistry        session.SkillRegistry
	MCPResolver          session.MCPResolver
	WorkspaceResolver    workspacepkg.RuntimeResolver
	SandboxRegistry      *sandbox.Registry
	SessionSupervision   aghconfig.SessionSupervisionConfig
	SessionBusyInput     aghconfig.SessionBusyInputConfig
	SessionInputQueue    store.SessionInputQueueStore
	SessionHealthConfig  aghconfig.HeartbeatConfig
	ProcessRegistry      *toolruntime.Registry
	HostedMCP            session.HostedMCPLauncher
	ProviderSecrets      session.ProviderSecretResolver
	SoulStore            session.SoulSnapshotStore
	SoulRunChecker       session.SoulRunActivityChecker
	SessionHealthStore   session.HealthStore
}

SessionManagerDeps captures the composition-root dependencies needed to create a session manager.

type StartupSectionPredicate

type StartupSectionPredicate func(session.StartupPromptContext) bool

StartupSectionPredicate decides whether a prompt section is eligible for the concrete startup context being assembled.

type SyntheticTurnMetadata

type SyntheticTurnMetadata struct {
	Reason      string
	Trigger     string
	SourceTask  string
	SourceRunID string
}

SyntheticTurnMetadata carries validated daemon-only synthetic reentry metadata.

type TurnOrigin

type TurnOrigin string

TurnOrigin identifies the resolved harness origin for one turn.

const (
	// TurnOriginUser identifies a standard user-driven turn.
	TurnOriginUser TurnOrigin = "user"
	// TurnOriginNetwork identifies a network-originated turn.
	TurnOriginNetwork TurnOrigin = "network"
	// TurnOriginSynthetic identifies a daemon-owned synthetic turn.
	TurnOriginSynthetic TurnOrigin = "synthetic"
)

Jump to

Keyboard shortcuts

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