Skip to content

Decorators ​

All decorators are imported from plugin.sdk.plugin.

python
from plugin.sdk.plugin import (
    neko_plugin, plugin_entry, lifecycle, timer_interval, message,
    on_event, custom_event,
    hook, before_entry, after_entry, around_entry, replace_entry,
    plugin, quick_action,  # namespace-style alternative and command-palette hint
)

@neko_plugin ​

Marks a class as a N.E.K.O. plugin. Required on all plugin classes.

python
@neko_plugin
class MyPlugin(NekoPluginBase):
    pass

@plugin_entry ​

Defines an externally callable entry point. For how it differs from @llm_tool, see Choosing between @plugin_entry and @llm_tool.

python
@plugin_entry(
    id="process",                # Entry point ID (auto-generated from method name if omitted)
    name="Process Data",         # Display name
    description="Process data",  # Description
    params=MyParamsModel,        # Pydantic model: input is validated at call time (schema generated)
    # input_schema={...},        # Alternative: JSON Schema, published only (not validated); cannot be combined with params
    kind="action",               # "action" | "service" | "hook" | "custom"
    auto_start=False,            # Metadata flag; ordinary entries are not invoked at load
    persist=False,               # Override post-call state snapshot policy
    model_validate=True,         # Validate input with the params model (False passes raw arguments)
    timeout=30.0,                # Execution timeout in seconds
    llm_result_fields=["text"],  # Fields to extract for LLM consumption
    # llm_result_model=MyResult, # Alternative: Pydantic model for the result schema (mutually exclusive with llm_result_fields)
    output_schema={...},         # JSON Schema of the return value (output contract)
    strict_output=False,         # True: a return value that violates the contract fails the call
    metadata={"category": "data"}  # Additional metadata
)
async def process(self, data: str, **_):
    return Ok({"result": data})

Parameters ​

ParameterTypeDefaultDescription
idstrmethod nameUnique entry point identifier
namestrNoneDisplay name
descriptionstr""Description
input_schemadictNoneJSON Schema published to callers. Not validated at runtime; mutually exclusive with params
paramstypeNonePydantic model. Input is validated with it before the handler runs, and its schema is published as input_schema
kindstr"action"Entry type
auto_startboolFalseMetadata flag; ordinary plugin_entry handlers are not invoked automatically at load
persistboolNoneOverride whether configured freezable state is saved after this entry runs
model_validateboolTrueValidate input with the params model; False passes the raw arguments
timeoutfloatNoneExecution timeout (seconds)
llm_result_fieldslist[str]NoneFields for LLM result extraction
llm_result_modeltypeNonePydantic model for result schema
fieldstypeNoneAlias for llm_result_model
metadatadictNoneAdditional metadata
output_schemadictNoneJSON Schema of the return value. Inferred from a Pydantic return annotation when omitted. See Output contract
strict_outputboolFalseWhen the return value violates the output contract, also fail the call (PLUGIN_OUTPUT_SCHEMA_VIOLATION). The default only logs a warning; strict mode logs the warning too. Only contracts inferred from a Pydantic return annotation are checked, so it has no effect on an explicit output_schema

output_schema is independent of llm_result_fields / llm_result_model: those decide what a model reads, output_schema describes the whole return value. The two can be combined.

A contract inferred from a Pydantic return annotation is validated at runtime by the model (like params); an explicit output_schema is published only (like input_schema). See Output contract.

TIP

Use **_ only when the handler intentionally accepts extra host-supplied fields. The runtime filters unsupported keyword arguments for handlers with explicit signatures, so it is not mandatory.

Runtime entries must use async def; the host rejects synchronous entry handlers.

@lifecycle ​

Defines optional handlers for startup, shutdown, external configuration changes, and process suspension. Use startup for initialization; a normal @plugin_entry(auto_start=True) is not executed when the plugin process starts.

python
@lifecycle(id="startup")
async def on_startup(self, **_):
    cfg = await self.config.dump()
    self.timeout = cfg.get("my_settings", {}).get("timeout", 30)
    return Ok({"status": "ready"})

@lifecycle(id="shutdown")
async def on_shutdown(self, **_):
    stop = getattr(self, "_worker_stop", None)  # threading.Event of a worker thread you started
    if stop:
        stop.set()
    return Ok({"status": "stopped"})

@lifecycle(id="config_change")
async def on_config_change(self, old_config, new_config, mode):
    self.timeout = new_config.get("my_settings", {}).get("timeout", 30)
    return Ok({"status": "config_updated"})
Lifecycle ID or actionWhen it happensTypical use
startupPlugin process startsLoad and validate config, prepare plain resources
shutdownPlugin process stopsStop your own threads, save state, release plain resources
Plugin Manager ReloadUser clicks ReloadRuns shutdown, then starts the process and runs startup
config_changeConfig is changed externallyApply new settings without a restart
freeze / unfreezePlugin is suspended or resumedPause or resume work

The reload lifecycle ID remains accepted for compatibility, but the Plugin Manager Reload button restarts the process instead of dispatching it. Updating configuration through await self.ctx.update_own_config(...) or await self.config.update(...) also does not dispatch config_change back to the same process; refresh derived state after the call.

startup, shutdown, and each timer tick run in their own event loop (asyncio.run); all entry calls share one long-running command loop that is separate from them. A task created with asyncio.create_task in startup is cancelled when startup returns, and an async client or session created in one phase cannot be used or closed in another. Create async clients inside the call that uses them (async with ...).

@timer_interval ​

Defines a scheduled task that executes at fixed intervals.

python
@timer_interval(
    id="cleanup",
    seconds=3600,           # Execute every hour
    name="Cleanup Task",
    auto_start=True          # Start automatically (default: True)
)
async def cleanup(self, **_):
    # Runs in a dedicated timer thread; each tick gets a new event loop
    return Ok({"cleaned": True})

INFO

Timer tasks must use async def. Each timer runs in a separate thread, and each tick runs in a new event loop (asyncio.run), so do not keep async clients on self across ticks; exceptions are logged but don't stop the timer.

@message ​

Registers a message handler.

Not dispatched by the host

The host does not currently deliver host or chat messages to @message handlers. A handler only runs when another plugin calls it explicitly with self.plugins.call_event("<plugin_id>:message:<id>", ...). Do not build features on it.

python
@message(
    id="handle_chat",
    source="chat",           # Filter by message source
)
async def handle_chat(self, text: str, sender: str, **_):
    return Ok({"handled": True})

@on_event ​

Generic event handler for custom event types.

python
@on_event(
    event_type="custom_event",
    id="my_handler",
    kind="hook"
)
async def custom_handler(self, event_data: str, **_):
    return Ok({"processed": True})

@custom_event ​

Specialized event handler with trigger method control.

python
@custom_event(
    event_type="data_refresh",
    id="refresh_handler",
    trigger_method="message",  # How this event is triggered
    auto_start=False
)
async def on_refresh(self, source: str, **_):
    return Ok({"refreshed": True})

@quick_action ​

Marks a plugin entry for prominent display in the command palette. Put it below @plugin_entry so Python applies it first:

python
@plugin_entry(id="get_weather", name="Get Weather")
@quick_action(icon="🌤️", priority=10)
async def get_weather(self, city: str = ""):
    return Ok({"city": city})

Larger priority values appear earlier. This decorator changes display metadata only; it does not alter Agent routing or execute the entry automatically.


Hook Decorators (AOP) ​

Metadata only, not executed today

These decorators only record hook metadata on the method. Nothing in the current host or SDK runs them (HookExecutorMixin is a contract stub that raises NotImplementedError), so they do not intercept, modify, abort, or replace any entry call. Put such logic in the entry itself or in a helper it calls. The descriptions below are the intended semantics.

@before_entry ​

Intended to run before the target entry point and modify arguments or abort execution (not executed today).

python
@before_entry(target="process", priority=0)
def validate_input(self, *, args, entry_id, **_):
    if not args.get("data"):
        return Err(SdkError("data is required"))
    # Return None to continue, or Err to abort

@after_entry ​

Intended to run after the target entry point and modify or replace the result (not executed today).

python
@after_entry(target="process", priority=0)
def log_result(self, *, result, entry_id, **_):
    self.logger.info(f"Entry {entry_id} returned: {result}")
    # Return None to keep original result, or a new value to replace it

@around_entry ​

Intended to wrap the target entry point with full control over execution (not executed today).

python
@around_entry(target="process", priority=0)
async def timing_wrapper(self, *, proceed, args, **_):
    import time
    start = time.time()
    result = await proceed(**args)
    elapsed = time.time() - start
    self.logger.info(f"Took {elapsed:.2f}s")
    return result

@replace_entry ​

Intended to replace the target entry point completely (not executed today).

python
@replace_entry(target="old_entry", priority=0)
async def new_implementation(self, **kwargs):
    return Ok({"replaced": True})

Hook parameters ​

ParameterTypeDefaultDescription
targetstr"*"Entry ID to hook ("*" = all entries)
priorityint0Execution order (lower = earlier)
conditionstrNoneOptional condition expression

Namespace-Style Alternative: plugin.* ​

For cleaner syntax, use the plugin namespace object:

python
from plugin.sdk.plugin import plugin

@plugin.entry(id="greet", description="Say hello")
async def greet(self, name: str = "World", **_):
    return Ok({"message": f"Hello, {name}!"})

@plugin.lifecycle(id="startup")
async def on_startup(self, **_):
    return Ok({"status": "ready"})

@plugin.hook(target="greet", timing="before")  # metadata only, not executed today
def validate(self, *, args, **_):
    pass

@plugin.timer(id="heartbeat", seconds=60)
async def heartbeat(self, **_):
    return Ok({"alive": True})

@plugin.message(id="on_chat", source="chat")  # not dispatched by the host, see @message
async def on_chat(self, text: str, **_):
    return Ok({"handled": True})