setup

package
v1.15.3 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package setup wires every workflow subpkg together. Server code instantiates one Manager via New and calls Start to boot the engine, router, and all registered workflows.

Index

Constants

View Source
const (
	DefaultRunKeepMax       = 50
	DefaultRunRetentionDays = 7
	// RunCleanupInterval is how often the background pass sweeps every
	// workflow, on top of the per-workflow pass after each finished run.
	RunCleanupInterval = 6 * time.Hour
)

Run-retention defaults. A run's state.json can carry megabytes of node output, so history is capped both by count and by age.

Variables

This section is empty.

Functions

func AttachSlackWorkflowSink added in v1.2.9

func AttachSlackWorkflowSink(ch *agentslack.Channel, router *trigger.Router)

AttachSlackWorkflowSink points one Slack instance's inbound event sink at the workflow router. Exported so the hot-reload path in tools/agents can wire an instance created after boot — without it a bot added from the dashboard receives Slack events but fires no workflow trigger until the next restart.

bot_user_id / bot_name ride along in the payload so a workflow can tell WHICH bot saw the event when several are connected to the same workspace.

func AttachSlackWorkflowSinkKeyed added in v1.2.9

func AttachSlackWorkflowSinkKeyed(ch *agentslack.Channel, router *trigger.Router, instanceKey string)

AttachSlackWorkflowSinkKeyed is AttachSlackWorkflowSink plus the registry instance key of this bot, stamped into every event as channel_instance. A trigger pinned to one instance compares against it, so two bots in the same workspace no longer both fire a workflow that was wired to one of them.

func Bootstrap

func Bootstrap(ctx context.Context, svc service.Service, router *trigger.Router, cron *trigger.CronScheduler, schedAt *trigger.ScheduleAtScheduler) error

Bootstrap wires every workflow folder found at startup into the router + cron scheduler. Called once from server startup after Service + Router are constructed.

func CleanupRuns

func CleanupRuns(layout config.Layout, opts CleanupOptions) (removed int, err error)

CleanupRuns applies the retention policy to every workflow's runs/. Best-effort per workflow: one unreadable folder doesn't stop the rest.

func CleanupWorkflowRuns added in v1.2.9

func CleanupWorkflowRuns(layout config.Layout, id string, opts CleanupOptions) (int, error)

CleanupWorkflowRuns applies the retention policy to one workflow.

func ConnectorsCredsAdapter

func ConnectorsCredsAdapter(svc *connectorsvc.Service) func(module, row, accountID string) (map[string]string, error)

ConnectorsCredsAdapter wraps the connectors service to expose a connector.RowCredsFn for the workflow registry. Lookup is by (module key, row label) — first matching label wins; empty row falls back to the first instance for that Key.

When accountID is set, the selected instance's connected SSO account token is injected as `user_token`, overriding the row's config — the same override the MCP tools/call path applies. Access is enforced at the instance (tag) level by the palette; here we only assert the account actually belongs to the resolved row (data integrity), not who may use it.

func HotReload

func HotReload(ctx context.Context, svc service.Service, router *trigger.Router, cron *trigger.CronScheduler, schedAt *trigger.ScheduleAtScheduler, id string) error

HotReload reloads + re-registers (or unregisters) one id. Used by fsnotify watcher in production.

func NewCLIProviders

func NewCLIProviders() ([]provider.Provider, error)

NewCLIProviders returns one workflow.Provider per healthy CLI runtime declared by the agent provider package. Caller registers each into the workflow Manager.

func PublishAndReload added in v0.15.1

func PublishAndReload(ctx context.Context, svc service.Service, router *trigger.Router, cron *trigger.CronScheduler, schedAt *trigger.ScheduleAtScheduler, id, actorID string) (workflow.Workflow, error)

func RegisterLiveChannels

func RegisterLiveChannels(wfReg *channel.Registry, base *agentchannels.Registry)

RegisterLiveChannels rewires the workflow channel registry to use the live agentchannels.Registry as its backing source. Channels become workflow-visible automatically once they implement agentchannels.WorkflowTriggerProvider or WorkflowActionProvider — channels without either (UI, API, REST one-shot) stay invisible to the workflow editor.

Call after the base channel registry has its channels added (after channels/setup constructs them in server.go) and before wfMgr.Start(ctx).

func RegisterLiveConnectors

func RegisterLiveConnectors(reg *connector.Registry)

RegisterLiveConnectors keeps the workflow connector registry in sync with the global connector registry — every module already registered is copied immediately, and every future connectors.Register call also flows through. The previous one-shot snapshot variant depended on boot ordering: any connector registered after this call (wfconn, wickmanager, notifications — all late-bound because they need runtime Deps) silently went missing from /api/workflows/palette and /workflows/api/registry. The observer hook removes that footgun.

Safe to call once per workflow registry instance; subscriptions are not removable, so calling twice for the same registry would double- fire on future Register events. Today the call sites in api/server.go (HTTP) and api/server_mcp.go (stdio) each touch their own registry.

func RegisterSlackIntegration

func RegisterSlackIntegration(intReg *integration.Registry, base *agentchannels.Registry, router *trigger.Router, pickers *wfmcp.PickerRegistry)

RegisterSlackIntegration wires the Slack channel into the workflow integration surface. Two pieces, both required for end-to-end:

  1. ActionDescriptor / EventDescriptor registration — slackwf.RegisterAll pushes every per-event + per-action descriptor (send_message, open_modal, on_message, on_block_action, …) into intReg so the palette + the engine see them.

  2. Inbound event sink — wires slack.Channel.SetWorkflowEventSink so every Slack callback (message, block_action, view_submission, slash command, …) fires router.Dispatch with a normalised workflow.Event.

No-op if Slack isn't registered or the channel isn't the expected type — callers can call this unconditionally regardless of which channels are configured.

func SlackInstancePicker added in v1.2.9

func SlackInstancePicker(base *agentchannels.Registry, fallback *agentslack.Channel) slackwf.ChannelPicker

SlackInstancePicker resolves which Slack bot an action node runs as.

The run's trigger payload carries bot_user_id — the bot that received the event that started this run (see AttachSlackWorkflowSink). Sending as a different bot is not a cosmetic difference: it posts under an identity the user never talked to, and in a private channel the other bot isn't in it fails outright with not_in_channel.

A node that PINNED an instance (channel_instance) wins over the payload: the editor showed exactly which bot the row was, so the run must use it — and a cron or manual run carries no bot at all.

Falls back to `fallback` when the run has no Slack trigger (manual, cron, webhook) or when the recorded bot is no longer registered — an action that used to work must not start erroring because the payload lacks a key.

func ToggleAndReload added in v0.15.1

func ToggleAndReload(ctx context.Context, svc service.Service, router *trigger.Router, cron *trigger.CronScheduler, schedAt *trigger.ScheduleAtScheduler, id string, enabled bool) error

func UserResolverAdapter added in v0.18.3

func UserResolverAdapter(svc userLookup) connector.UserResolverFn

UserResolverAdapter wraps the login service into a connector.UserResolverFn so the workflow connector executor can run identity-gated ops as the workflow owner (Workflow.CreatedBy). Unknown ids resolve to a nil user (no error) so the run proceeds unauthenticated and the op's own gate decides whether to reject.

func WatchWorkflows

func WatchWorkflows(ctx context.Context, workflowsDir string, svc service.Service, router *trigger.Router, cron *trigger.CronScheduler, schedAt *trigger.ScheduleAtScheduler)

WatchWorkflows polls workflow files under workflowsDir every 3 seconds and calls HotReload on any id whose mtime changed since the last poll. New files trigger a load; removed files trigger an unregister. Blocks until ctx is cancelled — run in a goroutine. Used by the file-based (non-DB) mode.

Types

type CleanupOptions

type CleanupOptions struct {
	// KeepMax is the hard cap of finished runs kept per workflow; the
	// newest KeepMax survive (unless older than TTL), the rest go.
	// <= 0 = DefaultRunKeepMax.
	KeepMax int
	// TTL removes a finished run whose EndedAt is older than this, even
	// inside KeepMax. <= 0 = DefaultRunRetentionDays.
	TTL time.Duration
	Now func() time.Time
}

CleanupOptions tunes the run-retention pass.

type Manager

type Manager struct {
	Layout  config.Layout
	Service service.Service
	// Repo is the DB-backed workflow repository. Nil when no DB is
	// wired (test paths) — every consumer that touches it must
	// nil-check first. Populated by WithDB.
	Repo       *repository.Repo
	StateStore *state.FileStore
	Engine     *engine.Engine
	Router     *trigger.Router
	Cron       *trigger.CronScheduler
	// DeferCron holds cron trigger firing back at Start, leaving it to an
	// explicit StartCron. The daemon sets it so cron only begins once this
	// process owns intake (see internal/pkg/upgrade.IntakeBaton).
	DeferCron   bool
	ScheduleAt  *trigger.ScheduleAtScheduler
	Canvas      *canvas.Canvas
	Channels    *channel.Registry
	Integration *integration.Registry
	Connectors  *connector.Registry
	Providers   *provider.Registry
	DataTables  datatable.Service
	Guard       *guard.Guard
	Cost        *cost.Tracker
	MCP         *mcp.Ops

	// AgentPool + AgentSubscribe route the `agent` + `session_init`
	// node types through the shared agent pool. Nil = engine still
	// runs (codex/gemini via cliProvider), but claude path skips the
	// queue/sidebar/session-reuse benefits. See workflow/pool.md.
	AgentPool      *pool.Pool
	AgentSubscribe nodes.AgentSubscribeFn
	// contains filtered or unexported fields
}

Manager bundles every wired piece so server.go can hand one struct to consumers (UI handlers, MCP transport, jobs).

func New

func New(layout config.Layout) *Manager

New constructs every dependency wired to a single Layout. Channels, connectors, providers, and guard start empty — caller plugs them in via With* before Start.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start ensures layout, bootstraps router with current workflows, and kicks off the cron scheduler. Idempotent — safe to call from main.go on every boot.

func (*Manager) StartCron added in v1.2.9

func (m *Manager) StartCron(ctx context.Context)

StartCron starts the cron trigger scheduler on its own. Paired with DeferCron so the daemon can bootstrap the workflow subsystem at boot but hold cron firing until this process actually owns intake — during a graceful upgrade the predecessor keeps firing until it has drained, and two schedulers would run every cron workflow twice.

func (*Manager) StartRunRetention added in v1.2.9

func (m *Manager) StartRunRetention(opts func() CleanupOptions)

StartRunRetention wires the per-workflow pass that prunes a workflow right after one of its runs finishes, and remembers opts for the background sweep. It does NOT sweep: during a graceful upgrade the predecessor still owns intake and is still finishing runs, so the all-workflow pass waits for StartRunSweep, called once this process holds the intake baton. opts is re-read on every pass so a config change lands without a restart.

func (*Manager) StartRunSweep added in v1.2.9

func (m *Manager) StartRunSweep(ctx context.Context)

StartRunSweep runs one all-workflow sweep now, then every RunCleanupInterval, until ctx is done. Call it only after this process has taken over intake (next to StartCron).

func (*Manager) Stop

func (m *Manager) Stop()

Stop drains the router workers cleanly.

func (*Manager) WithAgentRuntime

func (m *Manager) WithAgentRuntime(p *pool.Pool, sub nodes.AgentSubscribeFn) *Manager

WithAgentRuntime wires the shared agent pool + a subscribe adapter into the workflow engine so `agent` and `session_init` nodes route through the queue/session machinery. The subscribe function is the thin adapter around tools/agents.Broadcaster (kept out of this package to avoid an import cycle).

Calling re-registers the agent + session_init executors so the dependency takes effect immediately. Idempotent; nil arguments disable the pool path (engine reverts to the cliProvider one-shot).

func (*Manager) WithChannels

func (m *Manager) WithChannels(chs ...channel.Channel) *Manager

WithChannels registers one or more channels.

func (*Manager) WithDB added in v0.14.20

func (m *Manager) WithDB(db *gorm.DB) *Manager

WithDB switches the workflow Service from the file-based store to the DB-primary one. Workflow body + draft + version history + test cases now live in SQL; runtime concerns (state.json, env.json, runs/) keep their on-disk paths via the embedded FileService.

Idempotent — call once at boot with the shared *gorm.DB. Passing nil leaves the file-based Service in place (test path).

func (*Manager) WithDataTablesDB added in v0.13.1

func (m *Manager) WithDataTablesDB(db *gorm.DB) *Manager

WithDataTablesDB swaps the in-memory data table store for the Postgres-backed PgService. Re-registers the datatable_* executors so downstream Engine.Run calls hit the new backend. Idempotent; pass nil to revert to the in-memory store (test path).

func (*Manager) WithGuardConfig

func (m *Manager) WithGuardConfig(cfg guard.Config) *Manager

WithGuardConfig replaces the guard configuration.

func (*Manager) WithProvider

func (m *Manager) WithProvider(p provider.Provider) *Manager

WithProvider registers a provider.

Jump to

Keyboard shortcuts

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