Skip to content

插件能力与 SDK 参考 ​

所有插件开发 API 均从 plugin.sdk.plugin 导入。

python
from plugin.sdk.plugin import (
    # 基类
    NekoPluginBase, PluginMeta,
    # 装饰器
    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 工具与系统活动
    llm_tool, LlmToolMeta, OsActivitySnapshot, get_os_activity_snapshot,
    # 插件本地 i18n 与设置
    PluginI18n, tr, PluginSettings, SettingsField,
    # Result 类型
    Ok, Err, Result, unwrap, unwrap_or,
    # 运行时辅助工具
    Plugins, PluginRouter, PluginConfig, PluginStore,
    SystemInfo,
    # 错误
    SdkError, TransportError,
    # 日志
    get_plugin_logger,
)

plugin.sdk.plugin 是受支持的开发者导入面。根包 plugin.sdk 有意只暴露保守的共享子集;不要假定插件专用 helper 都会从根包再次导出。

NekoPluginBase ​

所有插件必须继承 NekoPluginBase。

python
@neko_plugin
class MyPlugin(NekoPluginBase):
    def __init__(self, ctx):
        super().__init__(ctx)

属性 ​

属性类型说明
self.ctxPluginContext运行时上下文(由宿主注入)
self.plugin_idstr本插件的唯一标识符
self.plugin_dirPath包含代码、Manifest 和静态资源的插件安装目录
self.config_dirPathself.plugin_dir 的兼容别名
self.storage_dirPath分配给插件的用户存储根目录
self.runtime_config_pathPath外部运行配置文件路径
self.metadatadict目前在插件进程里恒为 {}(plugin.toml 的内容不会传进来)。读取配置用 await self.config.dump()
self.busSdkBusContext宿主状态的 read/watch 门面;没有 publish/emit API
self.pluginsPlugins跨插件调用辅助工具
self.system_infoSystemInfo宿主系统元数据

常用能力 ​

NekoPluginBase 无需额外设置即可提供日志和配置:

python
self.logger.info("Processing request: %s", request_id)
timeout = await self.config.get_int("my_settings.timeout", default=30)

回复完成后由插件决定配图 ​

await self.ctx.reply_tail.subscribe("after_reply") 可以订阅普通文字回复的完成通知。 after_reply 是插件自行声明的 @plugin_entry(id="after_reply", kind="hook") 入口, 收到 text、user_text、has_attachments 和 _ctx.host_reply。 订阅的入口必须是宿主为该插件登记过的入口,且入口 id 不以 _ 开头。符合条件的有:插件类上的 @plugin_entry 方法、列在 __routers__ 里的 router 的入口(router 类不要配 prefix;router 实例的入口 id 已含实例上设好的前缀)、plugin.toml 里指向插件类方法的 [[plugin.entries]] 条目、用 register_dynamic_entry() 添加的入口。只传给 include_router() 的 router,以及列在 __routers__ 里、又带 prefix 引入的 router 类,它们的入口不符合条件(见 PluginRouter)。宿主只把完成通知分派给符合条件的入口;subscribe 不检查这一点,订阅其他入口也会被接受(仍要通过常规的 id 和容量检查),但每次回调都返回 HTTP 404(detail.code="ENTRY_NOT_REGISTERED"),不调用插件。 插件可以按规则、检索或辅助模型自行决定是否配图,无需主聊天模型调用发图工具。 选好图片后,在入口返回前调用 self.ctx.reply_tail.register(...),由宿主排在原回复末尾。

这是显式订阅的后台通知,插件异常或超时不会阻塞正常聊天;被丢弃或打断的回复不触发。 仅覆盖支持 v1 尾图协议的普通文字聊天。取消订阅使用 await self.ctx.reply_tail.unsubscribe("after_reply");插件停止时也会清理。 完整示例、生命周期、容量、超时和投递边界见原回复尾图接口。

日志会显示在插件管理器中,并写入宿主管理的日志目录;日志文件位置和轮换策略由宿主负责。运行时配置通过 await self.ctx.update_own_config(...) 或 await self.config.update(...) 更新。调用后,应在同一进程中主动刷新依赖配置的派生状态。

根据数据形式选择存储方式:

需求API
少量键值状态启用 [plugin.store] 后使用 self.store
结构化 SQLite 数据启用 [plugin.database] 后使用 self.db
任意持久文件self.data_path(...)
可重新生成的文件self.cache_path(...)
给别的插件读的文件self.shared_path(...)
别的插件发布的文件在 [plugin.shared] 里声明后使用 self.shared_path_of("<plugin_id>", ...)
python
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()

需要翻译插件文本时,在 plugin.toml 中配置 [plugin.i18n]、添加各语言 JSON 文件,然后使用 self.i18n.t(...):

python
message = self.i18n.t("greeting", name="Alice")

self.i18n.t(...) 不跟随用户语言:不传 locale= 时,依次查插件的 default_locale、它的基础语言(例如 fr-CA 的 fr)、en,最后退回 default 参数或键名。宿主登记的面向用户的字符串(插件和入口名称、描述、schema 标签、UI 动作标签)请用 tr("key", default="..."),由宿主按每个用户的语言解析。

方法 ​

report_status(status: dict) -> None ​

向宿主进程报告插件状态。

python
self.report_status({
    "status": "processing",
    "progress": 50,
    "message": "Halfway done..."
})

push_message(**kwargs) -> PushMessageResult ​

使用 v2 schema 向宿主系统推送消息:visibility 决定是否在用户的聊天窗口或 HUD 中显示,ai_behavior 独立决定模型是否读取消息或作出回应,parts 承载文字、图片和 ui_action。

python
result = self.push_message(
    source="my_feature",
    visibility=["chat"],       # []、["chat"]、["hud"] 或二者
    ai_behavior="blind",       # "respond"、"read"、"blind"
    parts=[{"type": "text", "text": "任务已完成"}],
    priority=5,
)
if not result["submitted"]:
    self.logger.warning("push failed: %s", result.get("reason"))

返回值只表示本地提交结果(submitted / reason)。两条轴的完整语义、parts 类型、payload 与图片大小限制、ctx.images.upload() 以及 v1 字段迁移见消息推送与结果投递。

data_path(*parts) -> Path ​

获取插件 data/ 目录下的路径。

python
db_path = self.data_path("records.db")
# → <storage-root>/plugins/<plugin_id>/data/records.db

cache_path(*parts) -> Path ​

获取插件可清理缓存目录下的路径。

python
preview_path = self.cache_path("preview.png")
# → <storage-root>/plugins/<plugin_id>/cache/preview.png

shared_path(*parts) -> Path ​

获取本插件共享目录下的路径,这个目录里的文件是发布给别的插件读的。目录不会自动创建;插件被删除后目录会保留。目录以插件 id 命名;id 里小写字母、数字、_、- 以外的字符在目录名里会被转义,所以路径请始终从这个方法取。

python
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 ​

获取另一个插件共享目录下的路径,用来读取。那个插件的 id 必须写在 plugin.toml 的 [plugin.shared] reads 里,否则抛 ValidationError(code="shared_not_declared")。会跑出共享目录的路径同样会被拒绝(code="shared_bad_path")。

python
cities = self.shared_path_of("weather", "cities.json")
# → <storage-root>/plugin_shared/weather/cities.json

这是插件之间的约定,不是安全边界:插件之间没有沙箱。拿到的文件请只读不写。

register_dynamic_entry(entry_id, handler, ...) -> bool ​

在运行时注册入口点(非通过装饰器)。

python
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",
)

handler 必须是 async def 函数:注册时只检查是否可调用,但调用 handler 不是协程函数的入口会失败,报 Entry must be 'async def'。

unregister_dynamic_entry(entry_id) -> bool ​

移除一个动态注册的入口点。

list_entries(include_disabled=False) -> list[dict] ​

列出所有入口点(静态 + 动态)。

enable_entry(entry_id) / disable_entry(entry_id) -> bool ​

在运行时启用或禁用动态入口点。

register_static_ui(directory, *, index_file, cache_control) -> bool ​

为本插件注册一个静态 Web UI 目录。

python
self.register_static_ui("static")  # 提供 <plugin_dir>/static/index.html 服务

include_router(router, *, prefix) -> None ​

挂载一个 PluginRouter,用于组织大型或按功能拆分的普通 Plugin。

还要把每个 router 类列进插件类属性 __routers__:宿主的静态入口扫描只读这个列表(见 PluginRouter)。列进去的 router 类不要再配 prefix,否则列表里的 ID 调不通(见带前缀的 Router)。相关方法还有 exclude_router(router_or_name) -> bool、get_router(name) 和 list_routers()。Router 不能作为 manifest 的 [plugin].entry。on_mount / on_unmount 不会被宿主调用,不要覆盖它们。

Hosted/静态 UI 与列表操作 ​

Hosted TSX 使用导出的 ui namespace 和 manifest surface,详见 Hosted UI。旧式静态 UI 使用 register_static_ui(...)。列表行操作使用 set_list_actions(...)、register_list_action(...)、clear_list_actions() 和 get_list_actions() 管理。

LLM 工具方法 ​

register_llm_tool(...)、unregister_llm_tool(name) 和 list_llm_tools() 是 @llm_tool 的命令式对应接口。它们注册对话期工具,不是用户插件 Agent 入口。同步调用发出去就不管;await register_llm_tool_async(...) 和 await unregister_llm_tool_async(name) 返回 main_server 的真实答复(ok、各 role 的结果、error),并让插件本地登记与之保持一致。详见 LLM Tool Calling。

run_update(**kwargs) -> object(异步) ​

在长时间运行的操作期间向宿主发送更新。

export_push(**kwargs) -> object(异步) ​

向宿主推送导出数据。

finish(**kwargs) -> Any(异步) ​

向宿主发送任务完成信号。

回复控制 ​

finish() 通过 delivery 参数("proactive" 默认 / "passive" / "silent")控制插件结果是否进入主 AI 上下文、是否立即触发角色说话。reply=True/False 是已弃用的布尔别名。delivery 在 Agent 直达调用入口时生效。入口由 task agent 调用时,结果回给 task agent,怎么告诉用户按那件事自己的设置。

python
# 正常:角色会播报结果
return await self.finish(data={"summary": "完成"})

# 静默:结果会记录但角色不说话
return await self.finish(data={"summary": "完成"}, delivery="silent")

三种模式的区别、result_kind 结果语义,以及 {MASTER_NAME} / {LANLAN_NAME} 角色占位符见消息推送与结果投递。

LLM 结果字段过滤 ​

通过 @plugin_entry 装饰器(静态入口)或 register_dynamic_entry()(动态入口)的 llm_result_fields 参数,控制模型能看到结果中的哪些字段:直达调用时是主 LLM,由 task agent 调用时是那个 task agent。未列出的字段不会出现在提示中,但仍保留在 Run 的结果里。入口没有声明字段时模型看到什么,见入口与参数的「Agent 怎么调用入口」一节。

python
# 静态入口
@plugin_entry(llm_result_fields=["summary"])
async def search(self, query: str):
    return await self.finish(data={"summary": "找到3条结果", "raw_results": [...]})

# 动态入口
self.register_dynamic_entry(
    entry_id="my-tool",
    handler=handler,
    llm_result_fields=["summary"],
)

输出契约 ​

@plugin_entry 或 register_dynamic_entry() 的 output_schema 声明返回值的 JSON Schema。和入参对称:静态入口的返回注解是 Pydantic 模型时会自动推导,运行时由模型校验返回的数据(和 params 一样);显式写的 output_schema 字典(动态入口都是这种)只发布、不校验(和 input_schema 一样)。默认不符合时只在插件日志里告警(有限流);strict_output=True 时调用失败,错误码 PLUGIN_OUTPUT_SCHEMA_VIOLATION。日志和错误里只有字段路径和错误类型。详见入口与参数的「输出契约」一节。

python
self.register_dynamic_entry(
    entry_id="my-tool-described",
    handler=handler,
    output_schema={"type": "object", "required": ["summary"]},  # 只发布,不校验
)

Result 类型:Ok / Err ​

SDK 使用受 Rust 启发的 Result 类型进行错误处理,而非异常。

python
from plugin.sdk.plugin import Ok, Err, unwrap, unwrap_or

# 返回成功
return Ok({"data": result})

# 返回错误
return Err(SdkError("something went wrong"))

# 使用结果
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}")

# 辅助函数
value = unwrap(result)           # 如果是 Err 则抛出异常
value = unwrap_or(result, None)  # 如果是 Err 则返回默认值

Plugins(跨插件调用) ​

通过 self.plugins 访问。

python
# 列出所有插件
result = await self.plugins.list()

# 仅列出已启用的插件
result = await self.plugins.list(enabled=True)

# 获取插件 ID 列表
result = await self.plugins.list_ids()

# 检查插件是否存在
result = await self.plugins.exists("other_plugin")

# 调用另一个插件的入口点
result = await self.plugins.call_entry("other_plugin:do_work", {"key": "value"})

# 调用并确保返回 JSON 对象
result = await self.plugins.call_entry_json("other_plugin:get_data")

# 要求某个插件存在且已启用
result = await self.plugins.require_enabled("dependency_plugin")

所有方法返回 Result 类型 — 在使用 .value 之前,请先用 isinstance(result, Ok) 检查。

谁调了你:ctx.call_chain ​

self.ctx.call_chain 是当前这次调用「从哪来」的只读视图。它由宿主按自己的记录生成;插件只能读,改了也不影响宿主。

python
chain = self.ctx.call_chain
chain.callers        # 一路调到这里的插件 id,根在前;宿主直接调你时是 ()
chain.origin.kind    # "run"、"chat_tool"、"chat_hook"、"ui_action"、"plugin_self" 或 "system"
chain.origin.ref     # run id 这类编号,不含消息原文
chain.hops           # 每一步 (plugin_id, event_type, event_id)
chain.rights         # 链上每个插件都被用户确认过的权限
chain.rights_known   # 宿主没给出时为 False(见下)
chain.allows("plugin_sdk.main_agent.memory:read")
  • 永远不是 None。不在调用里(定时器、入口返回后还在跑的后台任务)时,它是只含你自己的链,rights_known=False。
  • rights 里是权限 id,例如 plugin_sdk.main_agent.memory:read。在一个版本内它同时带着旧名字(memory.read、conversations.read、messages.push),allows() 两种写法都接受。
  • allows() 只是参考。权限未知时它一律回答 False,所以「没有」和「不知道」读出来都是 False,要区分就看 rights_known。每次使用由宿主自己判定:这里是 False 不代表宿主一定拒绝,是 True 也只是投递那一刻的快照。
  • 交给裸 threading.Thread、自建线程池,或交给带自建 executor 的 loop.run_in_executor 的工作会丢掉调用上下文,宿主会把这些请求当成插件自发的。asyncio.to_thread 会保留;自己开线程时,用 contextvars.copy_context().run(...) 包住要做的事。
  • loop.run_in_executor(None, ...) 也会保留,但只限插件运行时执行你代码的那个事件循环:运行时把它的默认 executor 换成了会复制上下文的版本。在自己新建的事件循环上,或者换掉默认 executor 之后,就会丢掉上下文。neko-plugin check 分辨不出 run_in_executor(None, ...) 跑在哪个事件循环上,所以不把这个调用列为盲区,改为列出 asyncio.new_event_loop、asyncio.Runner 和 set_default_executor。其他自己弄出事件循环的写法(比如在你的代码里调用 asyncio.run)不会列出。
  • 它和旧的 plugin.sdk.shared.runtime.call_chain(只在一个插件进程内部记调用)是两回事。

宿主会记录插件互调和能力使用,用于审计(只记编号和能力名,不记参数、返回值和消息原文)。设计见 docs/design/plugin-call-chain.md。


PluginStore(持久化存储) ​

通过 self.store 访问(由宿主在插件构造时预先创建并注入,无需自己实例化)。plugin.toml 里没有 [plugin.store] 且 enabled = true 时它是关闭的:关闭时 set() 不保存任何内容,get() 返回默认值。

PluginStore 的所有方法都返回 Result,需用 unwrap_or(...) 解包。

python
unwrap_or(await self.store.set("key", {"count": 42}), None)
value = unwrap_or(await self.store.get("key"), None)  # → {"count": 42}

SystemInfo ​

通过 self.system_info 访问。这些方法都返回 Result,需用 unwrap_or(...) 解包。

python
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) ​

ctx 对象在构造时由宿主注入。

属性类型说明
ctx.plugin_idstr插件标识符
ctx.config_pathPathplugin.toml 的路径
ctx.loggerLogger日志记录器实例
ctx.busSdkBusContext宿主状态的 read/watch 门面
ctx.metadatadict传给 __init__ 的原始 ctx 没有 metadata 属性(读取会抛 AttributeError);包装后的 self.ctx.metadata 返回 {}。读取配置用 await self.config.dump()

Bus 与 Memory ​

在异步入口中,先 await get(),再使用本地列表操作:

python
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)

列表接口为 filter / where、sort、limit、watch。可调用形式 filter(predicate)、where(predicate) 和 sort(key=...) 仅处理本地快照;可重放的 watcher 链必须使用结构化 filter(field=value, ...) 与 sort(by=...)。只有 messages、events、lifecycle 支持 watch();conversations、memory 与 frames 是只读快照。watcher 仅接受 add、del、change。

【访问范围】这几个 store 是共享的,读取不按插件做权限隔离:任何已启用的插件都能读 conversations 和 frames,包括来自用户、以及来自别的插件的轮次与画面。这不会扩大宿主已经发给模型的内容——会话没发过的帧不会出现在这里——但确实扩大了谁能看到:从模型服务方扩大到用户启用的每一个插件。安装一个插件就等于授予它这份可见性;你的插件如果读这两条总线,请在自己的说明里写明。

bus.memory 保存的是有容量上限、只驻留内存的近期用户话语事件(TTL 为一小时),与角色持久化的事实、反思和人格相互独立。ctx.query_memory(...) 对角色的私聊记忆执行与内置 recall_memory 工具相同的混合召回,返回 {"result": text};text 是按角色提示词语言渲染、带编号并受 token 预算限制的命中列表,没有相关记忆时为空字符串。

Frames ​

bus.frames 保存宿主已经推送给模型提供方的最近几帧画面——就是提供方实际收到的那份字节。

python
frames = await self.bus.frames.get(max_count=4)
latest = frames.sort(by="timestamp", reverse=True).limit(1)

插件无法要求截图。被会话自身的节流或投递模式栅栏丢掉的那一帧压根没有发给提供方,因此也不会出现在这里。

它不是日志,也不是队列。 帧在四个位置被有意丢弃:message plane 的 PUB 套接字对慢订阅方和到达高水位时都会丢包;宿主侧的发布是非阻塞的;发送队列有上限,一旦落后就直接拒收新帧;store 本身只保留个位数(NEKO_MESSAGE_PLANE_FRAMES_STORE_MAXLEN,取值被夹在 2-8,默认 4)。轮询"每一帧",或者认为读到过一次的帧还在,都会出错。

每条记录带有 image_base64(只有一份,不存在可读的裸字节副本)、mime、source、captured_at、turn_id、generation、frame_id 和 metadata。source 是宿主给这一帧归的通道:screen、camera、plugin、callback、proactive、user,以及这一轮被重排后宿主已经说不准时的 unknown。screen 和 camera 只在语音路径上区分这两条实时通道;文字模式下用户分享的每一帧——共享的屏幕、相机截图、拖进来的照片——都走同一条不区分来源的队列,因此一律报作 user。想在两种模式下都拿到「用户给角色看的东西」,请按 user 过滤。请按 frame_id 去重:generation 只为常驻画面排序,一次性提示图不会让它前进,所以两条记录可能共用同一个值。

工具返回的图片也在这条总线上——前提是携带它们的那次后继请求已经得到应答。这类帧的 source 为 "plugin",metadata 为 {"tool_name": "..."}。工具最多可以返回 2 MiB base64;超过投递预算(500 KiB)的部分由宿主按模型画面的同一套 profile 重新编码(JPEG,最大 1280×720),使其落在 message plane 的记录上限之内,从而同时到达模型和这条总线。此时记录里的 mime 会是 image/jpeg(即便工具交回的是 PNG),工具结果里也会带一条模型可见的说明,告诉它这张图被重新编码过。压缩之后仍然放不下的图会被丢弃,并附带自己的告警。读像素之前先读 source:标为 plugin 的帧是某个插件交给模型的媒体(未必是你自己的),不是用户共享给角色的画面。

优先级等级 ​

范围等级使用场景
0-2低信息性消息
3-5中一般通知
6-8高重要通知
9-10紧急需要立即处理