connectors

package
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package connectors is the central registry for every connector definition wick will expose via MCP. Downstream apps append to it via app.RegisterConnector; the MCP and admin-UI layers walk All() at boot to validate definitions and seed default instances.

Shape of a connector module (see internal/planning/archive/connectors-design.md for the full design):

  1. Package under internal/connectors/<name>/ exposing a Meta builder, a typed Creds struct (`wick:"..."` tags), a typed Input struct, and an `Execute(c *connector.Ctx) (any, error)` function.
  2. Register here inside RegisterBuiltins() (default-on for every wick app — httprest, slack) or RegisterLabSamples() (cmd/lab only — crudcrud), or in the downstream project's main.go via app.RegisterConnector. (Connectors shipped as external plugins — github, bitbucket, google_workspace — live under plugins/connector/ and are NOT registered here.)

Connector definitions live in code; per-instance rows (credentials, labels, tags) live in the connector_instances table — populated by the admin UI in a later phase.

Index

Constants

View Source
const (
	ProfileFull  = "full"
	ProfileAgent = "agent"
	ProfileLite  = "lite"
)

Build profiles select which builtin connectors a binary registers. The active profile is read at boot from the configs DB row (configs.KeyProfile) via configsSvc.Profile(). "full" (default and any unknown value) preserves the historical all-connectors behaviour.

View Source
const (
	// AccountOpInherit drops the override so the account follows the instance.
	AccountOpInherit = "inherit"
	// AccountOpOn forces the operation on for this account even when the
	// instance has it off.
	AccountOpOn = "on"
	// AccountOpOff forces it off even when the instance has it on.
	AccountOpOff = "off"
)

AccountOpState values accepted by SetAccountOpOverride.

View Source
const RunFilterAccountDefault = "default"

RunFilterAccountDefault is the AccountID sentinel for "the row's own configured credentials, no connected account". It is not an account id and cannot collide with one.

Variables

View Source
var ErrAccountMismatch = errors.New("connector account does not belong to this user")

ErrAccountMismatch is returned when an account does not belong to the connector, or to the wick user it is asked for.

View Source
var ErrFixedInstanceViolation = errors.New("connector is fixed: only one instance allowed")

ErrFixedInstanceViolation is returned by Service.Create / Duplicate when trying to add a second instance for a connector whose Meta.Fixed is true. Wick auto-seeds exactly one row for a Fixed connector at Bootstrap; admins cannot add or duplicate beyond that.

View Source
var ErrNoHealthCheck = errors.New("connector does not implement HealthCheck")

ErrNoHealthCheck is returned by RunHealthCheck when the target connector's module did not register a HealthCheck hook. The manager handler treats this as a 404-ish — admins should not see the button on that connector at all.

Functions

func AccountOpEnabled added in v1.2.9

func AccountOpEnabled(acc *entity.ConnectorAccount, opKey string, st OpState) bool

AccountOpEnabled answers the single question Execute needs: may this account run this operation? Same precedence as ResolveAccountOps.

func AccountOpOverrides added in v1.2.9

func AccountOpOverrides(acc *entity.ConnectorAccount) map[string]bool

AccountOpOverrides parses an account's per-operation overrides into opKey → forced state. A present key means this account overrides the instance; an absent key means it inherits. nil is a perfectly good "inherits everything".

Falls back to the legacy DisabledOps array when OpOverrides is empty, so accounts configured before the three-state model keep the behaviour they were given — every key in that array reads as a forced OFF.

func AccountTagPath added in v1.2.9

func AccountTagPath(accountID string) string

AccountTagPath is the tool_tags path an account's access tags live on — the account-level sibling of "/connectors/{id}". Admin tags an account here to share it with a team without opening the whole pool.

func AccountVisibleTo added in v1.2.9

func AccountVisibleTo(row entity.Connector, acc entity.ConnectorAccount, accountTagIDs []string, caller AccountAccess) bool

AccountVisibleTo reports whether a connected account may be seen — and run as — by the caller. accountTagIDs are the account's own filter tags (see AccountTagPath); pass nil when it has none.

Visible when ANY of these holds:

  • the caller administers the instance (admin or owner);
  • the row opted into AllowOthersSeeAccounts (the shared pool);
  • the caller connected the account themselves;
  • the account carries a filter tag the caller also carries — the per-account share, for handing one account to a team without opening every other account on the row;
  • the account has no owner recorded (legacy/system connect), so an existing install does not lose the account it has been running on.

func AccountsVisibleTo added in v1.2.9

func AccountsVisibleTo(row entity.Connector, accs []entity.ConnectorAccount, accountTagIDs map[string][]string, caller AccountAccess) []entity.ConnectorAccount

AccountsVisibleTo filters a row's connected accounts down to the ones the caller may see. accountTagIDs maps account id → its filter tags. See AccountVisibleTo for the rule.

func All

func All() []connector.Module

All returns every registered connector definition in registration order.

func KeyAllowed added in v1.2.9

func KeyAllowed(ctx context.Context, key string) bool

KeyAllowed reports whether the agent scope on ctx, if any, leaves the connector type key switched on.

func OnRegister added in v0.15.0

func OnRegister(fn func(connector.Module))

OnRegister installs a listener that fires for every connector module in the registry — once per module already present at the time of the call (catch-up), then once per future Register call (catch future). The catch-up loop matters: workflow setup runs after some builtins have already been registered, and a future-only subscription would silently drop them.

Listeners are not removable. The registry lives for the lifetime of the process; subscriptions are intended for setup-time wiring, not dynamic plug-in/plug-out.

func OnUnregister added in v1.2.0

func OnUnregister(fn func(key string))

OnUnregister installs a listener fired for every Unregister call. There is no catch-up pass — a module that is already gone has nothing to replay. Not removable, same as OnRegister.

func OwnsConnector added in v1.2.9

func OwnsConnector(row entity.Connector, userID string) bool

OwnsConnector reports whether the user created the instance. The owner is the non-admin counterpart of admin for instance-level decisions (managing the access policy, seeing every connected account).

func Register

func Register(m connector.Module)

Register appends a fully-resolved Module record to the registry. Called from app.RegisterConnector; do not call directly from app code.

Idempotent on Meta.Key: re-registering the same key REPLACES the existing entry. This keeps server stop→start safe — wickmanager is registered mid-boot with runtime Deps (configsSvc, jobsSvc, ...) that are rebuilt on each boot. A plain append would trip Bootstrap's duplicate-key check; a skip would leave handlers wired to stale services from the previous boot.

After the (append|replace), every listener registered via OnRegister is notified with the resolved module. Listeners run synchronously on the calling goroutine — keep them cheap. Registrations all happen on the main boot goroutine today; revisit if that ever changes.

func RegisterBuiltins

func RegisterBuiltins()

RegisterBuiltins seeds in-house connectors every downstream wick app gets by default. Idempotent on Meta.Key via registerOnce.

func RegisterLabSamples added in v0.9.0

func RegisterLabSamples()

RegisterLabSamples seeds the demo-only connectors shipped with the cmd/lab binary — currently the crudcrud sample. Downstream wick apps do not call this; they register their own connectors via main.go.

func RegisterProfile added in v0.22.0

func RegisterProfile(profile string)

RegisterProfile seeds the builtin connectors permitted by the named profile. Idempotent on Meta.Key via registerOnce.

func ToolAllowed added in v1.2.9

func ToolAllowed(ctx context.Context, name string) bool

ToolAllowed reports whether the agent scope on ctx, if any, leaves the MCP tool name switched on.

func Unregister added in v1.2.0

func Unregister(key string)

Unregister removes the module registered under key and notifies the unregister listeners. No-op when the key was never registered.

This exists because a CUSTOM connector's definition can be deleted at runtime. Register is the only way in, so without a way out the module stayed in `extra` for the life of the process: the connector's detail page kept rendering (name, description, operation count) from the registry while its rows were already gone, and — because the UI asks custom.Service.DefIDForKey whether a key is custom, and that map entry HAD been dropped — the leftover card presented itself as a BUILT-IN. A built-in has no Delete action, so the ghost could not be removed from the UI at all. Only a restart cleared it, since boot rebuilds the registry from the definitions still in the database.

Callers must hold no registry lock; like Register, this runs on the caller's goroutine and notifies synchronously.

func WithAgentScope added in v1.2.9

func WithAgentScope(ctx context.Context, scope AgentScope) context.Context

WithAgentScope attaches scope to ctx. A nil scope leaves ctx unchanged.

func WithoutAgentScope added in v1.2.9

func WithoutAgentScope(ctx context.Context) context.Context

WithoutAgentScope returns ctx with any agent scope removed, for the surfaces that must see a person's own reach even when called from inside an agent session (the checklist an agent is narrowed FROM).

Types

type AccessPolicy added in v1.2.9

type AccessPolicy struct {
	// AllowOthersConfigure: non-admin users with tag access may edit credentials.
	AllowOthersConfigure bool
	// AllowOthersConnectSSO: non-admin users may connect their OAuth account.
	AllowOthersConnectSSO bool
	// EnableSSO: the OAuth flow is active on this instance.
	EnableSSO bool
	// MultiAccount: each OAuth connect adds an account (true) or replaces the
	// existing one (false).
	MultiAccount bool
	// AllowOthersSeeAccounts: connected accounts are a shared pool visible to
	// every user with tag access (true), or private to whoever connected them
	// (false, the default).
	AllowOthersSeeAccounts bool
}

AccessPolicy is the per-instance access policy, written as one unit by the Access policy form (SPA POST or the legacy form-post). Grouped into a struct rather than positional bools so adding a flag does not silently re-order every call site.

type AccountAccess added in v1.2.9

type AccountAccess struct {
	UserID     string
	TagIDs     []string
	Privileged bool
}

AccountAccess is who is asking, for account-visibility decisions.

Privileged means "administers this instance" — an admin or the instance owner. TagIDs are the caller's filter tags, matched against the tags an admin put on the account itself.

type AccountOpState added in v1.2.9

type AccountOpState struct {
	Key string
	// Enabled is what applies to this account right now.
	Enabled bool
	// Overridden is true when this account states its own answer; false
	// means it follows the instance.
	Overridden bool
	// Inherited is what the instance says, shown as the value the account
	// would fall back to when the override is cleared.
	Inherited bool
	// SystemDisabled is the health-check lock on the instance. It is a
	// ceiling, not a default: an override cannot switch an operation back
	// on when the credential genuinely lacks the upstream permission, so
	// forcing it would only buy an error from the provider.
	SystemDisabled bool
	Reason         string
}

AccountOpState is one operation's state for one account, resolved: what actually applies, whether that came from an override or from the instance, and what the instance says — so the UI can show "inherited (off)" and "overridden on" as different things rather than one checkbox.

func ResolveAccountOps added in v1.2.9

func ResolveAccountOps(acc *entity.ConnectorAccount, instance map[string]OpState, opKeys []string) []AccountOpState

ResolveAccountOps resolves every operation in opKeys for one account against the instance's own operation state.

Precedence, tightest first: SystemDisabled wins over everything, then the account's own override, then the instance's Enabled flag.

type AgentFeatureScope added in v1.2.9

type AgentFeatureScope interface {
	// AllowKey reports whether connectors of this type are on at all.
	AllowKey(connectorKey string) bool
	// AllowTool reports whether a top-level MCP tool may be listed and
	// called.
	AllowTool(name string) bool
}

AgentFeatureScope is the optional half of an AgentScope that switches whole features off for an agent: every instance of a connector type, and wick's own MCP tools by name. An AgentScope without it gates nothing by feature.

type AgentScope added in v1.2.9

type AgentScope interface {
	// AllowConnector reports whether the connector instance is on the
	// agent's checklist at all.
	AllowConnector(connectorID string) bool
	// AllowAccount reports whether the agent may run the connector as the
	// given connected account. accountID "" is the instance's own
	// identity (the bot), which the checklist treats as one more account.
	AllowAccount(connectorID, accountID string) bool
	// AllowOp reports whether one operation is permitted. destructive is
	// the op's own declaration, used by the "read only" level.
	AllowOp(connectorID, opKey string, destructive bool) bool
}

AgentScope narrows what an agent (Agents app) may reach on top of its owner's own visibility. It can only take away: every check here runs AFTER the tag/ownership/admin rules have already decided the owner may see the row, so a scope can never grant a connector the owner lacks.

The scope rides on the request context. The MCP layer attaches it when the calling session belongs to an agent (see mcp.SetAgentScopeResolver); every other caller has no scope and behaves exactly as before.

func AgentScopeFrom added in v1.2.9

func AgentScopeFrom(ctx context.Context) AgentScope

AgentScopeFrom returns the scope on ctx, or nil when the caller is not an agent.

type AuditFilter added in v0.9.0

type AuditFilter struct {
	ConnectorID  string
	OperationKey string
	Source       string
	Status       string
	UserID       string
	From         *time.Time // inclusive lower bound on StartedAt
	To           *time.Time // inclusive upper bound on StartedAt
}

AuditFilter narrows cross-connector audit queries. All fields are optional — omit to get all runs across every connector instance.

type CatalogEntry added in v1.2.9

type CatalogEntry struct {
	Row    entity.Connector
	Module connector.Module
	Status string
	// Accounts are the connected accounts the caller may see and run as.
	// Always empty for a module without OAuth.
	Accounts []entity.ConnectorAccount
	// Ops are the enabled ops, in declaration order. Never empty: a row
	// with no enabled op is not in the catalog at all.
	Ops []CatalogOp
}

CatalogEntry is one connector instance as wick_list shows it to a caller.

type CatalogOp added in v1.2.9

type CatalogOp struct {
	Key         string
	Name        string
	Destructive bool
}

CatalogOp is one op of a catalog entry that is live for the caller.

type ExecuteParams

type ExecuteParams struct {
	ConnectorID  string
	OperationKey string
	Input        map[string]string
	// RawInput is the caller's arguments with original JSON types preserved
	// (bool, number, string, …), keyed identically to Input. Optional — only
	// the MCP tools/call path sets it. It is forwarded to the connector via
	// Ctx.SetRawInput so MCP-proxy connectors can relay a scalar in its
	// original type instead of the stringified Input form. nil elsewhere.
	RawInput  map[string]any
	Source    entity.ConnectorRunSource
	UserID    string
	IPAddress string
	UserAgent string
	// SessionID is the agent session this call was made within, when the
	// caller supplied it (MCP tools/call session_id). Empty on panel-test
	// and retry. Forwarded to the connector Ctx so identity-aware ops (e.g.
	// the Slack footer) can resolve the session-owning bot.
	SessionID string
	// IsAdmin indicates whether the caller holds admin role. When false,
	// operations marked AdminOnly in the connector_operations table are
	// blocked before execution starts.
	IsAdmin bool
	// TagIDs are the caller's filter tags. Used to honour per-account share
	// tags when the call names an AccountID — an account shared with a tag
	// the caller carries is theirs to run as.
	TagIDs []string
	// ParentRunID is set when this call replays an earlier run.
	// Intended for use with Source == ConnectorRunSourceRetry.
	ParentRunID *string
	// Progress, when non-nil, receives incremental progress events the
	// connector emits via Ctx.ReportProgress. The MCP SSE handler wires
	// a reporter that frames each event as a notifications/progress
	// JSON-RPC message; the JSON transport leaves this nil so events
	// are dropped harmlessly.
	Progress connector.ProgressReporter
	// AccountID, when non-empty, selects a specific ConnectorAccount
	// whose access token overrides the row's user_token config. Used by
	// the test panel when multiple accounts are connected to one instance.
	AccountID string
	// SessionInstance, when non-nil, runs against a session-workspace
	// instance instead of a DB connector row: there is no row to load,
	// so the base module is cloned and the instance's own Config map is
	// used verbatim. ConnectorID is the synthetic "sw_<uuid>" id (used
	// for run logging + rate limiting only). Per-row checks (op enable/
	// disable rows, admin-only flags, OAuth accounts) are skipped — a
	// session instance has none of that backing state.
	SessionInstance *SessionInstanceTarget
}

ExecuteParams bundles the ambient context for one execution. Keeping it as a struct keeps the call site readable when more fields are added (e.g. retry parent, MCP session id).

type ExecuteResult

type ExecuteResult struct {
	RunID        string
	Status       entity.ConnectorRunStatus
	ResponseJSON string
	ErrorMessage string
	LatencyMs    int
}

ExecuteResult carries the outcome of one Execute call. Returned alongside an error so the caller (panel-test or MCP) can render the run details even when the operation itself failed.

type HealthCheckResult added in v0.10.0

type HealthCheckResult struct {
	Ops          []connector.OpHealth
	NewlyLocked  []string // ops that became system-disabled this run
	NewlyCleared []string // ops whose system-disabled flag was cleared this run
}

HealthCheckResult bundles the outcome of a health-check run for one connector row. Per-op transitions describe what changed in the DB so the UI can surface a useful summary toast ("3 ops disabled, 1 cleared").

type OpState added in v0.10.0

type OpState struct {
	Enabled              bool
	SystemDisabled       bool
	SystemDisabledReason string
	AdminOnly            bool
	// ConfigOnly mirrors connector.Operation.ConfigOnly (a module-level flag,
	// not a per-row DB toggle): the op backs a config-form widget and must be
	// hidden from the MCP catalog. OperationStates collapses it into false;
	// Execute (which reads this full state) leaves Enabled intact so /test can
	// still run it.
	ConfigOnly bool
}

OpState bundles the effective state of one operation on one connector row: the admin-controlled Enabled flag, the health-check-controlled SystemDisabled flag, and the reason surfaced alongside the lock when SystemDisabled is true. Effective availability is `Enabled AND NOT SystemDisabled`. AdminOnly restricts the operation to admin MCP callers and is toggled separately by admins.

type Repo

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

Repo wraps the gorm handle and exposes the connector-specific CRUD surface used by the admin UI, the MCP dispatch layer, and the run-history retention job.

All queries scope on context, so cancellation from the HTTP handler (or the cron worker) propagates cleanly into the DB driver.

func NewRepo

func NewRepo(db *gorm.DB) *Repo

NewRepo wires a Repo around an existing gorm handle.

func (*Repo) AccountFilterTagIDs added in v1.2.9

func (r *Repo) AccountFilterTagIDs(ctx context.Context, accountIDs []string) (map[string][]string, error)

AccountFilterTagIDs returns the FILTER tag ids attached to each of the given connected accounts, keyed by account id. Accounts are tagged through the same tool_tags table every other taggable thing uses, on the path AccountTagPath(accountID) — so the admin tag picker, the tag-filter rules and the audit story are the ones wick already has.

Only is_filter tags are returned: a non-filter tag is a label, not a grant.

func (*Repo) ClearSystemDisabled added in v0.10.0

func (r *Repo) ClearSystemDisabled(ctx context.Context, connectorID, opKey string) error

ClearSystemDisabled removes the health-check lock from an operation (e.g. after a successful re-check). Leaves Enabled untouched, so an op that was manually disabled stays disabled; one the system locked will become available for manual toggling again.

func (*Repo) CountByKey

func (r *Repo) CountByKey(ctx context.Context, key string) (int64, error)

CountByKey returns how many Connector rows exist for a code key. Used by Bootstrap to decide whether to auto-create the initial row.

func (*Repo) CountRunsAudit added in v0.9.0

func (r *Repo) CountRunsAudit(ctx context.Context, f AuditFilter) (int64, error)

CountRunsAudit returns the total matching the same filter as ListRunsAudit. Used to drive pagination.

func (*Repo) CountRunsFiltered

func (r *Repo) CountRunsFiltered(ctx context.Context, connectorID string, f RunFilter) (int64, error)

CountRunsFiltered returns the total row count matching the same filter as ListRunsFiltered. Used to drive pagination controls.

func (*Repo) Create

func (r *Repo) Create(ctx context.Context, c *entity.Connector) error

Create inserts a new Connector row. The BeforeCreate hook on the entity stamps an ID if the caller left it empty.

func (*Repo) CreateRun

func (r *Repo) CreateRun(ctx context.Context, run *entity.ConnectorRun) error

CreateRun inserts a row at the start of an execution. Status should be ConnectorRunStatusRunning; FinishRun finalizes it.

func (*Repo) Delete

func (r *Repo) Delete(ctx context.Context, id string) error

Delete hard-deletes a connector row plus its operation toggles and connected accounts. Run history is intentionally preserved.

func (*Repo) DeleteAccount added in v0.16.0

func (r *Repo) DeleteAccount(ctx context.Context, accountID string) error

DeleteAccount removes one connected account by ID.

func (*Repo) FinishRun

func (r *Repo) FinishRun(ctx context.Context, runID string, status entity.ConnectorRunStatus, response, errMsg string, latencyMs, httpStatus int) error

FinishRun stamps terminal status, the response body, error message, and the timing/HTTP-status metrics. EndedAt is set to now.

func (*Repo) Get

func (r *Repo) Get(ctx context.Context, id string) (*entity.Connector, error)

Get loads a Connector by ID. Returns gorm.ErrRecordNotFound when no row matches.

func (*Repo) GetAccountByID added in v0.16.0

func (r *Repo) GetAccountByID(ctx context.Context, accountID string) (*entity.ConnectorAccount, error)

GetAccountByID returns one ConnectorAccount or gorm.ErrRecordNotFound.

func (*Repo) GetRun

func (r *Repo) GetRun(ctx context.Context, runID string) (*entity.ConnectorRun, error)

GetRun loads a single run, used by the retry handler to replay the stored RequestJSON against the current Connector.Configs.

func (*Repo) IsAccessibleForManager

func (r *Repo) IsAccessibleForManager(ctx context.Context, connectorID string, userTagIDs []string) (bool, error)

IsAccessibleForManager mirrors IsAccessibleTo but ignores the disabled flag. Used by manager handlers so admins who disabled a row can still open its detail page to re-enable.

func (*Repo) IsAccessibleTo

func (r *Repo) IsAccessibleTo(ctx context.Context, connectorID string, userTagIDs []string) (bool, error)

IsAccessibleTo reports whether a single connector row is visible to the caller using the same rule as ListAccessibleTo. Used by tools/call to re-check authorization before dispatch (the tools/list snapshot the client cached may be stale).

func (*Repo) IsOperationAdminOnly added in v0.9.0

func (r *Repo) IsOperationAdminOnly(ctx context.Context, connectorID, opKey string) (bool, error)

IsOperationAdminOnly returns true when the stored row has AdminOnly=true. Returns false (not restricted) when no row exists yet.

func (*Repo) List

func (r *Repo) List(ctx context.Context) ([]entity.Connector, error)

List returns every Connector row, newest first. Admin view.

func (*Repo) ListAccessibleForManager

func (r *Repo) ListAccessibleForManager(ctx context.Context, userTagIDs []string) ([]entity.Connector, error)

ListAccessibleForManager mirrors ListAccessibleTo but does NOT strip disabled rows. The admin manager surface must be able to enumerate disabled rows so they can be re-enabled. Tag-filter logic is unchanged.

func (*Repo) ListAccessibleTo

func (r *Repo) ListAccessibleTo(ctx context.Context, userTagIDs []string) ([]entity.Connector, error)

ListAccessibleTo returns the not-disabled Connector rows the caller is allowed to see, mirroring the Tools tag-filter rule:

  • row with no filter-type tags → visible to everyone
  • row with ≥1 filter-type tag → visible only when userTagIDs intersects the row's filter-tags

Tag association reuses the `tool_tags` table with `tool_path = '/connectors/{id}'` (see entity.Connector godoc).

Pass an empty userTagIDs for users that carry no filter tags — they still see fully untagged rows. Admin callers should bypass this and use List instead.

func (*Repo) ListAccounts added in v0.16.0

func (r *Repo) ListAccounts(ctx context.Context, connectorID string) ([]entity.ConnectorAccount, error)

ListAccounts returns all connected accounts for a connector instance.

func (*Repo) ListAccountsFor added in v1.2.9

func (r *Repo) ListAccountsFor(ctx context.Context, connectorIDs []string) (map[string][]entity.ConnectorAccount, error)

ListAccountsFor returns the connected accounts of MANY instances in one query, keyed by connector id. The admin connectors page lists every instance on the install, and asking per row was one round trip each — 46 rows on a database 30ms away is over a second spent on a listing.

func (*Repo) ListByKey

func (r *Repo) ListByKey(ctx context.Context, key string) ([]entity.Connector, error)

ListByKey returns every Connector that instantiates the given code definition (e.g. all "loki" rows).

func (*Repo) ListOperations

func (r *Repo) ListOperations(ctx context.Context, connectorID string) ([]entity.ConnectorOperation, error)

ListOperations returns the toggle rows for a connector. Missing rows mean "use the per-op default" (Destructive=false → on, Destructive=true → off); callers fold the defaults in themselves.

func (*Repo) ListOperationsFor added in v1.2.9

func (r *Repo) ListOperationsFor(ctx context.Context, connectorIDs []string) (map[string][]entity.ConnectorOperation, error)

ListOperationsFor is ListOperations for MANY connectors in one query, keyed by connector id. The agent catalog reads every instance the caller reaches, and one round trip per row made it seconds on a remote database.

func (*Repo) ListOwnedBy added in v1.2.9

func (r *Repo) ListOwnedBy(ctx context.Context, userID string) ([]entity.Connector, error)

ListOwnedBy returns every Connector the given user created, newest first. Ownership is independent of tags, so the manager listing can union these in and a creator never loses sight of their own instance.

func (*Repo) ListRunsAudit added in v0.9.0

func (r *Repo) ListRunsAudit(ctx context.Context, f AuditFilter, limit, offset int) ([]entity.ConnectorRun, error)

ListRunsAudit returns connector runs across all (or a filtered subset of) connector instances, newest first. Designed for the cross-connector audit log page and the /api/runs JSON endpoint. Admin-only.

func (*Repo) ListRunsByConnector

func (r *Repo) ListRunsByConnector(ctx context.Context, connectorID string, limit int) ([]entity.ConnectorRun, error)

ListRunsByConnector returns the most recent runs for one connector, newest first. Backed by composite index (connector_id, started_at).

func (*Repo) ListRunsFiltered

func (r *Repo) ListRunsFiltered(ctx context.Context, connectorID string, f RunFilter, limit, offset int) ([]entity.ConnectorRun, error)

ListRunsFiltered returns runs for one connector filtered by op/source/ status/user. The history page uses this to power its filter bar. Supports limit+offset for page-based paging.

func (*Repo) PurgeRunsOlderThan

func (r *Repo) PurgeRunsOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

PurgeRunsOlderThan deletes ConnectorRun rows whose StartedAt is before the cutoff. Returns how many rows were removed so the retention job can log progress.

Backed by the standalone started_at index — a single range delete, no composite index needed.

func (*Repo) ResetStuckRuns added in v0.35.0

func (r *Repo) ResetStuckRuns(ctx context.Context, cutoff time.Time) (int64, error)

ResetStuckRuns finalizes ConnectorRun rows left in "running" whose StartedAt is before cutoff, flipping them to "cancelled" with an explanatory error. These are runs whose op never returned (a crash/restart before the deferred finalizer could write, or the pre-fix era when a hung op left the row running forever). Called at boot and (optionally) on a periodic sweep so the history UI never shows a run wedged in "running" indefinitely. Returns the row count.

func (*Repo) SetAccessPolicy added in v0.16.0

func (r *Repo) SetAccessPolicy(ctx context.Context, id string, p AccessPolicy) error

SetAccessPolicy updates the access policy fields for a connector instance.

func (*Repo) SetAccountDisabledOps added in v0.16.0

func (r *Repo) SetAccountDisabledOps(ctx context.Context, accountID, disabledOpsJSON string) error

SetAccountDisabledOps persists the JSON-encoded disabled ops list for an account.

func (*Repo) SetAccountOpOverrides added in v1.2.9

func (r *Repo) SetAccountOpOverrides(ctx context.Context, accountID, overridesJSON string) error

SetAccountOpOverrides persists the JSON-encoded per-operation override map for an account (opKey → forced bool). Writing "" clears every override, putting the account back to inheriting the instance.

func (*Repo) SetCreatedBy added in v1.2.9

func (r *Repo) SetCreatedBy(ctx context.Context, id, userID string) error

SetCreatedBy re-stamps which wick user owns the instance. CreatedBy is documented as an identity field Update never touches, and that is still right for an edit — but ownership has to be transferable: the owner is who may configure the row and who sees every account connected to it, so an instance whose owner has left the company would otherwise be stuck with an administrator nobody can reach. Empty clears it, leaving the row admin-only.

func (*Repo) SetDescription added in v0.33.0

func (r *Repo) SetDescription(ctx context.Context, id, description string) error

SetDescription updates the per-instance AI-facing description. Empty string clears it. Uses a column map (not a struct) so "" actually writes through (a struct Update would skip the zero value and never clear it).

func (*Repo) SetDisabled

func (r *Repo) SetDisabled(ctx context.Context, id string, disabled bool) error

SetDisabled flips the Disabled flag without touching anything else. Used by the admin manager toggle.

func (*Repo) SetOperation

func (r *Repo) SetOperation(ctx context.Context, connectorID, opKey string, enabled bool) error

SetOperation upserts the toggle for a single (connector, op) pair. Insert when no row exists, update when it does. Uses an explicit OnConflict upsert on the composite PK with a map payload so the boolean Enabled column is always written verbatim: a plain Save() resolves to an UPDATE when the PK is populated (silent no-op on a missing row), and a struct insert drops Enabled=false because the column carries a `default:true` tag — false is indistinguishable from unset. A map value bypasses that zero-value detection.

func (*Repo) SetOperationAdminOnly added in v0.9.0

func (r *Repo) SetOperationAdminOnly(ctx context.Context, connectorID, opKey string, adminOnly bool) error

SetOperationAdminOnly upserts the admin_only flag for a (connector, op) pair without touching the Enabled state. Inserts a new row with Enabled=true (safe default) when no row exists yet.

func (*Repo) SetRateLimit added in v0.9.0

func (r *Repo) SetRateLimit(ctx context.Context, id string, rpm int) error

SetRateLimit updates the per-minute call cap for a connector instance. Pass 0 to remove the limit.

func (*Repo) SetSessionConfigAllowed added in v0.17.0

func (r *Repo) SetSessionConfigAllowed(ctx context.Context, id string, allowed bool) error

SetSessionConfigAllowed flips the per-instance opt-in for per-session config overrides. Separate from SetAccessPolicy so the toggle has its own POST and doesn't round-trip the SSO fields.

func (*Repo) SetSystemDisabled added in v0.10.0

func (r *Repo) SetSystemDisabled(ctx context.Context, connectorID, opKey, reason string) error

SetSystemDisabled marks an operation as disabled by the health-check system with a human-readable reason. The manual Enabled flag is left untouched — effective availability becomes `Enabled AND NOT SystemDisabled`. Upserts a new row when none exists yet.

func (*Repo) SummariseRuns added in v0.9.0

func (r *Repo) SummariseRuns(ctx context.Context, f AuditFilter) (RunSummary, error)

SummariseRuns returns aggregate stats for the given audit filter window.

func (*Repo) Update

func (r *Repo) Update(ctx context.Context, c *entity.Connector) error

Update writes label / disabled changes to an existing row. Per- field config values live in the configs table now and are written by Service.Update via configs.Service.SetOwned, not here. Identity fields (ID, Key, CreatedBy, CreatedAt) are untouched.

func (*Repo) UpdateAccountTokens added in v1.2.9

func (r *Repo) UpdateAccountTokens(ctx context.Context, accountID, access, refresh string, expiresAt *time.Time) error

UpdateAccountTokens rewrites one account's token set after a refresh. refresh "" keeps the stored refresh token (servers may omit it).

func (*Repo) UpsertAccount added in v0.16.0

func (r *Repo) UpsertAccount(ctx context.Context, acc *entity.ConnectorAccount, multiAccount bool) error

UpsertAccount saves a connected account.

  • MultiAccount=false: replace any existing account for this connector (1 slot).
  • MultiAccount=true: update existing account if same wick_user_id exists, otherwise insert new (prevents duplicate rows for the same user).

type RunEvent added in v0.35.0

type RunEvent struct {
	SessionID    string
	RunID        string
	ConnectorID  string
	OperationKey string
	Status       entity.ConnectorRunStatus
	Running      bool
}

RunEvent is emitted to the runObserver as a run starts and finishes, so the conversation UI can show/hide a per-tool-call Cancel button. Running=true is the start (Status "running"); Running=false is the terminal update carrying the final Status. RunID is what the FE passes to the cancel route.

type RunFilter

type RunFilter struct {
	OperationKey string
	Source       string
	Status       string
	UserID       string
	// AccountID narrows to one connected account. RunFilterAccountDefault
	// asks the opposite question — the calls that went out on the row's own
	// credentials — because the zero value is already spoken for ("any").
	AccountID string
}

RunFilter narrows ListRunsFiltered. Empty fields are ignored.

type RunSummary added in v0.9.0

type RunSummary struct {
	Total        int64   `json:"total"`
	Succeeded    int64   `json:"succeeded"`
	Errored      int64   `json:"errored"`
	AvgLatencyMs float64 `json:"avg_latency_ms"`
}

RunSummary holds aggregated stats for a connector run query window.

type Service

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

Service is the runtime façade between code-side connector definitions (kept in-memory by the registry) and DB-side connector rows. The admin UI, the panel-test handler, and the future MCP dispatcher all go through it.

Unlike the jobs Service, Bootstrap does NOT seed DB rows from code: connector instances are admin-created on demand. Bootstrap only wires the dispatch table so Execute can find the right ExecuteFunc when a row references its definition by Key.

func NewService

func NewService(r *Repo) *Service

func NewServiceFromDB

func NewServiceFromDB(db *gorm.DB) *Service

NewServiceFromDB is a convenience constructor for the web server and worker — both already hold a *gorm.DB.

func (*Service) AccountAccessFor added in v1.2.9

func (s *Service) AccountAccessFor(row entity.Connector, userID string, isAdmin bool, tagIDs []string) AccountAccess

AccountAccessFor builds the caller identity that decides which connected accounts a person may SEE and may RUN AS.

One function, used by both the listing and the execute gate, because the bug it exists to prevent is the two drifting: a dropdown that offers an account Execute then refuses. The offer is a promise, and a promise the next click breaks is worse than not offering it — the person cannot tell whether they lack access or the thing is broken.

Privileged means "administers this instance": its creator, or an admin while admin_see_all_connectors is on. With that knob off an admin is scoped like anybody else, which is the point of the knob.

func (*Service) AccountTagIDs added in v1.2.9

func (s *Service) AccountTagIDs(ctx context.Context, accs []entity.ConnectorAccount) (map[string][]string, error)

AccountTagIDs resolves the filter tags attached to each of the given accounts, keyed by account id.

func (*Service) AdminSeesAllConnectors added in v1.2.9

func (s *Service) AdminSeesAllConnectors() bool

AdminSeesAllConnectors reports whether an admin bypasses tag filtering on connector instances and account visibility — the admin_see_all_connectors knob, which is deliberately NOT the same switch as the sessions/projects one: answering both with one switch is how an admin who wanted to see a project ends up able to post as somebody else's Slack account.

Missing/blank config reads as ON — the behaviour every install had before the knob existed. Only an explicit "false" scopes admins like regular users. The /admin/connectors panel is NOT affected: it is the administration surface and always lists everything.

func (*Service) AgentCatalog added in v1.2.9

func (s *Service) AgentCatalog(ctx context.Context, userID string, tagIDs []string, isAdmin bool) ([]CatalogEntry, error)

AgentCatalog is VisibleCatalog plus the wickmanager row when the caller may see it (admins only, by its System tag). wick_list leaves it out because its ops surface as wick_manager_* tools instead; an agent's Access tab still needs it as a System-tier entry.

func (*Service) Bootstrap

func (s *Service) Bootstrap(ctx context.Context, mods []connector.Module) error

Bootstrap registers code-side connector definitions for dispatch and ensures every registered Key has at least one row in the database. Call once at startup with the All() slice from the registry.

For each module: if zero rows currently exist for the Key, an empty row is auto-created with Label = Meta.Name and Configs = "{}". This makes a fresh deploy ready to use — the admin opens the UI and only has to fill in the credentials. Existing rows (and their cred edits) are NEVER touched, so an admin who has already filled cred won't see the row reset on restart.

Duplicate Keys are an error — one Key may not back two definitions. DB rows whose Key has no registered module are tolerated: they show up as "deactivated" in the admin UI, and Execute on them returns an error.

func (*Service) CancelRun added in v0.35.0

func (s *Service) CancelRun(runID string) bool

CancelRun aborts one in-flight op by run id (the per-run Kill button). Returns true if a running op was found and cancelled. Cancelling its context unblocks the plugin gRPC stream so op.Execute returns and its deferred finalizer flips the row to "cancelled". Unknown / already-finished run → false.

func (*Service) CancelSession added in v0.35.0

func (s *Service) CancelSession(sessionID string) int

CancelSession aborts every op currently executing under sessionID and returns how many it cancelled. Cancelling each op's context unblocks its plugin gRPC stream, so op.Execute returns and its deferred finalizer flips the run row to "cancelled" — no op is left running in the background against a session that's gone. Called when a live browser session is closed (session_close). Safe to call for an unknown session (returns 0). Entries are removed by the ops' own deferred deregister, so a cancelled op won't be cancelled twice.

func (*Service) CatalogRefresh added in v0.17.0

func (s *Service) CatalogRefresh(ctx context.Context, key, instanceID string)

CatalogRefresh runs the lazy catalog re-sync hook, when installed. instanceID is the row whose account should authenticate the probe (oauth scheme) — servers may expose different tools per account.

func (*Service) ClearSystemDisabled added in v0.16.0

func (s *Service) ClearSystemDisabled(ctx context.Context, connectorID, opKey string) error

ClearSystemDisabled removes the health-check lock from one operation, allowing admin to override a stale or incorrect health-check result.

func (*Service) CountRunsAudit added in v0.9.0

func (s *Service) CountRunsAudit(ctx context.Context, f AuditFilter) (int64, error)

CountRunsAudit returns total runs for the audit filter — pagination companion.

func (*Service) CountRunsFiltered

func (s *Service) CountRunsFiltered(ctx context.Context, connectorID string, f RunFilter) (int64, error)

CountRunsFiltered returns total runs matching the filter — companion of ListRunsFiltered for paging.

func (*Service) Create

func (s *Service) Create(ctx context.Context, key, label string, configs map[string]string, createdBy string) (*entity.Connector, error)

Create inserts a new Connector row for the given code-defined Key and seeds its per-field config rows in the configs table (owner = "connector:{id}"). configs is the credential map keyed by the Creds-struct field names; values are written one row per field.

Returns the freshly stored row (with ID stamped).

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, id string) error

Delete hard-deletes the connector row plus its operation toggles and its per-field config rows. Run history is intentionally preserved for audit.

func (*Service) DeleteAccount added in v0.16.0

func (s *Service) DeleteAccount(ctx context.Context, accountID string) error

DeleteAccount removes one connected account by ID.

func (*Service) DisabledTypeKeys added in v0.27.2

func (s *Service) DisabledTypeKeys() map[string]bool

DisabledTypeKeys returns the set of connector type keys explicitly disabled, for the manager list to badge them in one shot.

func (*Service) Duplicate

func (s *Service) Duplicate(ctx context.Context, sourceID, createdBy string) (*entity.Connector, error)

Duplicate copies an existing connector row with credentials reset. The new row carries the same Key (so it dispatches to the same code definition) and a "(copy)"-suffixed Label; Configs is "{}" so the admin must re-fill secrets. Tag inheritance is intentionally NOT performed — the caller is responsible for assigning the creator's own tags via the existing ToolTag system.

func (*Service) Enc added in v0.17.0

func (s *Service) Enc() *enc.Service

Enc exposes the encrypted-fields cipher for callers that must tokenize values outside an Execute round-trip (wick_session_workspace encrypts user-typed secrets before persisting instance config). May be nil — callers must treat that as "encryption unavailable".

func (*Service) Execute

func (s *Service) Execute(ctx context.Context, p ExecuteParams) (*ExecuteResult, error)

Execute runs one operation against one connector row, logging a ConnectorRun with the request, response, latency, and IP/UA.

The same code path serves panel-test, MCP tools/call, and retry — the caller distinguishes via params.Source so the run row is tagged correctly. On success the returned ResponseJSON is the marshaled ExecuteFunc return value; on error ErrorMessage carries the message (the run row also stores it).

Validation order:

  1. connector row exists and is not Disabled
  2. connector's Key has a registered module (post-Bootstrap)
  3. requested OperationKey exists on the module
  4. operation is currently Enabled (per OperationStates)

func (*Service) FilterBotSlot added in v0.16.0

func (s *Service) FilterBotSlot(rows []entity.Connector) []entity.Connector

FilterBotSlot removes non-SSO instance rows from a row set when at least one SSO-enabled row (EnableSSO=true) exists for the same connector key in the visible set.

Connectors without OAuthMeta are left untouched — they have no SSO concept. Call this after ListVisibleTo before surfacing rows to the LLM via wick_list.

func (*Service) FinalizeStaleRun added in v0.35.0

func (s *Service) FinalizeStaleRun(ctx context.Context, runID string) error

FinalizeStaleRun flips one still-"running" row to "cancelled". Used when a per-run cancel is requested but no live cancel func is registered — the op already returned or the row is a crash leftover, yet the DB still shows "running". Reclaims exactly that row so the UI doesn't wedge. No-op-safe: if the row isn't "running" the update matches nothing.

func (*Service) Get

func (s *Service) Get(ctx context.Context, id string) (*entity.Connector, error)

Get is a thin pass-through to the repo.

func (*Service) GetAccount added in v0.16.0

func (s *Service) GetAccount(ctx context.Context, accountID string) (*entity.ConnectorAccount, error)

GetAccount returns one ConnectorAccount by ID.

func (*Service) GetRun

func (s *Service) GetRun(ctx context.Context, runID string) (*entity.ConnectorRun, error)

GetRun loads a single ConnectorRun by ID. Backs the test page's prefill flow when a Retry link is followed from the history view.

func (*Service) HealthCheckSessionInstance added in v0.17.0

func (s *Service) HealthCheckSessionInstance(ctx context.Context, baseKey, instanceID string, config map[string]string) ([]connector.OpHealth, error)

HealthCheckSessionInstance runs a base module's HealthCheck hook against a session-workspace instance's own config — the "test setup" button for an ephemeral instance. Returns ErrNoHealthCheck when the base module registers no hook, so the caller can fall back to running a real operation as the probe.

func (*Service) InflightCount added in v1.2.9

func (s *Service) InflightCount() int

NewService wires a Service around an existing Repo and the default HTTP client. The HTTP client is the one Ctx.HTTP exposes to every ExecuteFunc — replace with a custom client at construction time when tests need a transport hook. InflightCount is how many connector operations are executing right now. A single op can legitimately take minutes (a big Metabase query, a slow third-party API), which is exactly why a restart must not cut it off.

func (*Service) IsManageableBy

func (s *Service) IsManageableBy(ctx context.Context, connectorID, userID string, userTagIDs []string, isAdmin bool) (bool, error)

IsManageableBy reports whether the caller may operate on a row from the manager UI. Disabled rows are still manageable — the caller may be re-enabling them.

Three ways in, and ownership is one of them: admin while admin_see_all_connectors is on, the row's creator, or a tag the row carries. Ownership used to be missing, which is how a freshly created instance answered "connector not found" to the person who created it.

func (*Service) IsVisibleTo

func (s *Service) IsVisibleTo(ctx context.Context, connectorID, userID string, userTagIDs []string, isAdmin bool) (bool, error)

IsVisibleTo reports whether a single connector row is accessible to the caller. Used by tools/call to re-check authorization at dispatch time so a stale tools/list snapshot can't be replayed for access.

Must agree with ListVisibleTo, ownership included: a row the caller can see but not dispatch is a listing that lies.

func (*Service) List

func (s *Service) List(ctx context.Context) ([]entity.Connector, error)

func (*Service) ListAccounts added in v0.16.0

func (s *Service) ListAccounts(ctx context.Context, connectorID string) ([]entity.ConnectorAccount, error)

func (*Service) ListAccountsFor added in v1.2.9

func (s *Service) ListAccountsFor(ctx context.Context, connectorIDs []string) (map[string][]entity.ConnectorAccount, error)

ListAccounts returns all connected OAuth accounts for a connector instance. ListAccountsFor is ListAccounts for many instances at once — one query instead of one per row. See Repo.ListAccountsFor.

func (*Service) ListAccountsVisibleTo added in v1.2.9

func (s *Service) ListAccountsVisibleTo(ctx context.Context, row entity.Connector, caller AccountAccess) ([]entity.ConnectorAccount, error)

ListAccountsVisibleTo lists the connected accounts of a row that the given caller may see — the account-level twin of ListVisibleTo.

func (*Service) ListByKey added in v0.10.0

func (s *Service) ListByKey(ctx context.Context, key string) ([]entity.Connector, error)

List returns every connector row newest first, regardless of tag filter or visibility. Used by the admin manager and the retention dashboard. UI-layer code is responsible for tag-filtering for non-admin views.

func (*Service) ListForManager

func (s *Service) ListForManager(ctx context.Context, userID string, userTagIDs []string, isAdmin bool) ([]entity.Connector, error)

ListForManager returns rows the caller can see in the admin manager. Unlike ListVisibleTo, disabled rows are included so users can re- enable or delete them. Admins see every row while admin_see_all_connectors is on.

Rows the caller CREATED are always included, regardless of tags. A new instance inherits the connector type's default tags, which are usually filter tags the creator does not carry — so without this the person who just made an instance could not see it, and with admin_see_all_connectors off not even being an admin helped. Creating something and immediately losing it is not an access policy.

func (*Service) ListRuns

func (s *Service) ListRuns(ctx context.Context, connectorID string, limit int) ([]entity.ConnectorRun, error)

ListRuns returns the most recent ConnectorRun rows for a connector, newest first. Used by the admin detail page to render history under the test panel.

func (*Service) ListRunsAudit added in v0.9.0

func (s *Service) ListRunsAudit(ctx context.Context, f AuditFilter, limit, offset int) ([]entity.ConnectorRun, error)

ListRunsAudit returns connector runs across all instances with optional filters. Intended for the cross-connector admin audit log.

func (*Service) ListRunsFiltered

func (s *Service) ListRunsFiltered(ctx context.Context, connectorID string, f RunFilter, limit, offset int) ([]entity.ConnectorRun, error)

ListRunsFiltered returns runs filtered by op / source / status / user. Backs the history page; pass zero-value filter for "no filter".

func (*Service) ListVisibleTo

func (s *Service) ListVisibleTo(ctx context.Context, userID string, userTagIDs []string, isAdmin bool) ([]entity.Connector, error)

ListVisibleTo returns the not-disabled connector rows the caller can access, applying the same tag-filter rule as Tools (see Repo.ListAccessibleTo). Pass isAdmin=true to bypass tag filtering — admins see every row whether or not they carry the row's tags, unless the admin_see_all_connectors knob is off (see AdminSeesAllConnectors).

Use this from MCP tools/list and any user-facing surface that enumerates connectors; only the admin manager should call List.

Rows the caller CREATED are included regardless of tags, the same rule ListForManager applies — otherwise a creator can administer a row from the dashboard while their own agent session cannot see it, which is how an admin-created custom connector ended up present in /admin/connectors and absent from wick_list. See ownershipReaches for when this applies.

func (*Service) LoadConfigs added in v0.6.1

func (s *Service) LoadConfigs(c entity.Connector) map[string]string

LoadConfigs returns the credential map for a connector row, keyed by the Creds-struct field names. Values are pulled from the configs table (owner = "connector:{id}").

func (*Service) Module

func (s *Service) Module(key string) (connector.Module, bool)

Module looks up a definition by Key. The second return is false when no module is registered for the key (typical when a DB row outlives its code definition after a deploy that drops the connector).

func (*Service) Modules

func (s *Service) Modules() []connector.Module

Modules returns the registered definitions, useful for the "+ New instance" picker in the admin UI.

func (*Service) OperationStates

func (s *Service) OperationStates(ctx context.Context, connectorID, key string) (map[string]bool, error)

OperationStates returns the resolved enable state for every op the connector's definition declares: stored toggle when the row exists, otherwise the per-op default (off for Destructive, on for the rest).

Map key is OperationKey. Returned map is empty when the connector's Key has no registered module.

func (*Service) OperationStatesFull added in v0.10.0

func (s *Service) OperationStatesFull(ctx context.Context, connectorID, key string) (map[string]OpState, error)

OperationStatesFull returns the full per-operation state map for a connector row, folding stored rows + system-disabled flag + the Destructive-default rule. Missing rows mean "use the default" — on for non-destructive, off for destructive.

func (*Service) PurgeOldRuns

func (s *Service) PurgeOldRuns(ctx context.Context, retentionDays int) (int64, error)

PurgeOldRuns deletes ConnectorRun rows older than retentionDays. Returns the number of rows removed. Called by the cleanup job on a daily cadence (set up in a later phase).

func (*Service) RemoveModule added in v0.26.0

func (s *Service) RemoveModule(key string)

RemoveModule drops a module definition at runtime (the reverse of UpsertModule), used by the plugin hot-reloader when a plugin is uninstalled. The connector vanishes from the LLM surface immediately; any DB instance rows persist and become inert (Module() returns false) until a module with the same key is registered again.

func (*Service) ResolveToken added in v1.2.9

func (s *Service) ResolveToken(ctx context.Context, connectorID, accountID, userID string) (string, error)

ResolveToken returns the plaintext token a connector row posts with, for in-process callers that talk to the service themselves (a remote agent adapter). accountID empty = the instance's own token (auth_mode); set = that OAuth account's token, which must belong to connectorID and to userID. The token must never be logged or sent back to a client.

func (*Service) Retry

func (s *Service) Retry(ctx context.Context, originalRunID, userID, ipAddr, userAgent string) (*ExecuteResult, error)

Retry replays an earlier run against the current Connector.Configs. The new run's ParentRunID points to the original; cred edits made since the original are honored.

func (*Service) RowConfigs added in v0.6.1

func (s *Service) RowConfigs(c entity.Connector) []entity.Config

RowConfigs returns the connector module's declared config schema overlaid with the row's stored values. Used by the admin UI so the form always reflects the latest declaration even when EnsureOwned has not yet seeded a brand-new field. Returns nil when the row's Key has no registered module (e.g. after a deploy that dropped the connector — admins should delete the orphan row).

func (*Service) RunHealthCheck added in v0.10.0

func (s *Service) RunHealthCheck(ctx context.Context, connectorID string) (*HealthCheckResult, error)

RunHealthCheck invokes the module's HealthCheck hook and reconciles the per-operation system_disabled flags against the report. Ops the hook reports OK have their lock cleared (if previously set); ops it reports failing get system-disabled with the reported reason. Returns ErrNoHealthCheck when the module did not register a hook.

The hook itself runs against a Ctx populated from the row's stored configs — encrypted credentials are decrypted on read, identical to Execute. The caller's permission to act on this row is the manager handler's job; this method is unauthenticated by design (it is a background-style operation, not user input).

func (*Service) SaveAccount added in v0.16.0

func (s *Service) SaveAccount(ctx context.Context, connectorID, wickUserID, externalUserID, displayName, accessToken string) error

func (*Service) SaveAccountTokens added in v1.2.9

func (s *Service) SaveAccountTokens(ctx context.Context, connectorID, wickUserID, externalUserID, displayName, accessToken, refreshToken string, expiresAt *time.Time) error

SaveAccountTokens is SaveAccount for flows that also carry a refresh token and expiry (OAuth MCP per-user connect). Same MultiAccount upsert rules as SaveAccount.

func (*Service) SessionConfigCapable added in v0.17.0

func (s *Service) SessionConfigCapable(key string) bool

SessionConfigCapable reports whether a connector's MODULE opted into per-session config (the capability). The per-instance toggle is only shown / honored for capable connectors.

func (*Service) SetAccessPolicy added in v0.16.0

func (s *Service) SetAccessPolicy(ctx context.Context, id string, p AccessPolicy) error

SetAccessPolicy updates the access policy for a connector instance.

func (*Service) SetAccountDisabledOps added in v0.16.0

func (s *Service) SetAccountDisabledOps(ctx context.Context, accountID string, opKeys []string) error

SetAccountDisabledOps updates which operations are disabled for an account. opKeys is the list of op keys to disable — empty slice clears all. Every listed key becomes a forced OFF override and everything else goes back to inheriting, which is what the binary editor this backs means by "unchecked". It writes the override map, not the legacy array, so the two representations can never drift apart.

func (*Service) SetAccountOpOverride added in v1.2.9

func (s *Service) SetAccountOpOverride(ctx context.Context, accountID, opKey, state string) error

SetAccountOpOverride sets one operation's state for one account.

"inherit" DELETES the key rather than storing a value: an override that happens to agree with the instance today would silently stop agreeing the moment the instance changed, which is exactly the surprise inheritance is supposed to prevent.

func (*Service) SetCatalogRefresh added in v0.17.0

func (s *Service) SetCatalogRefresh(h func(ctx context.Context, key, instanceID string))

SetCatalogRefresh installs the hook wick_get fires before reading a module's operations — custom MCP connectors lazily re-sync their live tool catalog there. Nil (the default) is a no-op; set once at boot before serving.

func (*Service) SetConfigs added in v0.6.1

func (s *Service) SetConfigs(c *configs.Service)

SetConfigs wires the central configs.Service used to store per- instance config rows under owner = "connector:{id}". When nil, reads fall back to the legacy JSON blob on entity.Connector. Call at boot before Bootstrap so seeded rows get their config rows reconciled into the configs table.

func (*Service) SetDescription added in v0.33.0

func (s *Service) SetDescription(ctx context.Context, id, description string) error

SetDescription updates the per-instance AI-facing description (empty clears).

func (*Service) SetDisabled

func (s *Service) SetDisabled(ctx context.Context, id string, disabled bool) error

SetDisabled toggles the row-level off-switch.

func (*Service) SetEnc added in v0.6.0

func (s *Service) SetEnc(e *enc.Service)

SetEnc wires the encrypted-fields cipher in after construction. Call once at boot from server.go, before Execute is reachable. Passing nil is allowed — Execute then runs without any masking.

func (*Service) SetMetrics added in v0.9.0

func (s *Service) SetMetrics(rec metrics.Recorder)

SetMetrics wires a telemetry recorder into the service. Call once at boot before the server starts accepting requests. Passing nil is safe — the Noop recorder is used instead.

func (*Service) SetOperationAdminOnly added in v0.9.0

func (s *Service) SetOperationAdminOnly(ctx context.Context, connectorID, opKey string, adminOnly bool) error

SetOperationAdminOnly sets the admin_only restriction for a (connector, op) pair. When true, only admin users may call the operation via MCP.

func (*Service) SetOperationEnabled

func (s *Service) SetOperationEnabled(ctx context.Context, connectorID, opKey string, enabled bool) error

SetOperationEnabled flips the per-(connector, op) toggle.

func (*Service) SetOwner added in v1.2.9

func (s *Service) SetOwner(ctx context.Context, id, userID string) error

SetOwner re-stamps the instance's owner — the user OwnsConnector reads. Admin-only by construction: the only caller is the admin connectors page, because an owner who could hand ownership on would also be handing on the right to see every account connected to the row.

func (*Service) SetRateLimit added in v0.9.0

func (s *Service) SetRateLimit(ctx context.Context, id string, rpm int) error

SetRateLimit updates the calls-per-minute cap for a connector instance. Pass 0 to remove the limit.

func (*Service) SetRunObserver added in v0.35.0

func (s *Service) SetRunObserver(fn func(RunEvent))

SetRunObserver wires the hook notified as connector runs start/finish. Called once at boot where the agents SSE broadcaster is in scope, so a running connector run (and its run id) can be surfaced to the conversation UI for a per-run Cancel button. nil disables it.

func (*Service) SetSessionConfigAllowed added in v0.17.0

func (s *Service) SetSessionConfigAllowed(ctx context.Context, id string, allowed bool) error

SetSessionConfigAllowed flips the per-instance opt-in for per-session cloning (Config tab + wick_session_workspace). Only meaningful when the module declares AllowSessionConfig.

func (*Service) SetSessionOwnerBotResolver added in v0.28.0

func (s *Service) SetSessionOwnerBotResolver(fn func(sessionID string) (string, bool))

SetSessionOwnerBotResolver wires the hook that maps an agent session id to the bot user id of the channel instance owning it. Called once at boot from the API server where the channel registry is available. The Slack connector's "Sent using @bot" footer uses the resolved id so a send always names the session owner's bot rather than the sending connector's.

func (*Service) SetSessionOwnerUserResolver added in v0.30.1

func (s *Service) SetSessionOwnerUserResolver(fn func(sessionID string) (string, bool))

SetSessionOwnerUserResolver wires the hook that maps an agent session id to the wick user id that owns it. Called once at boot from the API server where the agents registry is available. Lets per-owner connector ops (data tables) attribute create/access to the human behind the session rather than the shared internal agent principal.

func (*Service) SetTags added in v0.10.0

func (s *Service) SetTags(t tagSeeder)

SetTags wires the tags service used to attach Meta.DefaultTags onto every connector row at boot. Call before Bootstrap. nil disables tag seeding.

func (*Service) SetTypeEnabled added in v0.27.2

func (s *Service) SetTypeEnabled(key string, enabled bool) error

SetTypeEnabled flips the connector-type switch. Disabling hides the whole connector type from the LLM surface (every instance + operation); the manager UI still lists it with a "Disabled" badge so it can be re-enabled.

func (*Service) SetTypeStateDB added in v0.27.2

func (s *Service) SetTypeStateDB(db *gorm.DB)

SetTypeStateDB wires the connector-type enable/disable overlay after construction (for call sites that build the Service via NewService). nil db leaves every type enabled.

func (*Service) SetUserNameResolver added in v1.1.0

func (s *Service) SetUserNameResolver(fn func(userID string) (string, bool))

SetUserNameResolver wires the hook that maps a wick user id to a display name. Called once at boot from the API server where the login service is available. Connectors use it to name people to the model rather than handing it a uuid — see Ctx.UserName.

func (*Service) Status added in v0.6.1

func (s *Service) Status(c entity.Connector) string

Status returns "ready" when every Required field on the connector has a non-empty value, "needs_setup" otherwise. Reads from the configs.Service cache (RWMutex, no DB hit per call).

func (*Service) SummariseRuns added in v0.9.0

func (s *Service) SummariseRuns(ctx context.Context, f AuditFilter) (RunSummary, error)

SummariseRuns returns aggregate stats (total, success, error, avg latency) for the given audit filter window.

func (*Service) TypeEnabled added in v0.27.2

func (s *Service) TypeEnabled(key string) bool

TypeEnabled reports whether the connector type key is enabled. Default-on: an unknown key or a nil overlay returns true.

func (*Service) Update

func (s *Service) Update(ctx context.Context, id, label string, configs map[string]string, disabled bool) error

Update writes label / configs / disabled changes. Identity fields (Key, CreatedBy, CreatedAt) are immutable and untouched.

Per-field config values land in the configs table (owner = "connector:{id}"); only declared keys are written, unknown keys are silently dropped to keep stale form fields from polluting storage.

func (*Service) UpdateAccountTokens added in v1.2.9

func (s *Service) UpdateAccountTokens(ctx context.Context, accountID, accessToken, refreshToken string, expiresAt *time.Time) error

UpdateAccountTokens persists a refreshed token set onto one account.

func (*Service) UpsertModule added in v0.17.0

func (s *Service) UpsertModule(ctx context.Context, m connector.Module) error

UpsertModule installs or replaces one module in the dispatch map at runtime and runs the same row seeding / config reconciliation as Bootstrap. This is the post-boot registration path for DB-defined custom connectors (save + reload) — built-in modules never change after boot. The map swap is atomic under the service mutex: in- flight Execute calls keep the module they already resolved, new calls see the replacement.

func (*Service) VisibleCatalog added in v1.2.9

func (s *Service) VisibleCatalog(ctx context.Context, userID string, tagIDs []string, isAdmin bool) ([]CatalogEntry, error)

VisibleCatalog is what a caller reaches through MCP: the connectors wick_list lists, each with its live ops and the accounts the caller may run it as.

One function for every surface that answers "what can this person use" — wick_list itself and the agent checklist — so a checklist can never offer what wick_list hides, nor hide what it shows. An agent scope on ctx narrows the result as it narrows wick_list; pass a ctx without one to get the person's own reach.

type SessionInstanceTarget added in v0.17.0

type SessionInstanceTarget struct {
	BaseKey string
	Label   string
	Config  map[string]string
}

SessionInstanceTarget describes an ephemeral session-workspace connector for Execute. BaseKey is the module it clones; Config is its full config map (secret values stored as wick_cenc_ master tokens, decrypted by the shared master-token pass in Execute).

Directories

Path Synopsis
Package crudcrud is a sample connector that wraps the crudcrud.com REST sandbox — a free, throwaway JSON store useful for demos and integration smoke tests.
Package crudcrud is a sample connector that wraps the crudcrud.com REST sandbox — a free, throwaway JSON store useful for demos and integration smoke tests.
Package custom is the generic executor behind admin-built custom connectors.
Package custom is the generic executor behind admin-built custom connectors.
Package customconnector is the management connector for custom connector definitions: the same lifecycle the admin UI offers (create / inspect / update / re-sync / disable / delete definitions, plus instance rows), exposed as LLM-callable operations so an agent can build a connector without anyone opening the dashboard.
Package customconnector is the management connector for custom connector definitions: the same lifecycle the admin UI offers (create / inspect / update / re-sync / disable / delete definitions, plus instance rows), exposed as LLM-callable operations so an agent can build a connector without anyone opening the dashboard.
Package datatables exposes the workflow engine's data-table store as its own fixed single-instance MCP connector.
Package datatables exposes the workflow engine's data-table store as its own fixed single-instance MCP connector.
Package httprest is a generic HTTP/REST connector that lets an LLM call any JSON API without writing a custom connector.
Package httprest is a generic HTTP/REST connector that lets an LLM call any JSON API without writing a custom connector.
Package notes exposes wick's notes as a fixed single-instance MCP connector.
Package notes exposes wick's notes as a fixed single-instance MCP connector.
Package notifications exposes Wick's in-process notification service as a fixed connector.
Package notifications exposes Wick's in-process notification service as a fixed connector.
Package plugin is the host side of the connector plugin platform: it spawns connector subprocesses on demand, hands out live gRPC clients, and reaps idle ones.
Package plugin is the host side of the connector plugin platform: it spawns connector subprocesses on demand, hands out live gRPC clients, and reaps idle ones.
Package slack — app_manifest.go: reads the Slack app's declared User Token Scopes so the consent URL can ask for exactly those.
Package slack — app_manifest.go: reads the Slack app's declared User Token Scopes so the consent URL can ask for exactly those.
Package source exposes the session's source-control selection as a fixed single-instance MCP connector.
Package source exposes the session's source-control selection as a fixed single-instance MCP connector.
Package subagents exposes sub-agent delegation as a fixed, single-instance connector.
Package subagents exposes sub-agent delegation as a fixed, single-instance connector.
Package teamagents exposes the Captain's agents.* ops — list, create, update_persona, set_access, schedule — as a fixed, single-instance connector.
Package teamagents exposes the Captain's agents.* ops — list, create, update_persona, set_access, schedule — as a fixed, single-instance connector.
Package teamlink exposes Team-agent messaging as a fixed, single-instance connector, the way sub-agents exposes delegation.
Package teamlink exposes Team-agent messaging as a fixed, single-instance connector, the way sub-agents exposes delegation.
Package tickets exposes wick's ticket entities as a fixed single-instance MCP connector.
Package tickets exposes wick's ticket entities as a fixed single-instance MCP connector.
Package wickmanager exposes wick's own management plane (apps, jobs, tools, connectors, lifecycle server/worker) as a fixed single- instance connector.
Package wickmanager exposes wick's own management plane (apps, jobs, tools, connectors, lifecycle server/worker) as a fixed single- instance connector.
Package workflow exposes the workflow engine as a fixed single-instance MCP connector.
Package workflow exposes the workflow engine as a fixed single-instance MCP connector.

Jump to

Keyboard shortcuts

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