Plugin Development Guide¶
This guide explains how to build plugins for Lyndrix Core and how the core runtime interacts with them.
Plugin model¶
A Lyndrix plugin is a Python package inside /app/plugins/<plugin_folder> with an entrypoint.py module.
At minimum, a plugin provides:
- a
manifest - a
setup(ctx)function
The manifest tells Lyndrix what the plugin is, what permissions it needs, and how it should behave during activation.
Directory structure¶
Minimal plugin¶
A simple, single-page plugin:
app/plugins/my_plugin/
├── entrypoint.py # manifest + lifecycle hooks
├── requirements.txt # optional
├── vendor/ # generated during install — do NOT commit this
├── assets/ # optional static assets
└── locales/ # optional translation files, auto-registered
Recommended structure for non-trivial plugins¶
For any plugin with persistent data, multiple UI pages, or business logic beyond a single page, it is strongly recommended to move all logic into an ./app/ sub-package and keep entrypoint.py as a thin wiring layer.
This is the pattern used by the reference implementation lyndrix-plugin-server-manager.
app/plugins/my_plugin/
├── entrypoint.py # manifest + lifecycle hooks only — no business logic
├── requirements.txt # optional
├── vendor/ # generated during install — do NOT commit this
├── assets/ # optional static assets
├── locales/ # optional translation files
├── examples/ # optional: example YAML/JSON configs for operators
└── app/
├── __init__.py
├── model/ # data layer: ORM models, DB session helpers, external loaders
├── controller/ # business logic: service singletons, event handlers
└── ui/ # NiceGUI components: pages, widgets, dialogs
Layer responsibilities:
| Layer | Responsibility | Examples |
|---|---|---|
model/ |
ORM models, DB session, external YAML/JSON loaders | models.py, database.py, catalog.py |
controller/ |
Business logic, CRUD, service singletons, event emission | service.py, configurator/ |
ui/ |
NiceGUI pages, widgets, dialogs | overview.py, widget.py |
Rules for the ./app/ pattern:
- UI components must never write to the database directly — all DB access goes through the controller layer
entrypoint.pymust only contain:manifest, lifecycle hook functions (setup,teardown,render_settings_ui,render_dashboard_widget), and imports — no business logic, no inline UI components- If your plugin holds state (DB sessions, caches, runtime configuration), expose a single service object from
app/controller/service.pyand import it where needed — avoid creating multiple instances - Include an
examples/directory if your plugin requires operator-provided configuration files (YAML, JSON) — this helps operators understand the expected format without reading source code
Naming rules:
- the folder name must be a valid Python identifier
- if a repository name contains
-, Lyndrix normalizes it to_for imports vendor/is generated at install time — add it to your.gitignore
Stable plugin API¶
Plugin code should import from core.api rather than from internal core modules.
Current stable API version:
__api_version__ = "1.2.0"
The goal is to give plugin authors a stable surface even when the internal core structure evolves.
Database integration¶
If your plugin needs persistent storage, use the Base and db_instance exported from core.api:
- Inherit your SQLAlchemy models from
Base— this registers them with the shared metadata - Use
db_instance.is_connectedto guard DB operations during setup - Call your table bootstrap logic when the
db:connectedevent fires (see Event integration) - Never write raw SQL against the core database schema — only interact with tables your plugin owns
Example model:
from core.api import Base
from sqlalchemy import Column, Integer, String
class MyRecord(Base):
__tablename__ = "my_plugin_records"
id = Column(Integer, primary_key=True)
name = Column(String(255))
Manifest fields¶
ModuleManifest supports the following fields:
| Field | Required | Description |
|---|---|---|
id |
✅ | Unique plugin ID — typically lyndrix.plugin.<name> — must be stable across releases |
name |
✅ | Display name shown in the marketplace and plugin manager |
version |
✅ | Plugin version string — should match the git tag for installable releases |
description |
recommended | Short description shown in marketplace and plugin cards |
author |
recommended | Author name or organization |
icon |
recommended | Material icon name for the plugin card |
type |
✅ | Use PLUGIN for user plugins |
ui_route |
if using NiceGUI | NiceGUI sidebar route mounted by the plugin |
react_ui / react_routes |
if using React | Whether the plugin ships a React bundle + its routes [{path, label, icon, sidebar_visible}]. Each route auto-registers a plugin:<id>:route:<path> permission. |
permissions.subscribe |
as needed | Topics the plugin may subscribe to — unauthorized access raises a PermissionError |
permissions.emit |
as needed | Topics the plugin may emit — unauthorized access raises a PermissionError |
permissions.vault_paths |
as needed | Additional Vault paths beyond the plugin's default namespace |
custom_permissions |
as needed | Fine-grained permissions the plugin declares (see below) — [ManifestPermission] |
roles |
as needed | Named permission bundles with optional group auto-mapping — [ManifestRole] |
settings_schema |
optional | Schema-driven settings rendered by core (GET/PUT /api/plugins/<id>/settings); fields of kind: "action" become buttons (see Settings actions) |
dependencies |
as needed | List of {id, version_constraint} entries for required plugins/modules |
min_core_version |
recommended | Minimum Lyndrix API version required by this plugin |
auto_enable_on_install |
recommended | Whether the plugin auto-activates on install — default is False; the manifest defaults to not activating until configured |
repo_url |
recommended | Source repository URL — used for update checks and marketplace metadata — must point to the canonical lyndrix-platform org URL |
notification_endpoints |
as needed | List of NotificationEndpoints the plugin can route through the central Notification Router |
panels |
optional | Floating, per-user pinnable shell windows rendered from the plugin's React bundle — [{id, label, icon, description?, default_size?, permission?}] (see Panels, API 1.11) |
ai_instructions |
optional | Markdown the plugin hands to the AI assistant about itself (purpose, API paths, vocabulary, cautions; max 20 kB). Never served to shells — read through core.api.module_registry (API 1.11) |
Settings actions (API 1.6)¶
A settings_schema field with kind: "action" is rendered as a button in the core's plugin
settings dialog instead of a value. Clicking it calls <method> /api/plugins/<id><action> — a route
on the plugin's own router, so the plugin's permission gates apply — and shows the reply's message.
Nothing is stored in Vault for action fields; a PUT /settings naming one is rejected with 400.
settings_schema=[
{"key": "action_prune", "label": "Prune old heartbeats now", "kind": "action",
"action": "/maintenance/prune", "category": "Maintenance",
"description": "Runs the hourly retention job right away."},
{"key": "action_delete_all", "label": "Delete ALL monitors", "kind": "action",
"action": "/maintenance/delete-monitors/all", "confirm": True, "danger": True},
]
confirm: true asks before running, danger: true renders the button destructively, method
defaults to POST (PUT/DELETE allowed). The route should return JSON with a human-readable
message plus any counts; it runs with the caller's identity, so gate it with the plugin's
api:write (or a custom permission) exactly like any other mutating route.
Permissions & roles (1.0)¶
Every plugin automatically gets plugin:<id>, plugin:<id>:api:read and
plugin:<id>:api:write in the permission catalog — no declaration needed. Guard
a route with the per-plugin id via the context helper (which namespaces it for
you):
# in a route mounted through ctx.register_routes(...)
router.get("/things", dependencies=[Depends(ctx.require_permission("api:read"))])
Declare finer permissions and roles in the manifest:
from core.api import ModuleManifest, ManifestPermission, ManifestRole
manifest = ModuleManifest(
id="lyndrix.plugin.example",
# ...
custom_permissions=[
ManifestPermission(id="api:apply", label="Apply changes", icon="bolt"),
],
roles=[
ManifestRole(
id="admin", label="Example Administrator",
# local suffixes are namespaced; already-qualified ids pass through
permissions=["api:read", "api:write", "plugin:lyndrix.plugin.example:api:apply"],
auto_map_groups=["INT_ADMIN"], # applied once, ledger-guarded
),
],
)
- A custom permission
api:applybecomesplugin:<id>:api:applyin the catalog and is enforced withctx.require_permission("api:apply"). - A role is registry metadata, not a DB entity. Its
permissionsattach to eachauto_map_groupsgroup exactly once (see Auth). Reference a custom permission by its fully-qualified id inside a role — a bareapi:*suffix is treated as the global permission, not the plugin one. - Global
api:read/api:writeremain a permanent fallback, so a plugin that never declares anything still works for any user holding them.
Important notes on repo_url:
The repo_url field must always point to the current canonical repository under the lyndrix-platform organization. A stale or wrong URL will break the update and marketplace flow.
# ✅ Correct
repo_url="https://github.com/lyndrix-platform/lyndrix-plugin-my-name",
# ❌ Wrong — personal fork, stale URL
repo_url="https://github.com/my-personal-account/lyndrix-my-name",
Lifecycle hooks¶
Required hook¶
setup(ctx)— can be synchronous or asynchronous. Called when the plugin becomes active.
Optional hooks¶
teardown(ctx)— cleanup during deactivation or unloadrender_settings_ui(ctx)— render plugin settings inside the platform settings UIrender_dashboard_widget(ctx)— render a compact widget on the main dashboard
Lifecycle rules¶
setup(ctx)must not block indefinitely — long-running work belongs inctx.create_task(...)- If your plugin needs the database, guard DB operations behind
db:connected(see Event integration) - If setup raises an unhandled exception, the plugin status transitions to
failedand aplugin:setup_failedevent is emitted
Runtime states¶
Plugins can move through the following internal states:
| State | Meaning |
|---|---|
initializing |
Plugin is being loaded and setup() is running |
active |
Plugin is fully operational |
disabled |
Manually disabled by an operator |
blocked |
Enabled, but a declared dependency is missing or inactive |
failed |
setup() raised an unhandled exception |
degraded |
Loaded but manifest validation found issues |
ModuleContext¶
Each plugin receives a ModuleContext instance named ctx. This is the supported bridge into the core runtime.
| Member | Description |
|---|---|
ctx.manifest |
Validated manifest object |
ctx.log |
Plugin-specific logger — lines are tagged Plugin:<name> and are viewable in the plugin manager and via GET /api/logs?source=Plugin:<name> |
ctx.require_permission(suffix) |
FastAPI dependency that requires plugin:<this-id>:<suffix> (namespaced automatically) |
ctx.state |
Transient in-memory state dictionary — lost on restart |
ctx.subscribe(topic) |
Permission-checked event subscription decorator |
ctx.emit(topic, payload) |
Permission-checked event emission |
ctx.create_task(coro, name=...) |
Tracked async task creation |
ctx.get_secret(key) |
Read from the plugin Vault namespace |
ctx.set_secret(key, value) |
Write into the plugin Vault namespace |
ctx.register_routes(router) |
Mount a FastAPI APIRouter under /api/plugins/<id>/ |
ctx.notify(endpoint_name, …) |
Emit a manifest-declared notification through the Notification Router |
ctx.register_gateway_adapter(adapter) |
Register a Messaging Gateway provider adapter |
ctx.register_theme_overrides(overrides) |
Register plugin-scoped theme style overrides |
Choosing the right storage mechanism¶
| What you need to store | Use |
|---|---|
| Temporary runtime flags, cached objects | ctx.state |
| Credentials, tokens, sensitive configuration | ctx.get_secret / ctx.set_secret |
| Persistent business data that must survive restarts | DB models (via Base) |
⚠️
ctx.stateis in-memory only. Do not store anything inctx.statethat must survive a process restart or plugin reload.
Vault isolation¶
Secrets are separated by module identity:
- core components use
core/<manifest.id> - plugins use
plugins/<manifest.id> - both are stored inside the Vault mount
lyndrixusing KV v2
Plugins do not automatically share secret space with each other.
Runtime status (startup sequence / maintenance window)¶
A plugin whose warm-up takes a while (an initial probe sweep, a large import) or that needs a maintenance window reports it through the context instead of letting its endpoints time out:
ctx.set_status("starting", message="Initial probe sweep", progress=(done, total), blocking=True)
# ... work ...
ctx.set_status("ready")
async with ctx.maintenance("Re-importing inventory"): # blocking=True by default
await asyncio.to_thread(self._reimport)
| Phase | Meaning |
|---|---|
starting |
warming up; optionally progress=(done, total) |
ready |
normal operation (the default — a plugin that never calls set_status is ready) |
degraded |
working with reduced function (never blocking) |
maintenance |
temporarily unavailable on purpose |
Effects of a blocking starting/maintenance status:
- the core answers every route of the plugin with
503,Retry-Afterand anX-Plugin-Runtimeheader (JSON status) — public routes included; - the React shell shows a warm-up panel with message, progress and elapsed time instead of the
plugin UI and mounts the UI by itself when
readyarrives; /api/healthdoes not call the plugin'shealth()while it isstartingor in a blockingmaintenance(it reportsunknownwithdetails.reason).
A non-blocking status only adds a banner above the plugin UI. The status is broadcast as
plugin:runtime_status (a core-owned topic, no manifest permission needed), exposed as
runtime in GET /api/plugins and /api/health, coalesced to one progress update per second,
and reset to ready when the plugin is disabled, unloaded or its setup fails. Guard the call with
getattr(ctx, "set_status", None) when the plugin must still load on cores older than API 1.5.
Related guard: the core caps every SQL statement on its pooled connections
(DB_STATEMENT_TIMEOUT_SECONDS, default 60 s, MariaDB max_statement_time). Keep health() and
per-request queries small and do bulk deletes in chunks.
Event integration¶
Plugins should communicate through the event bus via ctx instead of importing the global bus directly.
# ✅ Correct — uses ctx, respects permission declarations
@ctx.subscribe("db:connected")
async def _on_db_ready(payload):
...
# ❌ Wrong — bypasses permission checking
from core.bus import global_bus
global_bus.subscribe("db:connected")(my_handler)
Permission enforcement:
- Every subscribed topic must be declared in
permissions.subscribe - Every emitted topic must be declared in
permissions.emit - Unauthorized access raises a
PermissionErrorimmediately — it does not silently fail
Subscriber identity:
- Every distinct callback is delivered: bound methods of two instances (
a.on_event,b.on_event), closures produced by a factory and lambdas all receive the event. (Cores before this change de-duplicated by module + qualified name and silently kept only the first of them.) - Subscribing the same callback twice — the same function object, or the same bound method of the same instance — is a no-op.
- Subscriptions made through
ctx.subscribeare removed when the plugin is disabled, unloaded, reloaded or itssetup()fails, so a latersetup()never double-subscribes. Handlers subscribed directly on the bus are only removed when the plugin is unloaded — one more reason to usectx.
Common platform topics:
| Topic | When it fires |
|---|---|
vault:ready_for_data |
Vault is unsealed and ready for secret access |
system:boot_complete |
All core components have finished booting |
db:connected |
Database connection established (also fires on reconnect) |
plugin:install_started |
A plugin installation has begun |
plugin:installed |
A plugin installation completed successfully |
plugin:install_failed |
A plugin installation failed |
plugin:files_changed |
Plugin files on disk were modified |
plugin:setup_failed |
A plugin's setup() raised an unhandled exception |
git:status_update |
Git component has a new status |
ui:needs_refresh |
The UI should refresh its state |
Dependencies inside a plugin¶
If a plugin contains a requirements.txt, Lyndrix installs those dependencies during plugin installation or upgrade into the plugin-local vendor/ folder.
This keeps plugin dependencies isolated from the core application environment.
Notes:
- installation happens before the plugin is moved into its final runtime directory
- install failures abort the operation and trigger cleanup
- suspicious requirement lines (e.g. local-path style entries) are rejected
vendor/must be in your.gitignore— it is generated by Lyndrix and should never be committed to source control- vendored packages do not have priority over core packages — they cannot shadow or override core dependencies
Declaring inter-plugin dependencies:
Use the dependencies manifest field to declare that your plugin requires another plugin to be active:
- Lyndrix checks that the dependency is installed and active before activating your plugin
version_constraintis evaluated against the dependency'smanifest.version- A plugin with an unmet or version-incompatible dependency enters
blockedstate
Installation and versioning¶
Lyndrix can install plugins directly from GitHub repositories.
Supported flows:
- install the default branch as
latest - install a specific tag such as
v1.2.3 - upgrade an existing plugin through an atomic staging and swap workflow
During installation, Lyndrix:
- resolves repository metadata through the GitHub API
- downloads a branch or tag archive
- extracts the archive into a staging directory
- validates extraction paths to prevent ZIP path traversal
- verifies that the extracted
manifest.idmatches the expected plugin identity - installs dependencies into
vendor/if needed - moves the plugin into
/app/plugins - emits plugin lifecycle events
Versioning guidance for plugin authors:
- use semantic versioning:
MAJOR.MINOR.PATCH manifest.versionmust match the git tag used for the release- tag releases with
git tag v0.1.0 && git push --tags latestalways tracks the default branch HEAD — only pin to a tag for production deployments- maintain a
CHANGELOG.mdin your plugin repository so operators know what they are upgrading to
Desired plugin state¶
LYNDRIX_PLUGINS_DESIRED allows operators to define plugins that should exist after reconciliation.
Format:
Rules:
- omit
@versionto meanlatest - set
LYNDRIX_PLUGINS_AUTO_UPDATE=trueto auto-updatelatestplugins during reconcile
Cluster placement and leases (API 1.7)¶
A Lyndrix deployment may run several core instances behind a load balancer
(LYNDRIX_CLUSTER_MODE=cluster). Plugins keep one code path: in single mode every lease is
granted to the only instance and cluster=True is a no-op.
manifest = ModuleManifest(..., placement="any") # any | singleton | pinned:<role>
def setup(ctx):
ctx.register_routes(router) # every instance
on_lease = getattr(ctx, "on_lease", None) # older cores: start directly
if callable(on_lease):
on_lease("myplugin:worker", acquired=svc.start, lost=svc.stop) # exactly one instance
else:
svc.start()
ctx.emit("myplugin:items_changed", {...}, cluster=True) # peers receive it with payload["_origin"]
on_lease:acquiredfires when this instance obtains the lease,lostwhen a peer took it or the coordinator was unreachable for a full TTL — stop the work inlost. Leases are released ondispose().ctx.release_lease(name)(API 1.9) gives a wanted lease up at runtime — e.g. when a setting excludes this instance from the work — and fireslostwhen it was held.ctx.emitis thread-safe (core 1.7): a call from a worker thread (asyncio.to_threadcode, blocking Vault/DB helpers) is handed over to the application loop.ctx.lease(name)is a one-shot lease for a piece of work;ctx.is_leader,ctx.instance_id,ctx.cluster_size,ctx.roles,ctx.cluster_modefor diagnostics and one-off tasks.placement="pinned:<role>":setup()runs only on instances with that role; the others answer 503X-Plugin-Runtime: {"phase": "remote"}and the shell shows "runs on another instance".- Rules for cluster-safe plugins (idempotent locked DDL, tolerate MariaDB 1020 on concurrent
writes, no in-process state peers need, standby-aware
health()): High Availability → For plugin developers.
Cluster-wide operations (core 1.8)¶
An install, upgrade or rollback triggered through the API is one operation for the whole cluster: the leading instance opens it with every live instance as participant, every instance reports its outcome once it loaded (or failed to load) the files — the lead directly, the followers through the reconcile — and the last report closes it. The operator gets one notification ("'state_monitoring' upgrade → 1.6.1 on 6/6 instance(s)" or the failed/unreported instances).
GET /api/plugins/operations?active=true&limit=20andGET /api/plugins/operations/{id}list operations with their per-instance outcomes; SSEplugin:operation_changedreports progress.POST /api/plugins/upgrade-allupgrades every plugin whose newest release tag is newer than the loaded version (one operation each, run one after another).- Participants that never report are closed as
skippedby the leader after 10 minutes, so an operation cannot stay "running" forever. - Plugin authors see nothing of this —
health()aftersetup()decides the instance's outcome, exactly as before (the verification waits up to 24 s for a bootstrapping plugin).
Navigation entries (API 1.9)¶
A plugin whose pages are data — one entry per embedded external service, a per-site console, a
saved dashboard — cannot declare them as react_routes in the manifest. It publishes sidebar
entries at runtime instead:
ctx.register_nav_entries([
{"id": "grafana", "label": "Grafana", "url": "https://grafana.example",
"icon": "insights", "open_mode": "iframe", "group": "Services",
"description": "Dashboards", "order": 10},
])
ctx.clear_nav_entries() # same as register_nav_entries([])
- Each call replaces the plugin's previous set — always pass the complete list.
urlis an absolute http(s) URL or a path on this origin;open_modeisiframe(the shell embeds the page full-height at/ext/<plugin>/<id>),new_tab, orroute(API 1.10: a path inside the shell such as/apps/<plugin>/<route>— use it to expose an optional page of your own React UI without a permanent sidebar tab);groupnames the sidebar section (defaultServices);iconis a Material icon name.- The shell lists a plugin itself only when one of its
react_routeshassidebar_visible: true; a React UI that only consists of a settings page is reached through the header gear and the Plugins page (settings_ui_route). - Shells read
GET /api/nav(api:read, like the plugin list), which returns only entries of plugins the caller may see (plugin:<id>grant, as in/api/me/access), and refetch on thenav:changedSSE topic. - Entries are per instance: register them from the shared database on every instance and
re-register when a peer announces a change (
ctx.emit(..., cluster=True)). They never touch the module registry, so the plugin set and its cluster fingerprint stay what is installed. dispose()(disable/unload) removes the plugin's entries automatically.- Guard with
getattr(ctx, "register_nav_entries", None)to stay loadable on older cores.
Reference: plugins/lyndrix-plugin-external-services (app/logic/routing.py).
Panels (API 1.11)¶
A panel is a floating window the React shell hosts above every page — a chat, a live log, a
quick form. The user opens it from the launcher in the header, drags and resizes it, minimises,
pins or closes it; the shell remembers all of that per user and across devices. The content is
the plugin's own React bundle, so a plugin needs react_ui=True and a built ui_bundle.js.
manifest = ModuleManifest(
...,
react_ui=True,
panels=[
{
"id": "chat", # slug [a-z][a-z0-9_-]{0,40}, unique per plugin
"label": "Assistant", # title-bar text (required)
"icon": "smart_toy", # Material icon name (default "extension")
"description": "Ask the AI about this installation", # optional, launcher hint
"default_size": {"width": 420, "height": 560}, # optional, px (min 320×240)
"permission": "plugin:lyndrix.plugin.ai_assistant:api:read", # optional extra gate
},
],
)
- Invalid declarations fail manifest validation (
ValueError), exactly like the other manifest fields.panelsis part ofPluginOut(GET /api/plugins). - Visibility. The launcher lists a panel when the caller may see the plugin (
plugin:<id>grant, as for sidebar entries) and — ifpermissionis set — holds that permission too. Enforcement still happens in the plugin's API; the flag only decides what is offered. - The
panelprop. The shell mounts the bundle'sPluginAppwith one optional prop:
// What the shell passes — nothing when the plugin is rendered as a page.
interface PluginPanelContext { id: string; pluginId: string }
export default function PluginApp({ panel }: { panel?: PluginPanelContext }) {
if (panel?.id === 'chat') return <ChatView compact /> // panel-aware: compact layout
return <FullPage /> // page route (and unknown panels)
}
A plugin that ignores the prop simply shows its default view inside the window — existing
bundles keep working unchanged. The same bundle instance serves pages and panels, so keep
module-level state panel-agnostic (two mounts can be alive at once).
- Per-user state lives in the account preferences document (GET/PUT /api/me/preferences,
deep-merged server-side) under the panels namespace, one entry per "<plugin_id>/<panel_id>":
{open, pinned, minimized, x, y, width, height, z}. The shell writes it debounced; position and
size are always restored, open is restored only for pinned panels (an unpinned panel is
closed again on the next login). Plugins never touch this document.
- Lifecycle. The window remounts its content on plugin:state_changed for the plugin (same as
a page route); warm-up (ctx.set_status(..., blocking=True)) and pinned:<role> "remote" states
render the same stand-ins as a page. Below the md breakpoint open panels appear as a bottom
sheet (no drag/resize).
- Guard nothing: the field is ignored by older cores (unknown manifest fields are dropped by the
validator), so declaring panels is safe for plugins that also run on cores < 1.9.
module_registry (API 1.11)¶
Plugins that need to know about other plugins — the AI assistant collects every plugin's
ai_instructions — read the loaded manifests through a read-only view instead of reaching into
core.components.plugins.*:
from core.api import module_registry
for m in module_registry.get_manifests(): # List[ModuleManifest]
if m.ai_instructions:
write_instruction_file(m.id, m.ai_instructions)
module_registry.get("lyndrix.plugin.itsm") # ModuleManifest | None
module_registry.is_active("lyndrix.plugin.itsm") # loaded *and* active
It is a view: no loading, enabling or mutation. Treat the result as optional data — another
plugin may be absent or disabled — and refresh it on plugin:state_changed.
AI instructions (API 1.12)¶
A plugin describes itself to the AI assistant in two tiers — and stays the single source of truth for both:
ai_instructions(manifest, API 1.11): one short paragraph — what the plugin is for and when an assistant should reach for it. Not inPluginOut; read throughcore.api.module_registry.ai_instructions_route(manifest, API 1.12): the path below the plugin's API prefix where the plugin serves its full operating guide, by convention/ai/instructions. The route is the plugin's own and answers{"plugin_id", "version", "format": "markdown", "markdown": "<guide>"}— read live from a Markdown file in the plugin repo (e.g.ai/INSTRUCTIONS.md), so the text is always the running version's and nothing is copied anywhere:
manifest = ModuleManifest(..., ai_instructions="GitOps control plane … reach for it to …",
ai_instructions_route="/ai/instructions")
@router.get("/ai/instructions")
async def ai_instructions(_identity: ApiIdentity = Depends(require_permission(PERM_READ))):
path = Path(__file__).resolve().parents[1] / "ai" / "INSTRUCTIONS.md"
text = await asyncio.to_thread(lambda: path.read_text(encoding="utf-8") if path.is_file() else "")
return {"plugin_id": PLUGIN_ID, "version": manifest.version, "format": "markdown", "markdown": text}
The core only indexes: GET /api/ai/plugins (api:read) returns
{"generated_at", "plugins": [{id, name, version, status (active|remote), purpose,
instructions_url}]} built purely from the registry — no plugin knowledge, no stored
bodies; a plugin with neither field does not appear. module_registry.status(id) (API
1.12) exposes the registry status for in-process consumers. The AI assistant plugin
generates its CLAUDE.md from this index and fetches a guide on demand, cached per
plugin version. Older cores ignore the new manifest field (no min_core_version bump
needed for the field alone).
Maintenance windows (API 1.13)¶
core.api.maintenance is the shared vocabulary of the maintenance-window feature. The core
provides the model, the time evaluation and the bus contract — no persistence, no
endpoints, no plugin knowledge. Every plugin implements its own maintenance capability on top
of it and treats the other plugins as optional (an orchestrator-only installation must work).
from core.api import maintenance as mw # core >= 1.11; optional: try/except ImportError
schedules = mw.parse_windows(item["windows"], default_tz="Europe/Berlin")
state = mw.effective_state(schedules, overrides, mw.utcnow())
if state.active: # window or override running
suppress_alerts_until(state.until) # state.source == "window" | "override"
if state.open_ended: # no real end known — see below
recheck_at(state.until)
upcoming = state.next_start # next window that is not yet running
Result semantics (MaintenanceState: active, until, source, next_start, note, open_ended):
| Situation | active |
until |
open_ended |
next_start |
|---|---|---|---|---|
| nothing running | False |
None |
False |
start of the next window within horizon (30 days), else None |
| window/override with a real end | True |
that end (occurrences that overlap or abut are merged into one window; a running window is followed past the horizon to its real end) | False |
next window after it, else None |
| windows that never pause | True |
lower bound — maintenance certainly lasts until then, very likely longer | True |
None |
A window "never pauses" when its occurrences overlap or abut without a gap for 256 occurrences in
a row — e.g. cron: {expr: "*/5 * * * *", duration_minutes: 10}, 0 * * * * with
duration_minutes: 60, or weekly windows that cover the whole week. For those there is no end to
report: until is the end of the last occurrence that was looked at, a time at which the CI is
still in maintenance. Never store an open_ended until as the moment maintenance ends
(e.g. as a suppression end) — show it as "ongoing" and evaluate again when it is reached.
open_ended was added after core 1.11.1 — use getattr(state, "open_ended", False) when the
plugin must run on older cores (which reported now + 30 days here). active_until(), current_interval() and next_window() return
the same lower bound as their end for such windows. Evaluation cost is bounded by that limit
(a few milliseconds per call); callers that evaluate many CIs per request should still do it off
the event loop and once per request.
Window formats (input form in service.yml/iac-controller, normal form on the bus):
| Input | Normal form |
|---|---|
- weekly: {days: [sun], start: "02:00", end: "04:00", tz: Europe/Berlin} |
{"type":"weekly","days":["sun"],"start":"02:00","end":"04:00","tz":"Europe/Berlin"} |
- once: {start: "2026-11-02T22:00+01:00", end: "2026-11-03T02:00+01:00", note: "…"} |
{"type":"once","start":"2026-11-02T21:00:00Z","end":"2026-11-03T01:00:00Z","note":"…"} |
- cron: {expr: "0 2 1 * *", duration_minutes: 180, tz: Europe/Berlin} |
{"type":"cron","expr":"0 2 1 * *","duration_minutes":180,"tz":"Europe/Berlin"} |
weekly.end <= start means "over midnight"; days take mon…sun or 0…6 (0 = Monday).
Cron has five fields with Vixie semantics (day or weekday when both are restricted, names,
0/7 = Sunday, no @ macros); the window lasts duration_minutes from each fire. A missing
tz is the caller's default_tz (site time zone, else UTC). Evaluation is DST-safe through
zoneinfo; all returned datetimes are aware UTC. validate_windows() returns error texts for
linters and UIs; parse_window() raises ScheduleError with a specific message.
Kinds are the Entity-Registry kinds and are open: validate with is_valid_kind()
(lower-case slug), never against a fixed list; KNOWN_KINDS is display order only.
Topics and payloads (constants TOPIC_*, shapes as TypedDicts in the module):
| Topic | Emitter | Payload |
|---|---|---|
maintenance:windows_published |
every plugin that owns windows (orchestrator from controller + service.yml, monitoring for manual windows) |
{source, published_at, replaces: true, items: [{ci_id, kind, name, host_ci_id?, windows: [normal form…], inherited_from: null\|"host"\|"stage_default"\|"site_default", deploy_policy?, incidents?}]} |
maintenance:override_started |
a running deploy, a manual override | {override_id, ci_ids, until, reason, source, started_at, linger_minutes} |
maintenance:override_ended |
same | {override_id, source, ended_at, linger_minutes} |
maintenance:window_missing |
orchestrator when a deploy_policy: window deploy runs at once because no window lies within the horizon |
{event_id, ci_id, kind, name, host_ci_id?, site, stage, horizon_days, job_id, source, detected_at, reason} → ITSM opens a task |
monitoring:outage_persisted |
monitoring, once per outage after offline_minutes outside maintenance |
{outage_id, ci_id, kind, name, host_ci_id?, monitor_id, since, persisted_at, duration_s, rule, error?} |
monitoring:outage_recovered |
monitoring | {outage_id, ci_id, since, recovered_at, duration_s} |
replaces: true means the consumer drops every earlier item of that source in one
transaction. Ids are deterministic: make_outage_id(ci_id, since) =
"<ci_id>:<since ISO UTC>", make_window_missing_id(ci_id, job_id); ITSM uses them as
external_id for idempotent upserts.
Transport rule: emit maintenance:* and monitoring:outage_* locally (no
cluster=True). Plugins with placement=any run on every instance, so the emitter's local
consumer writes the shared DB exactly once. Handlers stay idempotent anyway (unique keys,
delete+insert per source), and a consumer with an in-memory cache invalidates its peers with
its own cluster broadcast.
Overrides are active from started_at until until; after override_ended they linger
for linger_minutes (default 15) and then expire — consumers evaluate at read time
(override_active, effective_state), no timers. An emitter that does not know the end in
advance (a deploy job) sends until = now + DEFAULT_MAX_OVERRIDE_MINUTES (240).
Incident rules (IncidentRule: enabled, offline_minutes, severity, auto_resolve) cascade
with resolve_incident_rule(own, kind, stage_defaults, site_defaults) — the own block wins and
may be partial, then the first incident_defaults mapping that defines the kind;
offline_minutes: 0 disables the rule.
Shell/NiceGUI expose the state colour as --lx-state-maintenance (badge lx-badge--maintenance,
rail lx-status-rail--maintenance, falls back to the paused colour on older servers). Tests:
tests/maintenance/ (pure stdlib — they also run on a bare host).
Authentication extensions¶
Plugins can register custom authentication providers at runtime through the event bus.
Relevant event:
auth:register_providerwith payload{"provider": <AuthProvider instance>}
If you do this, the provider ID must also be listed in LYNDRIX_AUTH_PROVIDERS so the provider chain can activate it.
Extension points¶
Beyond events and routes, plugins can extend several core subsystems through ctx:
| Subsystem | How | Reference |
|---|---|---|
| Messaging providers | Subclass GatewayAdapter and call ctx.register_gateway_adapter(...) to add a delivery channel (Discord, Slack, …) |
Messaging Gateway |
| Notifications | Declare notification_endpoints in the manifest and emit via ctx.notify(...); operators route them internally/externally |
Notification Router |
| Socket providers | Subclass BaseSocketProvider and register it for privileged host-socket access behind core auth |
Sockets |
| Theming | Call ctx.register_theme_overrides({...}) for plugin-scoped UI style overrides |
Settings → Theming |
| API authorization | Guard plugin routes with require_api_auth / require_permission(...) from core.api |
Auth → API authentication |
Testing your plugin¶
Plugin code that follows the ./app/ pattern is independently testable — the model/ and controller/ layers have no dependency on a running core.
Recommended test setup:
- create a
tests/directory alongsideapp/ - mirror the core toolchain: include
pytest,pytest-asyncio,pytest-cov,mypy,ruff, andblackin arequirements-dev.txt - unit-test
model/andcontroller/logic without a running Lyndrix instance - mock
ctxfor lifecycle hook tests — theModuleContextinterface is stable
app/plugins/my_plugin/
├── entrypoint.py
├── app/
│ ├── model/
│ ├── controller/
│ └── ui/
├── tests/
│ ├── test_service.py
│ └── test_models.py
└── requirements-dev.txt
Minimal example¶
from core.api import ModuleManifest
from nicegui import ui
manifest = ModuleManifest(
id="lyndrix.plugin.hello",
name="Hello Plugin",
version="1.0.0",
description="Example plugin",
author="Example",
icon="waving_hand",
type="PLUGIN",
ui_route="/hello",
auto_enable_on_install=False,
repo_url="https://github.com/lyndrix-platform/lyndrix-plugin-hello",
permissions={"subscribe": ["system:boot_complete"], "emit": []},
)
async def setup(ctx):
@ui.page('/hello')
async def hello_page():
ui.label('Hello from plugin')
Best practices¶
Manifest and identity:
- keep
manifest.idstable across releases — changing it creates a new plugin identity - set
auto_enable_on_install=Falsefor plugins that require configuration before first use - always set
repo_urlto the canonicallyndrix-platformorg URL - declare
min_core_versionwhen your plugin depends on newer core behavior
Code structure:
- import from
core.apiwhenever possible — never from internalcore.*modules - use the
./app/sub-package pattern for any plugin with more than trivial logic - keep
entrypoint.pyas a pure wiring layer — manifest, hooks, and imports only - do not write to the filesystem from plugin code; use
ctx.state, Vault secrets, or plugin-owned DB tables
State and secrets:
- use
ctx.get_secret/ctx.set_secretfor credentials and sensitive configuration — never plain files or environment variables - use plugin-owned
Basemodels for data that must survive restarts - reserve
ctx.statefor transient runtime objects only
Async and tasks:
- move long-running or background work into
ctx.create_task(...) - never block in
setup(ctx)— usedb:connectedandvault:ready_for_dataevents to defer initialization
Events:
- declare all subscribed and emitted topics in
permissions— unauthorized access raises immediately - emit well-documented events from your service layer so other plugins can integrate with your plugin
Releases:
- tag every release with a semver git tag that matches
manifest.version - maintain a
CHANGELOG.md - add
vendor/to your.gitignore
Troubleshooting¶
Plugin does not load¶
Check:
entrypoint.pyexists and imports without errorsmanifestis present and is a validModuleManifestinstance- the folder name is a valid Python identifier
- all entries in
requirements.txtcan be installed cleanly
Plugin is blocked¶
Check:
- all entries in
dependenciesare installed and inactivestate - the dependency plugin IDs match exactly (check
manifest.idin each dependency's entrypoint) version_constraintentries are satisfiable against the installed dependency versions
Plugin is in failed state¶
Check:
- the
plugin:setup_failedevent payload for the exception message setup(ctx)does not raise during DB bootstrap or Vault access- the plugin waited for the appropriate event (
db:connected,vault:ready_for_data) before accessing those subsystems
Secret access returns nothing¶
Check:
- whether Vault is unsealed (wait for
vault:ready_for_data) - whether the secret was written under the plugin's own namespace (
plugins/<manifest.id>)
Upgrade fails¶
Check:
- whether the requested tag exists in the source repository
- whether the downloaded archive is valid and the
manifest.idmatches the expected plugin identity - whether
requirements.txtinstalls cleanly in isolation
Permission error on emit or subscribe¶
Check:
- whether the topic is declared in
permissions.emit(forctx.emit) orpermissions.subscribe(forctx.subscribe) - unauthorized access raises a
PermissionError— it will appear in the plugin log and in the platform error stream