bootstrap

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 114 Imported by: 0

Documentation

Overview

Package bootstrap provides shared server initialization logic

Package bootstrap provides shared server initialization logic

Package bootstrap provides shared server initialization logic

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyRuntimeDataDirDefaults

func ApplyRuntimeDataDirDefaults(cfg *config.Config, dataDir string)

ApplyRuntimeDataDirDefaults aligns config defaults that still use legacy cwd-relative data paths with the runtime's resolved data directory. Explicit custom paths are preserved.

func BindRuntimeDreamCron

func BindRuntimeDreamCron(handler *cron.Handler, service *memory.DreamService)

func InitMetrics

func InitMetrics(dataDir string, sharedDB *sql.DB) (*metrics.Collector, *metrics.MetricsWriter)

InitMetrics initializes metrics services.

func InitMetricsWithReadDB

func InitMetricsWithReadDB(dataDir string, sharedDB, readDB *sql.DB) (*metrics.Collector, *metrics.MetricsWriter)

InitMetricsWithReadDB initializes metrics services with separate write/read handles when metrics persistence reuses the shared application database.

func InitWebPushSender

func InitWebPushSender(db *sql.DB, kv kvstore.Store, logger *zap.Logger) *webpush.Sender

InitWebPushSender creates a Web Push sender with VAPID keys. Returns nil if initialization fails (non-fatal).

func InitWebPushSenderWithReadDB

func InitWebPushSenderWithReadDB(writeDB, readDB *sql.DB, kv kvstore.Store, logger *zap.Logger) *webpush.Sender

InitWebPushSenderWithReadDB creates a Web Push sender with separate write and read database handles.

func IsZimaOS

func IsZimaOS() bool

IsZimaOS returns true if running on ZimaOS (a Linux-based NAS OS). It checks for the presence of ZimaOS-specific paths or environment variables.

func LoadProvidersFromPool

func LoadProvidersFromPool(pool *providerpool.Pool, llmRegistry *llm.ProviderRegistry)

LoadProvidersFromPool loads providers from Provider Pool and registers them in LLM registry

func NewRuntimeExecConfig

func NewRuntimeExecConfig(dataDir string, allowedDirs []string) tools.ExecConfig

NewRuntimeExecConfig returns the shared exec runtime defaults used by Blue entrypoints. CLI shells such as `blue` and embedded surfaces such as future bluelib exec entrypoints should source host-exec defaults from here so the behavior stays aligned with the runtime bundle.

func NewRuntimeFormfillerHandler

func NewRuntimeFormfillerHandler() *formfiller.Handler

NewRuntimeFormfillerHandler keeps formfiller disabled at runtime. Route registration falls back to the existing feature-disabled surface when this returns nil.

func NewSandboxManagerFromConfig

func NewSandboxManagerFromConfig(cfg *config.Config) (*sandbox.Manager, error)

NewSandboxManagerFromConfig builds a sandbox manager from the loaded app config. Returning nil, nil means sandbox is disabled by configuration.

func OpenRuntimeDatabaseWithPath

func OpenRuntimeDatabaseWithPath(dataDir string, logger *zap.Logger) (*database.SQLiteConn, error)

OpenRuntimeDatabaseWithPath opens runtime.db at the specified data directory This is a convenience function for use outside of the bootstrap package.

func RegisterAllRoutes

func RegisterAllRoutes(e *echo.Echo, deps *RoutesDeps) *echo.Group

RegisterAllRoutes registers all API routes on the Echo instance. Returns the authenticated API group for late-binding route registration.

func ResolveAuditIPCSocketPath

func ResolveAuditIPCSocketPath(dataDir string) string

func ResolveBuiltinToolAllowedPaths

func ResolveBuiltinToolAllowedPaths(appCfg *config.Config, dataDir string) []string

func ResolveWorkspaceDir

func ResolveWorkspaceDir(dataDir string, appCfg *config.Config) string

ResolveWorkspaceDir returns the shared runtime workspace directory. Explicit non-default workspace settings win; otherwise we keep the historical data-dir workspace to avoid surprising runtime behavior. On ZimaOS, defaults to /media/ZimaOS-HD/AppData/zimaos-blue

func ResolveWorkspaceSkillsDir

func ResolveWorkspaceSkillsDir(dataDir string, appCfg *config.Config) string

func ResolveZimaOSDataDir

func ResolveZimaOSDataDir(dataDir string) string

ResolveZimaOSDataDir returns the ZimaOS-specific data directory. On ZimaOS: /media/ZimaOS-HD/AppData/zimaos-blue Otherwise falls back to the standard dataDir.

func ResolveZimaOSWorkspaceDir

func ResolveZimaOSWorkspaceDir(dataDir string) string

ResolveZimaOSWorkspaceDir returns the workspace directory for ZimaOS. On ZimaOS, this is the AppData directory itself (not a subdirectory).

func RunStartupMemoryTrimLoop

func RunStartupMemoryTrimLoop(ctx context.Context, logger *zap.Logger, delays ...time.Duration)

RunStartupMemoryTrimLoop schedules best-effort heap reclamation after startup. It is intended to run in a lifecycle-managed goroutine once the server is ready.

func StartupMemoryTrimSchedule

func StartupMemoryTrimSchedule() []time.Duration

StartupMemoryTrimSchedule returns the default post-start trim checkpoints.

func StartupTraceEnabled

func StartupTraceEnabled() bool

StartupTraceEnabled returns true when startup timing logs should be emitted.

func TuneGC

func TuneGC()

TuneGC configures Go runtime GC for lower memory usage. GOGC=50 balances memory vs CPU; 128MB soft limit avoids excessive GC thrashing. Should be called early in main/runServer before allocations ramp up.

Types

type HarnessRuntimeBundle

type HarnessRuntimeBundle struct {
	Controller       *harness.Controller
	GroupDispatcher  *harness.GroupDispatcher
	RunTracer        *harness.RunTraceCollector
	RuntimeObserver  tools.RuntimeEventObserver
	SubagentExecutor tools.SubagentExecutor
	WriteGuard       tools.WritePathGuard
	ExecGuard        tools.ExecPathGuard
}

HarnessRuntimeBundle centralizes the shared harness runtime wiring used by chat, deep research, agent tasks, and harness-backed subagents.

type PushServiceDeps

type PushServiceDeps struct {
	DB          *sql.DB
	ReadDB      *sql.DB
	MemoryStore *memory.Store
	CronGetSvc  func() *cron.Service // lazy cron getter (may return nil)
	SSEBroker   *sse.Broker
	WPSender    *webpush.Sender // optional, may be nil
	Logger      *zap.Logger
}

PushServiceDeps holds dependencies for InitPushService.

type PushServiceResult

type PushServiceResult struct {
	IPC     sockipc.PushBackend // for IPC registration
	Service *push.Service       // for skill/tool wiring
}

PushServiceResult holds the outputs of InitPushService.

func InitPushService

func InitPushService(deps *PushServiceDeps) *PushServiceResult

InitPushService creates and wires the push notification service. Returns nil if initialization fails.

type RoutesDeps

type RoutesDeps struct {
	DB     *sql.DB
	Config *config.Config
	// DisablePromptGuard disables chat prompt interception for controlled runs.
	DisablePromptGuard bool
	ServerConfig       *ServerConfig
	Services           *Services
	Logger             *zap.Logger
	Ctx                context.Context
	MetricsWriter      *metrics.MetricsWriter
	MetricsCollector   *metrics.Collector
	FlagEvaluator      *config.FlagEvaluator
	ChatHandler        *server.ChatHandler
	ExtauthService     extauth.Service
	ExtauthHandler     *extauth.Handler
	AutoreplyService   *autoreply.Service
	AutoreplyHandler   *autoreply.Handler
	AuthMiddleware     *auth.AuthMiddleware
	APIKeyHandler      *auth.APIKeyHandler
	UserHandler        *user.Handler
	// Additional handlers
	BackupHandler      *backup.Handler
	SecurityHandler    *security.Handler
	SandboxHandler     *sandbox.Handler
	CronHandler        *cron.Handler
	BrowserHandler     *browser.Handler
	WorkflowHandler    *workflow.Handler
	VoiceHandler       *voice.Handler
	VoiceWSHandler     *voice.WSHandler
	FormfillerHandler  *formfiller.Handler
	CompanionHandler   *companion.Handler
	CompanionWSHandler *companion.WebSocketHandler
	ProviderPool       *providerpool.Pool
	APIKeyService      *auth.APIKeyService
	SpeechHandler      *speech.Handler
	STTService         stt.Service
	NgrokTunnelMgr     *ngrok.SDKTunnelManager
	NgrokConfigStore   *ngrok.ConfigStore
	MemoryHandler      *server.MemoryHandler
	ChannelConfigStore *server.ChannelConfigStore
	ConfigKV           kvstore.Store       // shared kvstore for config persistence
	ConfigStore        *config.ConfigStore // kvstore-backed config persistence
	HotReloader        *config.HotReloader
	WorkspaceHandler   *workspace.Handler
	SSEBroker          *sse.Broker
	Gateway            *gateway.Gateway
	GatewayHandler     *gateway.Handler

	// IPC backends (optional, wired from main.go)
	BrowserIPC     sockipc.BrowserBackend
	UIReviewerIPC  sockipc.UIReviewBackend
	UIReviewerTool *tools.UIReviewerTool  // for VLM bridge wiring
	AnalyzeTool    *tools.AnalyzeTool     // for LLM bridge wiring
	MediaManager   *mediagen.Manager      // for native image tool wiring
	MediaStorage   *mediagen.MediaStorage // for ppt/image review wiring
	PushIPC        sockipc.PushBackend
	PushService    *push.Service // for skill/tool wiring
	CronIPC        sockipc.CronBackend
	// RegisterIPCExtensions allows cmd/blue to add main-process-only CLI IPC
	// handlers after the shared runtime IPC surface is initialized.
	RegisterIPCExtensions func(*sockipc.Server)

	// Consolidated init deps (previously only in cmd/blue/main.go)
	SkillEmbedFS              fs.FS            // embedded SKILL.md filesystem for ReleaseSkills
	SandboxManager            *sandbox.Manager // for sandbox skill wiring
	SystemPromptBuilder       *agentcore.SystemPromptBuilder
	LazyBrowserSvc            func() *browser.RodService // for UI reviewer lazy adapter
	AcquireBrowserSvc         func() (*browser.RodService, func(), error)
	AcquireFallbackBrowserSvc func() (*browser.RodService, func(), error)
	LightpandaShimSvc         *browser.LightpandaService
	BrowserBackend            tools.BrowserBackend // for browser tool + IPC

	// Closers collects io.Closers started during route registration.
	// The caller should close them on shutdown (e.g., via lifecycle hooks).
	Closers []interface{ Close() error }

	// ChannelTaskWatcher is populated by RegisterAllRoutes for main.go to wire the notifier.
	ChannelTaskWatcher *mediagen.ChannelTaskWatcher

	// OnEarlyReady is called after critical routes (health, system/mode, auth)
	// are registered but before heavy subsystem init. The caller can start the
	// HTTP listener here so health checks succeed while the rest initializes.
	OnEarlyReady func()
}

RoutesDeps holds all dependencies needed for route registration

type RuntimeDBMigrationResult

type RuntimeDBMigrationResult struct {
	TablesMoved []string
	RowsMoved   int
	Vacuumed    bool
}

RuntimeDBMigrationResult summarizes the one-time split from blue.db to runtime.db.

func PrepareRuntimeDatabase

func PrepareRuntimeDatabase(
	ctx context.Context,
	dataDir string,
	primaryConn *dbutil.SQLiteConn,
	runtimeConn *dbutil.SQLiteConn,
	logger *zap.Logger,
) (*RuntimeDBMigrationResult, error)

PrepareRuntimeDatabase ensures runtime.db has the required schemas and, on first run, moves harness/agent tables out of blue.db so future startup checks touch less data.

type ServerConfig

type ServerConfig struct {
	Port      int
	DataDir   string
	Version   string
	BuildTime string
	GitCommit string
	Mode      string // "standalone" or "embedded"
}

ServerConfig holds configuration for server initialization

func DefaultConfig

func DefaultConfig() *ServerConfig

DefaultConfig returns default server configuration

type Services

type Services struct {
	DB            *sql.DB
	DBConn        *database.SQLiteConn // Read-write separated connection
	RuntimeDBConn *database.SQLiteConn // Separate DB for harness/agent tables (reduces startup time)
	Config        *config.Config
	Logger        *zap.Logger
	UserService   *user.Service
	UserRepo      *user.SQLiteRepository
	JWTService    *auth.JWTService
	APIKeyService *auth.APIKeyService
	MemoryStore   *memory.Store
	A2UIManager   *a2ui.Manager
	OCRService    *ocrruntime.TesseractService
	PDFService    *pdfextract.Service
	LLMRegistry   *llm.ProviderRegistry
	ToolRegistry  *tools.Registry
	SkillRegistry *skill.Registry
	MgmtTool      *tools.MgmtTool
	WorkerPool    *worker.Pool
	DataDir       string
}

Services holds all initialized services

func InitServices

func InitServices(cfg *ServerConfig, appCfg *config.Config, logger *zap.Logger) (*Services, error)

InitServices initializes all core services

func (*Services) Close

func (s *Services) Close()

type StartupTrace

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

StartupTrace emits coarse startup timing marks when tracing is enabled via env.

func NewStartupTrace

func NewStartupTrace(component string, logger *zap.Logger) *StartupTrace

NewStartupTrace creates a new startup trace for a component.

func (*StartupTrace) Mark

func (t *StartupTrace) Mark(label string, fields ...zap.Field)

Mark records a startup milestone.

func (*StartupTrace) SetLogger

func (t *StartupTrace) SetLogger(logger *zap.Logger)

SetLogger attaches a logger for subsequent trace events.

Source Files

Jump to

Keyboard shortcuts

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