Files
agent-safe-middleware/docs/plugins.md
T
starrrLight d1f5f69454 fix(运行时): 将插件路径匹配移到宿主
新增宿主侧精确路径匹配和插件级 match.paths 配置。\n按请求路径固定插件会话链,移除 Lua 插件内的路径判断与 bypass 状态,并迁移现有插件配置和测试。
2026-10-15 15:49:05 +08:00

8.4 KiB
Raw Blame History

Lua 插件开发接口 v1

插件文件返回一个 Lua table,已知钩子若存在必须是函数。未知元数据字段可以保留。init 不返回决定,缺省钩子或返回 nil 表示继续;on_end 返回 nil 表示没有待释放事件。

local plugin = {}
local settings = {}
function plugin.init(ctx, config) settings = config end
function plugin.on_request(ctx, request)
    local data = host.json.decode(request.body)
    if data.message == 'blocked' then return {action='block'} end
    return {action='pass'}
end
return plugin

ctx 包含中间层生成的 request_id 和当前 plugin_id。它不是用户身份或授权证据。每次钩子获得数据副本,需通过返回值传递修改。插件用模块局部变量保存本请求状态;不同插件、不同请求均不共享全局变量。

路径匹配

插件是否参与一次请求由宿主根据插件级 match.paths 决定,Lua 插件不再读取或维护路径白名单和 bypass 状态。一次请求创建会话时完成匹配,后续的 on_request、on_response、on_event、on_end 和 close 始终使用同一组插件。

plugins:
  - id: request-rewrite
    file: plugins/request_rewrite.lua
    match:
      paths: [/chat/stream]
    config:
      prefix: "[checked] "

match.paths 是精确路径列表,区分大小写和尾斜杠,不支持前缀、通配符、查询参数或正则。省略 match 表示匹配所有路径。旧的 config.paths 已移除,启动时会报错并要求迁移到 match.paths。

钩子数据

钩子 第二参数 可以返回的动作
init(ctx, config) 此插件的 YAML config 对象 必须返回 nil
on_request(ctx, request) {method, path, headers, body} pass、replace、block
on_response(ctx, response) {status, headers, body, streaming} pass、replace、block
on_event(ctx, event) {event?, id?, data, has_data, comments, retry?} pass、replace、hold、block
on_end(ctx) 无业务参数 pass、replace、block
close(ctx) 无业务参数 返回值忽略

请求/非流式正文是 UTF-8 字符串;method、path 不可改变。请求头和正文允许修改。SSE 响应的 body 是 JSON null,不能替换或切换 streaming 模式,应使用 on_event。状态码必须为 200–599。

SSE data 是原始文本,不是宿主解码的 JSON。has_data=false 表示无 data 行,例如心跳注释。多行 data 合并为 \n;comments 是注释字符串数组。宿主会规范化 SSE 的行分隔及空格,保持协议语义,不承诺字节一致。缺少完整结束空行、非法 UTF-8 或超大帧会导致流失败。修改 event、id 时不能包含换行或 NUL。

-- 原样继续;修改了参数但返回 pass,不会保留修改
return {action='pass'}

-- 请求/响应替换,返回完整对象
return {action='replace', value=request}

-- SSE 替换,可以产生一个或多个事件
return {action='replace', events={event1, event2}}

-- 不输出任何事件;空数组须明确标记
return {action='replace', events=host.json.array()}

-- 暂存由插件自行维护,宿主本次不发出事件
return {action='hold'}

-- 立即阻断;reason 可作为插件内部说明,但不记录、不回显
return {action='block', reason='internal explanation'}

替换事件按数组顺序进入后续插件。on_end 释放的事件也经过后续插件的 on_event;前一个插件释放完成后才调用后一个插件的 on_end。内置 Lua 协议适配器最后处理事件,暂存 run_completed,在所有业务结束钩子通过后放行。

非流式响应也调用 on_end;此时不能释放 SSE 事件。执行性输出若需要审核,应在请求或完整响应钩子中完成。本层看到的工具生命周期事件不能阻止已经发生的 Agent 内部工具调用。

JSON 数据桥

host.json.decode(text)、host.json.encode(value) 保留对象、数组、布尔、数字和 null。JSON null 用 host.json.null 表示;不与 Lua nil 混淆。

解码所得空数组保留数组类型,新建空数组请用 host.json.array() 或 host.json.array(table)。新建空 {} 默认编码为对象;连续的正整数键表编码为数组。禁止稀疏数组、循环引用、非字符串对象键、函数、Python userdata 和非有限数字;嵌套深度最多 64。

网络与日志

local result = host.http.request({
    url='https://review.example.com/check',
    method='POST',
    headers={['content-type']='application/json'},
    body=host.json.encode({text='待审核内容'}),
})
-- result: {status=200, headers={...}, body='UTF-8 response text'}

仅接受 url、method、headers、body。method 支持 GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS,默认 GET;body 默认空字符串。HTTP body 为 UTF-8 文本,第一版不提供二进制、文件上传或原始 socket。

请求在 Lua 中表现为同步调用,实际由宿主的异步网络代理执行,不阻塞主事件循环。网络错误抛出可被 pcall 捕获的异常;未捕获时插件失败并阻断。插件不得改变白名单、TLS 校验、代理、重定向或超时设置。3xx 直接返回,若自行跟随 Location,新地址也必须满足白名单。宿主不提供凭据,插件若需 API Key,应由管理员在此插件配置中注入,不能放进日志。

host.log.info(...)、warning(...)、error(...) 只生成固定的插件日志标记,不保存文本参数。每钩子最多 64 次宿主调用,限制可配置;日志和 HTTP 都计数。

模块加载及所有钩子都有超时与内存限制;配置修改后重启生效,不提供热加载或长期跨请求状态。业务规则应有正常对照测试,避免关键词规则把合法的安全研究或引用内容误判为攻击。

Python LLM capability

The optional guard dependency (pip install -e ".[guard]") enables local Transformers guard models. Model definitions live at the top level and plugins explicitly allow model IDs:

模型的 llm[].file 指向包含权重、config.json 和分词器文件的目录。相对路径以进程当前工作目录为基准:从 /service 启动时,models/guard_model 解析为 /service/models/guard_model,与 --config 文件所在位置无关;绝对路径直接使用。Docker 镜像设置了 WORKDIR /service,模型文件需挂载到对应的容器目录。原来依赖配置文件目录的模型相对路径需要按工作目录调整,或改用绝对路径。插件的 plugins[].file 仍相对于配置文件目录解析。

llm:
  - id: Qwen3Guard-Gen-0.6B
    type: guard
    backend: transformers
    file: /models/Qwen3Guard-Gen-0.6B
    enabled: true
    load:
      device: cpu
      dtype: bfloat16
      revision: "fixed-model-revision"
    limits:
      max_input_tokens: 4096
      max_new_tokens: 32
      timeout_seconds: 3
      queue_size: 8
plugins:
  - id: response-guard
    file: plugins/response_guard.lua
    llm:
      allow: [Qwen3Guard-Gen-0.6B]
    config:
      model: Qwen3Guard-Gen-0.6B

A Lua plugin receives only the authorized model metadata:

for _, model in ipairs(host.llm.list()) do
    -- model.id, model.type, model.capabilities
end
local result = host.llm("Qwen3Guard-Gen-0.6B", {
    task = "response_moderation",
    prompt = prompt,
    response = text,
})
-- result = {safety="Safe|Controversial|Unsafe", categories={}, refusal="Yes|No|nil"}

host.llm.call(id, request) is equivalent to the callable form. Calls are synchronous from Lua, serialized per model, and executed in a separate Python process. The worker is started before /readyz becomes ready. Model failures are returned as capability failures; plugins should fail closed (the example response_guard.lua blocks on a failed moderation call). The model worker is local-only and does not download weights at request time.

模型启动失败时,服务日志输出 model_load_failed model=... stage=... exception=... dependency=...。stage 区分 import_torch、import_transformers、load_tokenizer、load_model、move_to_device 和 eval_model;exception 是允许记录的异常类型,dependency 标记已知的缺失依赖,其余值为 unknown。诊断不输出原始异常文本或模型文件内容,模型加载失败仍会阻止服务就绪。例如 stage=import_torch exception=ModuleNotFoundError dependency=torch 表示缺少 PyTorch,需要在构建实际运行的镜像时安装 .[guard]。