Files
agent-safe-middleware/plugins/response_guard.lua
T
Автомата Калашникова 6d9ab4fbf8 guard: 修正本地守卫模型的输入形态(Qwen3Guard 直接收原文)
上一版把自定义指令塞进 prompt、并在 response_moderation 里丢了用户提问,与 Qwen3Guard-Gen 的实际用法不符:
- 输入:prompt 就是待审原文,不再加指令和 <BEGIN CONTENT> 包裹
- 输出:prompt=用户原问题(截断 2000 字节)、response=模型输出,恢复问答上下文
- 自定义指令改为可选的 prompt_prefix,默认不发送
宿主的 parse_guard_output 与九个类别名逐字对应 Qwen3Guard-Gen,已在注释和自检脚本里写明必须用该族模型。

验证:verify_plugins.py 104 项全通过;用假模型目录跑 load_settings + LLMRegistry,
确认 5 插件/1 启用、guard_model adapter 与两项能力正常建立;luac -p 通过。
2026-11-27 19:19:06 +08:00

960 lines
31 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- response_guard.lua —— OpenAI 兼容内容安全插件(Lua 插件接口 v1)
--
-- 判定走宿主本地守卫模型(host.llm.call),数据不出机器。
-- 宿主只接受 {task, prompt} 或 {task, prompt, response},多一个键即
-- InvalidModelRequest;返回 {safety, categories, refusal},safety 只有
-- Safe / Unsafe / Controversial,categories 必须命中宿主固定枚举。
-- 所以本地判定不能套 OpenAI 的 messages 结构,对外接口才是 OpenAI 格式。
--
-- 宿主对 {action="block"} 只返回它自己固定的 403 正文,插件改不了;所以请求侧判定
-- 不通过时不 block,而是把请求体换成 stub(原文不出网关),再在响应侧 replace 成
-- OpenAI 错误体:400 content_policy_violation / 503 safety_review_unavailable。
local plugin = {}
local config = {}
local requests = {}
local MAX_TAIL_BYTES = 512
local MAX_JUDGE_CHUNKS = 8
-- 分段字节上限要配合宿主的 max_input_tokens:英文约 4 字节/token,
-- 24576 字节约 6k token,加指令仍在 8192 以内。
local MAX_JUDGE_CHUNK_BYTES = 24576
local DEFAULT_STREAM_PATH = "choices.*.delta.content"
local DEFAULT_FULL_PATH = "choices.*.message.content"
-- Qwen3Guard-Gen 的输出就是 Safety / Categories / Refusal 三行,宿主 parse_guard_output
-- 按这个格式解析,类别必须落在它的枚举内,否则整条判定按 InvalidModelOutput 失败。
-- 该模型训练时直接收原文,不要再加自定义指令;prompt_prefix 只在确有需要时使用。
local MAX_INPUT_CONTEXT = 2000
local function key_for(ctx)
if type(ctx) == "table" and type(ctx.request_id) == "string" and ctx.request_id ~= "" then
return ctx.request_id
end
return nil
end
local function clear(key)
if key then requests[key] = nil end
end
local function shallow_copy(value)
local out = {}
for k, v in pairs(value or {}) do out[k] = v end
return out
end
local function is_continuation(byte)
return byte ~= nil and byte >= 0x80 and byte <= 0xBF
end
-- 按字节上限截断,回退到 UTF-8 字符边界
local function truncate_utf8(text, max_bytes)
if type(text) ~= "string" then return "" end
if #text <= max_bytes then return text end
local stop = max_bytes
while stop > 0 and is_continuation(string.byte(text, stop + 1)) do
stop = stop - 1
end
return string.sub(text, 1, stop)
end
-- 保留末尾 max_bytes 字节,起点对齐到 UTF-8 字符边界
local function utf8_tail(text, max_bytes)
if #text <= max_bytes then return text end
local start = #text - max_bytes + 1
while start <= #text and is_continuation(string.byte(text, start)) do
start = start + 1
end
return string.sub(text, start)
end
-- 按字节上限切分,切点回退到 UTF-8 字符边界
local function split_utf8(text, size)
local chunks = {}
local pos, length = 1, #text
while pos <= length do
local stop = pos + size - 1
if stop >= length then
chunks[#chunks + 1] = string.sub(text, pos)
break
end
while stop > pos and is_continuation(string.byte(text, stop + 1)) do
stop = stop - 1
end
chunks[#chunks + 1] = string.sub(text, pos, stop)
pos = stop + 1
end
return chunks
end
local function dense_length(value)
if type(value) ~= "table" then return nil end
local count, max_index = 0, 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index then return nil end
return count
end
local function parse_path(value)
if value == nil then return nil end
if type(value) == "string" then
local parts = {}
for part in string.gmatch(value, "[^%.]+") do
if part == "" then return nil end
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
if type(value) == "table" then
local parts, count = {}, 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
count = count + 1
end
for i = 1, count do
local part = value[i]
if type(part) ~= "string" or part == "" then return nil end
parts[i] = part
end
if count == 0 then return nil end
return parts
end
return nil
end
local function parse_paths(value, default_text)
if value == nil then value = default_text end
if type(value) == "string" then
local single = parse_path(value)
if not single then return nil end
return { single }
end
if type(value) ~= "table" then return nil end
local count = dense_length(value)
if not count or count == 0 then return nil end
local list = {}
for i = 1, count do
local single = parse_path(value[i])
if not single then return nil end
list[i] = single
end
return list
end
-- 字段缺失 = 本帧没文本(role/finish 帧);存在但不是字符串 = malformed,必须 fail-closed
local function collect_locations(root, parts)
local found = {}
local malformed = false
local function walk(node, depth)
local segment = parts[depth]
if segment == "*" then
local length = dense_length(node)
if not length or length == 0 then
malformed = true
return false
end
for i = 1, length do
local child = node[i]
if depth == #parts then
if child == host.json.null or child == nil then
-- 无文本
elseif type(child) ~= "string" then
malformed = true
return false
else
found[#found + 1] = { parent = node, key = i }
end
else
if type(child) ~= "table" then
malformed = true
return false
end
if not walk(child, depth + 1) then return false end
end
end
return true
end
if type(node) ~= "table" then
malformed = true
return false
end
local child = node[segment]
if depth == #parts then
if child == nil or child == host.json.null then
return true
end
if type(child) ~= "string" then
malformed = true
return false
end
found[#found + 1] = { parent = node, key = segment }
return true
end
if child == nil or child == host.json.null then return true end
if type(child) ~= "table" then
malformed = true
return false
end
return walk(child, depth + 1)
end
walk(root, 1)
return found, malformed
end
local function join_locations(locations)
if #locations == 0 then return "" end
local parts = {}
for i, location in ipairs(locations) do
parts[i] = location.parent[location.key]
end
return table.concat(parts)
end
-- 顺序必须稳定:放行时按同样的顺序把脱敏结果切回各字段
local function collect_all(root, path_list)
local locations = {}
local malformed = false
for _, parts in ipairs(path_list) do
local found, bad = collect_locations(root, parts)
if bad then malformed = true end
for _, location in ipairs(found) do
locations[#locations + 1] = location
end
end
return locations, malformed
end
local redact_text
-- 就地脱敏;脱敏不改变字节长度,失败即 fail-closed
local function redact_locations(locations)
if #locations == 0 then return false, nil end
local original = join_locations(locations)
if original == "" then return false, nil end
local masked = redact_text(original)
if #masked ~= #original then
return false, "redaction_length_changed"
end
if masked == original then return false, nil end
local offset = 1
for _, location in ipairs(locations) do
local length = #location.parent[location.key]
location.parent[location.key] = string.sub(masked, offset, offset + length - 1)
offset = offset + length
end
return true, nil
end
redact_text = function(text)
local out = text
-- Bearer 凭证与常见 API Key
out = out:gsub("([Bb]earer%s+)([%w%._~%+/%-]+=*)", function(prefix, token)
return prefix .. string.rep("*", #token)
end)
out = out:gsub("sk%-[%w_%-]+", function(token)
return "sk-" .. string.rep("*", #token - 3)
end)
out = out:gsub("AKIA[A-Z0-9]+", function(token)
if #token >= 12 then return "AKIA" .. string.rep("*", #token - 4) end
return token
end)
-- 邮箱:保留域名与首字符
out = out:gsub("[%w%._%+%-]+@[%w%-%.]+%.[%a]+", function(email)
local at = email:find("@", 1, true)
if not at then return email end
local local_part, domain = email:sub(1, at - 1), email:sub(at + 1)
if #local_part <= 1 then return "*@" .. domain end
return local_part:sub(1, 1) .. string.rep("*", #local_part - 1) .. "@" .. domain
end)
-- 18 位身份证
out = out:gsub("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]", function(id)
return id:sub(1, 6) .. "********" .. id:sub(-4)
end)
-- 银行卡号(16~19 位,允许空格/连字符分隔),保持分隔符与长度
out = out:gsub("%d[%d %-]*%d", function(number_run)
local digits = number_run:gsub("%D", "")
if #digits < 16 or #digits > 19 then return number_run end
local total, index = #digits, 0
return (number_run:gsub("%d", function(digit)
index = index + 1
if index <= 4 or index > total - 4 then return digit end
return "*"
end))
end)
-- 中国大陆手机号
out = out:gsub("1[3-9]%d%d%d%d%d%d%d%d%d", function(phone)
return phone:sub(1, 3) .. "****" .. phone:sub(-4)
end)
-- 10 位固话:保留分隔符,长度必须不变
out = out:gsub("(%d%d%d)([%s%.%-]?)(%d%d%d)([%s%.%-]?)(%d%d%d%d)",
function(a, sep1, b, sep2, c)
return a .. sep1 .. "***" .. sep2 .. c
end)
return out
end
local closers = {
['"'] = true, ["'"] = true, [')'] = true, [']'] = true, ['}'] = true,
}
local function skip_utf8_closer(s, i)
for _, token in ipairs({ "”", "’", ")", "】", "》", "」", "』", "〉", "〕" }) do
if s:sub(i, i + #token - 1) == token then
return i + #token
end
end
return nil
end
local abbreviations = {
["mr"] = true, ["mrs"] = true, ["ms"] = true, ["dr"] = true,
["prof"] = true, ["sr"] = true, ["jr"] = true, ["st"] = true,
["vs"] = true, ["etc"] = true, ["e.g"] = true, ["i.e"] = true,
["fig"] = true, ["no"] = true, ["approx"] = true,
}
local function is_abbreviation_dot(s, i)
local prefix_start = math.max(1, i - 64)
local prefix = s:sub(prefix_start, i - 1):lower()
local token = prefix:match("([%a%.]+)$")
if token and abbreviations[token] then return true end
local before = s:sub(i - 1, i - 1)
local after = s:sub(i + 1, i + 1)
if before:match("%d") and after:match("%d") then return true end
return false
end
local function has_sentence_boundary(s)
local i = 1
while i <= #s do
local ch = s:sub(i, i)
local punct_len = 1
local punct = (ch == "." or ch == "!" or ch == "?")
if not punct then
local utf = s:sub(i, i + 2)
if utf == "。" or utf == "!" or utf == "?" then
punct, punct_len = true, 3
end
end
if punct then
if ch == "." and is_abbreviation_dot(s, i) then
i = i + punct_len
else
local j = i + punct_len
while j <= #s do
local c = s:sub(j, j)
if closers[c] then
j = j + 1
else
local next_j = skip_utf8_closer(s, j)
if next_j then j = next_j else break end
end
end
if (punct_len == 3) or (j <= #s and s:sub(j, j):match("%s")) then
return true
end
i = i + punct_len
end
else
i = i + 1
end
end
return false
end
local function policy_denied(verdict, kind)
return {
status = config.block_status,
type = "invalid_request_error",
code = "content_policy_violation",
message = (kind == "output") and config.block_message_output or config.block_message_input,
category = (verdict and verdict.category) or "other",
}
end
local function policy_unavailable(reason)
return {
status = 503,
type = "server_error",
code = "safety_review_unavailable",
message = "The content safety review could not complete. Please retry.",
category = reason or "unavailable",
}
end
local function error_body(policy)
return host.json.encode({
error = {
message = policy.message,
type = policy.type,
param = host.json.null,
code = policy.code,
},
})
end
-- 非流式:整包替换成一个标准 OpenAI 错误响应
local function error_response(policy)
return {
status = policy.status,
headers = { ["content-type"] = "application/json; charset=utf-8" },
body = error_body(policy),
streaming = false,
}
end
-- 流式:单帧 data: {"error":{...}}
local function error_frame(policy)
return { has_data = true, data = error_body(policy) }
end
-- prompt_moderation 只有 prompt 一个字段承载内容,所以原文直接放进去;
-- response_moderation 用 prompt 放用户原问题、response 放模型输出——不能把正文
-- 塞进 prompt,也不能只发输出而丢掉提问上下文。
local function input_prompt(part, index, total)
if total <= 1 then return part end
return string.format("(part %d of %d)\n%s", index, total, part)
end
local function judge_call(kind, part, index, total, user_text)
local request
if kind == "output" then
local context = user_text
if type(context) ~= "string" or context == "" then
context = "Evaluate the safety of the assistant reply."
end
if config.prompt_prefix then
context = config.prompt_prefix .. "\n\n" .. context
end
request = { task = "response_moderation", prompt = context, response = part }
else
local text = input_prompt(part, index, total)
if config.prompt_prefix then
text = config.prompt_prefix .. "\n\n" .. text
end
request = { task = "prompt_moderation", prompt = text }
end
local ok, result = pcall(host.llm.call, config.model, request)
if not ok or type(result) ~= "table" then return nil, "judge_call_failed" end
local safety = result.safety
if safety == "Safe" then return { allow = true } end
if safety == "Controversial" and not config.block_controversial then
return { allow = true }
end
if safety == "Unsafe" or safety == "Controversial" then
local categories = type(result.categories) == "table" and result.categories or {}
local first = categories[1]
return { allow = false, category = type(first) == "string" and first or "other" }
end
-- safety 落在枚举外说明模型输出不可信,按 fail-closed 处理
return nil, "judge_invalid_safety"
end
local function judge(kind, user_text, model_text)
local target = model_text or user_text or ""
if target == "" then return { allow = true } end
local chunks = split_utf8(target, config.judge_chunk_bytes)
if #chunks == 0 then return { allow = true } end
if #chunks > MAX_JUDGE_CHUNKS then return nil, "judge_input_too_large" end
for index = 1, #chunks do
local verdict, err = judge_call(kind, chunks[index], index, #chunks, user_text)
if not verdict then return nil, err end
if verdict.allow ~= true then return verdict end
end
return { allow = true }
end
-- chat 的 {type="text"} 和 Responses 的 {type="input_text"} 都要认,否则换个写法就能绕过审核
local function message_text(content)
if type(content) == "string" then return content end
if type(content) ~= "table" then return nil end
local parts = {}
for _, part in ipairs(content) do
if type(part) == "table" and type(part.text) == "string"
and (part.type == "text" or part.type == "input_text") then
parts[#parts + 1] = part.text
end
end
if #parts == 0 then return nil end
return table.concat(parts, "\n")
end
local function collect_user_text(decoded)
local texts = {}
local messages = decoded.messages
if type(messages) == "table" then
local count = dense_length(messages)
if not count then return nil end
for i = 1, count do
local message = messages[i]
if type(message) == "table" and message.role == "user" then
local text = message_text(message.content)
if text and text ~= "" then texts[#texts + 1] = text end
end
end
elseif type(decoded.prompt) == "string" and decoded.prompt ~= "" then
texts[1] = decoded.prompt
else
return nil
end
if #texts == 0 then return nil end
return table.concat(texts, "\n\n---\n\n")
end
-- 拦截后发往上游的占位请求:只带 OpenAI 规范字段,否则上游会先用自己的 400 拒掉它
local function encode_stub(state)
local body = {
messages = { { role = "user", content = "ping" } },
stream = state.stream == true,
}
local model = state.model
if model == nil or model == "" then model = config.stub_model end
if type(model) == "string" and model ~= "" then body.model = model end
if config.stub_max_tokens then
body.max_tokens = config.stub_max_tokens
end
return host.json.encode(body)
end
local function should_flush(state)
if state.text_bytes < config.flush_chars then return false end
if has_sentence_boundary(state.tail) then return true end
return state.text_bytes >= config.force_flush_bytes
end
-- 审核 + 脱敏 + 按原顺序还原事件;失败返回 nil, policy
local function release(state)
local pending = state.pending
if #pending == 0 then return host.json.array(), nil end
local text = table.concat(state.texts)
local masked = text
if text ~= "" then
if config.check_output then
local verdict, err = judge("output", state.input_text, text)
if not verdict then return nil, policy_unavailable(err) end
if verdict.allow ~= true then return nil, policy_denied(verdict, "output") end
end
local ok_redact, redacted = pcall(redact_text, text)
if not ok_redact or type(redacted) ~= "string" or #redacted ~= #text then
return nil, policy_unavailable("redaction_failed")
end
masked = redacted
end
local events = {}
local offset = 1
for _, entry in ipairs(pending) do
if #entry.lengths == 0 then
events[#events + 1] = entry.event
else
local ok_decode, decoded = pcall(host.json.decode, entry.event.data)
if not ok_decode or type(decoded) ~= "table" then
return nil, policy_unavailable("release_decode_failed")
end
local locations, malformed = collect_all(decoded, config.content_paths_stream)
if malformed or #locations ~= #entry.lengths then
return nil, policy_unavailable("release_shape_changed")
end
for i, location in ipairs(locations) do
local length = entry.lengths[i]
local replacement = ""
if length > 0 then
replacement = string.sub(masked, offset, offset + length - 1)
end
offset = offset + length
location.parent[location.key] = replacement
end
local ok_encode, encoded = pcall(host.json.encode, decoded)
if not ok_encode or type(encoded) ~= "string" then
return nil, policy_unavailable("release_encode_failed")
end
local copy = shallow_copy(entry.event)
copy.data = encoded
events[#events + 1] = copy
end
end
state.pending = {}
state.texts = {}
state.text_bytes = 0
state.tail = ""
return host.json.array(events), nil
end
local function positive_int(value, default, label)
if value == nil then return default end
local number = tonumber(value)
if not number or number < 1 or number % 1 ~= 0 then
error("response_guard: config." .. label .. " must be a positive integer")
end
return number
end
local function boolean(value, default)
if value == nil then return default end
if value == true or value == false then return value end
error("response_guard: boolean config value must be true or false")
end
-- 模型由宿主的 llm 段加载;这里只写 id,插件必须在 config.yaml 里用
-- llm.allow 声明同一个 id,否则 host.llm.call 必然失败。
function plugin.init(ctx, options)
if type(options) ~= "table" then
error("response_guard config must be a table")
end
local o = options
if type(o.model) ~= "string" or o.model == "" then
error("response_guard requires config.model (id of a host llm entry)")
end
local prompt_prefix = o.prompt_prefix
if prompt_prefix ~= nil and (type(prompt_prefix) ~= "string" or prompt_prefix == "") then
error("response_guard: config.prompt_prefix must be a non-empty string or absent")
end
-- 单个路径字符串或多路径数组都接受;多路径用于同时覆盖正文与工具调用参数
local stream_paths = parse_paths(o.content_path_stream, DEFAULT_STREAM_PATH)
if not stream_paths then
error("response_guard: invalid config.content_path_stream")
end
local full_paths = parse_paths(o.content_path_full, DEFAULT_FULL_PATH)
if not full_paths then
error("response_guard: invalid config.content_path_full")
end
local block_status = positive_int(o.block_status, 400, "block_status")
if block_status < 400 or block_status > 599 then
error("response_guard: config.block_status must be within 400..599")
end
local judge_chunk_bytes = positive_int(o.judge_chunk_bytes, 8192, "judge_chunk_bytes")
if judge_chunk_bytes > MAX_JUDGE_CHUNK_BYTES then
error("response_guard: config.judge_chunk_bytes must not exceed " .. MAX_JUDGE_CHUNK_BYTES)
end
local stream_mode = o.stream_mode or "incremental"
if stream_mode ~= "incremental" and stream_mode ~= "buffered" then
error("response_guard: config.stream_mode must be 'incremental' or 'buffered'")
end
-- 占位请求兜底模型:客户端请求里没有 model 时用(规范要求 model 必填)
local stub_model = o.stub_model
if stub_model ~= nil and (type(stub_model) ~= "string" or stub_model == "") then
error("response_guard: config.stub_model must be a non-empty string or absent")
end
-- 占位请求生成长度上限:默认 16;false 表示不发(上游只认 max_completion_tokens 时用)
local stub_max_tokens
if o.stub_max_tokens == false then
stub_max_tokens = nil
else
stub_max_tokens = positive_int(o.stub_max_tokens, 16, "stub_max_tokens")
end
config = {
model = o.model,
prompt_prefix = prompt_prefix,
stub_model = stub_model,
stub_max_tokens = stub_max_tokens,
judge_chunk_bytes = judge_chunk_bytes,
content_paths_stream = stream_paths,
content_paths_full = full_paths,
block_status = block_status,
block_message_input = type(o.block_message_input) == "string" and o.block_message_input
or "Your request was rejected by the content safety policy.",
block_message_output = type(o.block_message_output) == "string" and o.block_message_output
or "The model response was withheld by the content safety policy.",
flush_chars = positive_int(o.flush_chars, 512, "flush_chars"),
force_flush_bytes = positive_int(o.force_flush_bytes, 4096, "force_flush_bytes"),
max_buffer_bytes = positive_int(o.max_buffer_bytes, 131072, "max_buffer_bytes"),
stream_mode = stream_mode,
check_input = boolean(o.check_input, true),
check_output = boolean(o.check_output, true),
block_controversial = boolean(o.block_controversial, true),
}
-- 不重置 requests:host 可能在请求初始化阶段调用 init
return nil
end
function plugin.on_request(ctx, request)
local key = key_for(ctx)
if not key then
-- 没有 request_id 就无法保存判定结果,只能 fail-closed
return { action = "block", reason = "missing request_id" }
end
local state = {
input_text = "",
verdict = "allow",
policy = nil,
stream = false,
model = nil,
pending = {},
texts = {},
text_bytes = 0,
tail = "",
terminal = false,
opaque = false,
}
requests[key] = state
if type(request) ~= "table" or type(request.body) ~= "string" then
state.opaque = true
return { action = "pass" }
end
local ok_decode, decoded = pcall(host.json.decode, request.body)
if not ok_decode or type(decoded) ~= "table" then
-- 非法 JSON 交给上游按 OpenAI 规范自己拒绝,这里不额外加工
state.opaque = true
return { action = "pass" }
end
if type(decoded.model) == "string" then state.model = decoded.model end
state.stream = decoded.stream == true
if not config.check_input then return { action = "pass" } end
local input_text = collect_user_text(decoded)
if input_text == nil then return { action = "pass" } end
local verdict, err = judge("input", input_text)
if not verdict then
state.verdict = "error"
state.policy = policy_unavailable(err)
elseif verdict.allow ~= true then
state.verdict = "deny"
state.policy = policy_denied(verdict, "input")
end
-- 输出判定要带上用户原问题:Qwen3Guard 的 response_moderation 用 user 轮做上下文
state.input_text = truncate_utf8(input_text, MAX_INPUT_CONTEXT)
if state.verdict == "allow" then return { action = "pass" } end
local replacement = shallow_copy(request)
replacement.body = encode_stub(state)
return { action = "replace", value = replacement }
end
function plugin.on_response(ctx, response)
if type(response) ~= "table" then
return { action = "block", reason = "invalid response" }
end
-- SSE 响应只在 on_event 处理,body 是 JSON null,不能整体替换
if response.streaming == true then return nil end
local key = key_for(ctx)
if not key then return { action = "block", reason = "missing request_id" } end
local state = requests[key]
if not state then return { action = "block", reason = "request state missing" } end
if state.verdict ~= "allow" then
clear(key)
return { action = "replace", value = error_response(state.policy) }
end
if state.opaque then
clear(key)
return { action = "pass" }
end
if response.status ~= 200 then
-- 上游自己返回的 OpenAI 错误,原样透传
clear(key)
return { action = "pass" }
end
if type(response.body) ~= "string" then
clear(key)
return { action = "replace", value = error_response(policy_unavailable("invalid_response_body")) }
end
local ok_decode, decoded = pcall(host.json.decode, response.body)
if not ok_decode or type(decoded) ~= "table" then
clear(key)
return { action = "replace", value = error_response(policy_unavailable("response_not_json")) }
end
local locations, malformed = collect_all(decoded, config.content_paths_full)
if malformed then
clear(key)
return { action = "replace", value = error_response(policy_unavailable("unexpected_response_shape")) }
end
local text = join_locations(locations)
if text ~= "" and config.check_output then
local verdict, err = judge("output", state.input_text, text)
if not verdict then
clear(key)
return { action = "replace", value = error_response(policy_unavailable(err)) }
end
if verdict.allow ~= true then
local policy = policy_denied(verdict, "output")
clear(key)
return { action = "replace", value = error_response(policy) }
end
end
local changed, redact_err = redact_locations(locations)
clear(key)
if redact_err then
return { action = "replace", value = error_response(policy_unavailable(redact_err)) }
end
if not changed then return { action = "pass" } end
local ok_encode, encoded = pcall(host.json.encode, decoded)
if not ok_encode or type(encoded) ~= "string" then
return { action = "replace", value = error_response(policy_unavailable("response_encode_failed")) }
end
local replacement = shallow_copy(response)
replacement.body = encoded
return { action = "replace", value = replacement }
end
function plugin.on_event(ctx, event)
if type(event) ~= "table" then
return { action = "block", reason = "invalid event" }
end
local key = key_for(ctx)
if not key then return { action = "block", reason = "missing request_id" } end
local state = requests[key]
if not state then return { action = "block", reason = "request state missing" } end
-- 已经给出错误帧:后续一切事件全部吞掉,连接由宿主正常关闭
if state.terminal then
return { action = "replace", events = host.json.array() }
end
-- 请求侧已判定不通过或审核不可用:第一帧就换成 OpenAI 错误
if state.verdict ~= "allow" then
state.terminal = true
return { action = "replace", events = host.json.array({ error_frame(state.policy) }) }
end
local entry = { event = event, lengths = {} }
local added = 0
if event.has_data ~= false and type(event.data) == "string" and event.data ~= "" then
if event.data == "[DONE]" then
-- 终止帧本身没有正文,随缓冲内容一起按序放行
state.pending[#state.pending + 1] = entry
local events, policy = release(state)
if not events then
state.terminal = true
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
end
return { action = "replace", events = events }
end
local ok_decode, decoded = pcall(host.json.decode, event.data)
if not ok_decode or type(decoded) ~= "table" then
state.terminal = true
return { action = "replace", events = host.json.array({
error_frame(policy_unavailable("invalid_stream_frame")),
}) }
end
local locations, malformed = collect_all(decoded, config.content_paths_stream)
if malformed then
state.terminal = true
return { action = "replace", events = host.json.array({
error_frame(policy_unavailable("unexpected_stream_shape")),
}) }
end
for i, location in ipairs(locations) do
local text = location.parent[location.key]
entry.lengths[i] = #text
state.texts[#state.texts + 1] = text
added = added + #text
-- 增量维护句边界扫描窗口(只保留尾部,避免持有整段文本副本)
state.tail = utf8_tail(state.tail .. text, MAX_TAIL_BYTES)
end
end
state.pending[#state.pending + 1] = entry
state.text_bytes = state.text_bytes + added
if state.text_bytes > config.max_buffer_bytes then
state.terminal = true
return { action = "replace", events = host.json.array({
error_frame({
status = 413,
type = "invalid_request_error",
code = "response_too_large",
message = "The model response exceeded the safety review buffer limit.",
}),
}) }
end
if config.stream_mode == "incremental" and added > 0 and should_flush(state) then
local events, policy = release(state)
if not events then
state.terminal = true
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
end
return { action = "replace", events = events }
end
return { action = "hold" }
end
function plugin.on_end(ctx)
local key = key_for(ctx)
if not key then return { action = "block", reason = "missing request_id" } end
local state = requests[key]
if not state then return nil end
if state.terminal then
clear(key)
return nil
end
if #state.pending == 0 then
clear(key)
return nil
end
local events, policy = release(state)
clear(key)
if not events then
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
end
return { action = "replace", events = events }
end
function plugin.close(ctx)
local key = key_for(ctx)
if key then clear(key) end
return nil
end
return plugin