Plugin Capabilities and SDK Reference
All plugin development APIs are imported from plugin.sdk.plugin.
from plugin.sdk.plugin import (
# Base
NekoPluginBase, PluginMeta,
# Decorators
EntryKind, neko_plugin, plugin_entry, lifecycle, timer_interval, message,
on_event, custom_event, hook, before_entry, after_entry, around_entry,
replace_entry, quick_action, plugin, ui,
# LLM tools and activity
llm_tool, LlmToolMeta, OsActivitySnapshot, get_os_activity_snapshot,
# Plugin-local i18n and settings
PluginI18n, tr, PluginSettings, SettingsField,
# Result types
Ok, Err, Result, unwrap, unwrap_or,
# Runtime helpers
Plugins, PluginRouter, PluginConfig, PluginStore,
SystemInfo,
# Errors
SdkError, TransportError,
# Logging
get_plugin_logger,
)plugin.sdk.plugin is the supported developer import surface. The root plugin.sdk package intentionally exposes only a conservative shared subset; do not assume every plugin-only helper is re-exported there.
NekoPluginBase
All plugins must inherit from NekoPluginBase.
@neko_plugin
class MyPlugin(NekoPluginBase):
def __init__(self, ctx):
super().__init__(ctx)Properties
| Property | Type | Description |
|---|---|---|
self.ctx | PluginContext | The runtime context (injected by host) |
self.plugin_id | str | This plugin's unique identifier |
self.plugin_dir | Path | Installed plugin directory containing code, manifest, and static assets |
self.config_dir | Path | Compatibility alias for self.plugin_dir |
self.storage_dir | Path | User storage root assigned to this plugin |
self.runtime_config_path | Path | External runtime configuration file |
self.metadata | dict | Always {} in the plugin process today (plugin.toml data is not passed in). Read configuration with await self.config.dump() |
self.bus | SdkBusContext | Read/watch facade over host state; it has no publish/emit API |
self.plugins | Plugins | Cross-plugin call helper |
self.system_info | SystemInfo | Host system metadata |
Everyday capabilities
NekoPluginBase provides logging and configuration without extra setup:
self.logger.info("Processing request: %s", request_id)
timeout = await self.config.get_int("my_settings.timeout", default=30)Logs appear in the Plugin Manager and are written to the host-managed log directory. The host owns log-file location and rotation. Runtime configuration updates use await self.ctx.update_own_config(...) or await self.config.update(...); after updating, refresh any derived state in the same process.
Choose storage by data shape:
| Need | API |
|---|---|
| Small key-value state | self.store after enabling [plugin.store] |
| Structured SQLite data | self.db after enabling [plugin.database] |
| Arbitrary persistent files | self.data_path(...) |
| Rebuildable files | self.cache_path(...) |
| Files other plugins may read | self.shared_path(...) |
| Files another plugin published | self.shared_path_of("<plugin_id>", ...) after declaring it in [plugin.shared] |
from plugin.sdk.plugin import unwrap
unwrap(await self.store.set("last_query", "weather"))
async with unwrap(await self.db.session()) as session:
await session.execute(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, title TEXT)"
)
await session.commit()For translated plugin text, configure [plugin.i18n], add locale JSON files, and use self.i18n.t(...):
message = self.i18n.t("greeting", name="Alice")self.i18n.t(...) does not follow the user's language: without locale= it looks up the plugin's default_locale, then its base language (for example fr for fr-CA), then en, then falls back to the default argument or the key. For user-facing strings that the host registers (plugin and entry names, descriptions, schema labels, UI action labels), use tr("key", default="..."), which the host resolves for each user's locale.
Methods
report_status(status: dict) -> None
Report plugin status to the host process.
self.report_status({
"status": "processing",
"progress": 50,
"message": "Halfway done..."
})push_message(**kwargs) -> PushMessageResult
Push a message to the host system with the v2 schema: visibility controls rendering in the user's chat or HUD, ai_behavior independently controls whether the model reads the message or responds, and parts carries text, images, and ui_actions.
result = self.push_message(
source="my_feature",
visibility=["chat"], # [], ["chat"], ["hud"], or both
ai_behavior="blind", # "respond", "read", or "blind"
parts=[{"type": "text", "text": "Task complete"}],
priority=5,
)
if not result["submitted"]:
self.logger.warning("push failed: %s", result.get("reason"))The return value reports only local submission (submitted / reason). For the full axis semantics, parts types, payload and image size limits, ctx.images.upload(), and v1 field migration, see Message Delivery.
data_path(*parts) -> Path
Get a path under the plugin's data/ directory.
db_path = self.data_path("records.db")
# → <storage-root>/plugins/<plugin_id>/data/records.dbcache_path(*parts) -> Path
Get a path under the plugin's disposable cache directory.
preview_path = self.cache_path("preview.png")
# → <storage-root>/plugins/<plugin_id>/cache/preview.pngshared_path(*parts) -> Path
Get a path under the directory this plugin publishes for other plugins to read. The directory is not created for you, and it is kept when the plugin is removed. The directory is named after the plugin id; characters other than lower-case letters, digits, _ and - are escaped in the name, so always take the path from this method.
cities = self.shared_path("cities.json")
# → <storage-root>/plugin_shared/<plugin_id>/cities.json
cities.parent.mkdir(parents=True, exist_ok=True)shared_path_of(plugin_id, *parts) -> Path
Get a path under another plugin's shared directory, for reading. That plugin's id must be listed under [plugin.shared] reads in plugin.toml; otherwise ValidationError is raised (code="shared_not_declared"). A path that would leave the shared directory is refused as well (code="shared_bad_path").
cities = self.shared_path_of("weather", "cities.json")
# → <storage-root>/plugin_shared/weather/cities.jsonThis is an agreement between plugins, not a security boundary: plugins are not sandboxed from each other. Treat the files as read-only.
register_dynamic_entry(entry_id, handler, ...) -> bool
Register an entry point at runtime (not via decorator).
async def greet(name: str = "World", **_):
return Ok({"msg": f"Hi {name}"})
self.register_dynamic_entry(
entry_id="dynamic_greet",
handler=greet,
name="Dynamic Greet",
description="A dynamically registered greeting",
)The handler must be an async def function: registration accepts any callable, but calling an entry whose handler is not a coroutine function fails with Entry must be 'async def'.
unregister_dynamic_entry(entry_id) -> bool
Remove a dynamically registered entry.
list_entries(include_disabled=False) -> list[dict]
List all entry points (static + dynamic).
enable_entry(entry_id) / disable_entry(entry_id) -> bool
Enable or disable a dynamic entry at runtime.
register_static_ui(directory, *, index_file, cache_control) -> bool
Register a static web UI directory for this plugin.
self.register_static_ui("static") # serves <plugin_dir>/static/index.htmlinclude_router(router, *, prefix) -> None
Mount a PluginRouter to organize a large or feature-split normal plugin.
Also list every router class in the plugin class attribute __routers__: the host's static entry scan only reads that list (see PluginRouter). Do not combine a router class listed there with prefix: the listed ID would not be callable (see Prefixed Routers). Related methods are exclude_router(router_or_name) -> bool, get_router(name), and list_routers(). A Router cannot be the manifest [plugin].entry. on_mount / on_unmount are never called by the host; do not override them.
Hosted/static UI and list actions
Hosted TSX uses the exported ui namespace plus manifest surfaces; see Hosted UI. Legacy static UI uses register_static_ui(...). List-row actions are managed with set_list_actions(...), register_list_action(...), clear_list_actions(), and get_list_actions().
LLM tool methods
register_llm_tool(...), unregister_llm_tool(name), and list_llm_tools() are the imperative counterparts to @llm_tool. They register conversation-time tools, not user-plugin Agent entries. The sync calls are fire-and-forget; await register_llm_tool_async(...) and await unregister_llm_tool_async(name) return what main_server actually answered (ok, per-role results, error) and keep the plugin's local registration in step with it. See LLM Tool Calling.
run_update(**kwargs) -> object (async)
Send an update to the host during long-running operations.
export_push(**kwargs) -> object (async)
Push export data to the host.
finish(**kwargs) -> Any (async)
Signal task completion to the host.
Reply Control
finish() takes a delivery argument ("proactive" by default, "passive", or "silent") that controls whether the result enters the main AI's context and whether the character speaks immediately. reply=True/False is the deprecated boolean alias. delivery takes effect when the Agent calls the entry directly. When a task agent calls the entry, the result goes back to the task agent, and how the user is told follows the task's own setting.
# Normal: character will announce the result
return await self.finish(data={"summary": "Done"})
# Silent: result is recorded but character stays quiet
return await self.finish(data={"summary": "Done"}, delivery="silent")For the three modes, result_kind result semantics, and the {MASTER_NAME} / {LANLAN_NAME} role placeholders, see Message Delivery.
LLM Result Field Filtering
Use llm_result_fields on @plugin_entry (static entries) or register_dynamic_entry() (dynamic entries) to control which fields of the result a model can see: the main LLM when the entry is called directly, or the task agent that called it. Fields not listed are excluded from the prompt but remain in the run's result. See "How the Agent calls an entry" in Entries for what is shown when an entry declares no fields.
# Static entry
@plugin_entry(llm_result_fields=["summary"])
async def search(self, query: str):
return await self.finish(data={"summary": "3 results", "raw_results": [...]})
# Dynamic entry
self.register_dynamic_entry(
entry_id="my-tool",
handler=handler,
llm_result_fields=["summary"],
)Output Contract
output_schema on @plugin_entry or register_dynamic_entry() declares the JSON Schema of the return value. Symmetric with inputs: a static entry whose return annotation is a Pydantic model gets it inferred and its returned data is validated by the model at runtime (like params); an explicit output_schema mapping, including every dynamic entry's, is published only (like input_schema). A mismatch is a rate-limited warning in the plugin log by default; with strict_output=True the call fails with PLUGIN_OUTPUT_SCHEMA_VIOLATION. Logs and errors carry field paths and error types only. See Output contract.
self.register_dynamic_entry(
entry_id="my-tool-described",
handler=handler,
output_schema={"type": "object", "required": ["summary"]}, # published, not checked
)Result Types: Ok / Err
The SDK uses Rust-inspired Result types for error handling instead of exceptions.
from plugin.sdk.plugin import Ok, Err, unwrap, unwrap_or
# Returning success
return Ok({"data": result})
# Returning error
return Err(SdkError("something went wrong"))
# Consuming results
result = await self.plugins.call_entry("other:do_stuff")
if isinstance(result, Ok):
data = result.value
else:
error = result.error
self.logger.error(f"Call failed: {error}")
# Helper functions
value = unwrap(result) # raises if Err
value = unwrap_or(result, None) # returns default if ErrPlugins (Cross-Plugin Calls)
Access via self.plugins.
# List all plugins
result = await self.plugins.list()
# List only enabled plugins
result = await self.plugins.list(enabled=True)
# Get plugin IDs
result = await self.plugins.list_ids()
# Check if a plugin exists
result = await self.plugins.exists("other_plugin")
# Call another plugin's entry point
result = await self.plugins.call_entry("other_plugin:do_work", {"key": "value"})
# Call and ensure JSON object response
result = await self.plugins.call_entry_json("other_plugin:get_data")
# Require a plugin to be present and enabled
result = await self.plugins.require_enabled("dependency_plugin")All methods return Result types — check with isinstance(result, Ok) before using .value.
Who called you: ctx.call_chain
self.ctx.call_chain is a read-only view of how the current invocation was reached. The host builds it from its own records; you only read it, and nothing you change in it affects the host.
chain = self.ctx.call_chain
chain.callers # plugin ids that led here, root first; () when the host called you directly
chain.origin.kind # "run", "chat_tool", "chat_hook", "ui_action", "plugin_self" or "system"
chain.origin.ref # an id such as the run id; never message text
chain.hops # each step as (plugin_id, event_type, event_id)
chain.rights # permissions every plugin on the chain has been approved for
chain.rights_known # False when the host did not say (see below)
chain.allows("plugin_sdk.main_agent.memory:read")- It is never
None. Outside an invocation (a timer, a background task still running after your entry returned), it is a chain holding only your plugin, withrights_known=False. rightsholds permission ids such asplugin_sdk.main_agent.memory:read. For one release it also holds the earlier names (memory.read,conversations.read,messages.push), andallows()accepts either form.allows()is advisory. It answersFalsewhenever the rights are unknown, so "not allowed" and "do not know" both readFalse; checkrights_knownto tell them apart. The host decides every use on its own: aFalsehere does not mean the host will refuse, and aTrueis a snapshot taken when the call was delivered.- Work you hand to a bare
threading.Thread, a thread pool of your own, orloop.run_in_executorwith an executor of your own loses the invocation context, so the host sees those requests as your plugin acting on its own.asyncio.to_threadkeeps it; for a thread of your own, run the work undercontextvars.copy_context().run(...). loop.run_in_executor(None, ...)keeps it too, but only on the event loop the plugin runtime runs your code on: the runtime sets that loop's default executor to one that copies the context. On an event loop you create yourself, or after you replace the default executor, it loses the context.neko-plugin checkcannot tell which loop arun_in_executor(None, ...)call runs on, so it does not list that call as a blind spot; it listsasyncio.new_event_loop,asyncio.Runnerandset_default_executorinstead. Other ways of getting a loop of your own, such as callingasyncio.runfrom your code, are not listed.- This is separate from the older in-process helpers in
plugin.sdk.shared.runtime.call_chain, which only track calls inside one plugin process.
The host records cross-plugin calls and capability use for audit (identifiers and capability names only, never arguments, results or message text). Design: docs/design/plugin-call-chain.md.
PluginStore (Persistent Storage)
Access via self.store (the host pre-builds and injects it at plugin construction time — you do not instantiate PluginStore yourself). It is disabled unless plugin.toml has [plugin.store] with enabled = true; while disabled, set() stores nothing and get() returns the default.
All PluginStore methods return a Result; unwrap with unwrap_or(...).
unwrap_or(await self.store.set("key", {"count": 42}), None)
value = unwrap_or(await self.store.get("key"), None) # → {"count": 42}SystemInfo
Access via self.system_info. These methods all return a Result; unwrap with unwrap_or(...).
config = unwrap_or(await self.system_info.get_system_config(), {})
settings = unwrap_or(await self.system_info.get_server_settings(), {})
python_env = unwrap_or(await self.system_info.get_python_env(), {})PluginContext (ctx)
The ctx object is injected by the host at construction time.
| Property | Type | Description |
|---|---|---|
ctx.plugin_id | str | Plugin identifier |
ctx.config_path | Path | Path to plugin.toml |
ctx.logger | Logger | Logger instance |
ctx.bus | SdkBusContext | Read/watch facade over host state |
ctx.metadata | dict | The ctx passed to __init__ has no metadata attribute (reading it raises AttributeError); the wrapped self.ctx.metadata returns {}. Use await self.config.dump() for configuration |
Bus and memory
Inside async entries, await get() before applying the local list operations:
events = await self.bus.events.get(plugin_id=self.plugin_id, max_count=50)
recent = events.filter(priority_min=1).sort(by="timestamp", reverse=True).limit(20)
records = await self.bus.memory.get(bucket_id="default", limit=20)The list surface is filter / where, sort, limit, and watch. Callable filter(predicate), where(predicate), and sort(key=...) are local-only; replayable watcher chains must use structured filter(field=value, ...) and sort(by=...). Only messages, events, and lifecycle support watch(); conversations, memory, and frames are read-only snapshots. Watcher subscriptions accept only add, del, or change.
These stores are shared, and reading them is not gated per plugin: any enabled plugin can read conversations and frames, including turns and pictures that came from the user or from another plugin. Nothing here widens what the host already sent to the model — a frame the session never sent never appears — but it does widen who can see it, from the model provider to every plugin the user has enabled. Treat installing a plugin as granting it that visibility, and say so in your own plugin's description if you read these.
bus.memory contains a bounded, in-memory window of recent user-utterance events (one-hour TTL); it is separate from the character's persistent facts, reflections, and persona. ctx.query_memory(...) runs the same hybrid recall as the built-in recall_memory tool over the character's private memory and returns {"result": text}, where text is a numbered, token-budgeted block of hits rendered in the character's prompt language, or an empty string when nothing relevant was found.
Frames
bus.frames holds the last few frames the host already pushed to the model provider — exactly the bytes the provider received.
frames = await self.bus.frames.get(max_count=4)
latest = frames.sort(by="timestamp", reverse=True).limit(1)A plugin cannot ask for a capture. A frame the session's own throttle or delivery-mode fence dropped was never sent to the provider, so it never appears here.
This is not a log and not a queue. Frames are dropped by design at four points: the message-plane PUB socket is lossy for slow joiners and at its high-water mark, the host publish is non-blocking, the send queue is bounded and refuses frames as soon as it falls behind, and the store keeps only a handful (NEKO_MESSAGE_PLANE_FRAMES_STORE_MAXLEN, clamped to 2-8, default 4). Polling for "every frame", or expecting a frame you read once to still be there, will be wrong.
Each record carries image_base64 (one copy — there is no raw-bytes twin to read), mime, source, captured_at, turn_id, generation, frame_id, and metadata. source is the channel the host attributed the frame to: screen, camera, plugin, callback, proactive, user, or unknown once a turn was reshaped and the host could no longer say. screen and camera separate the two live channels only on the voice path; in text mode every frame the user shares — a shared screen, a camera still, a dragged-in photo — arrives through one queue that does not keep them apart, so it is reported as user. Filter for user if you want "something the user showed the character" in both modes. Dedupe on frame_id: generation orders ambient frames but does not advance for one-shot cue images, so two records can share one.
Pictures a tool handed back are on this bus too, once the follow-up request that carried them was answered. They arrive with source="plugin" and a metadata of {"tool_name": "..."}. A tool may return up to 2 MiB of base64; anything over the delivery budget (500 KiB) is re-encoded by the host through the same profile every model-bound image goes through — JPEG, at most 1280x720 — so it fits under the message plane's record bound and reaches both the model and this bus. The record then says mime: image/jpeg even if the tool handed back a PNG, and the tool result carries a model-visible note that the picture was re-encoded. An image that still will not fit after that is dropped with its own warning rather than sent. Read source before you read the pixels: a plugin frame is media some plugin gave the model — possibly not yours — and is not a picture the user shared with the character.
Priority levels
| Range | Level | Use case |
|---|---|---|
| 0-2 | Low | Informational messages |
| 3-5 | Medium | General notifications |
| 6-8 | High | Important notifications |
| 9-10 | Emergency | Needs immediate handling |
