插件改造:输出改为 OpenAI 协议,审核改走远程接口

response_guard.lua 重写:按 OpenAI 协议定位内容(choices[*].delta.content / message.content,支持多路径覆盖 tool_calls.arguments),判定改走远程 /chat/completions,拦截输出 400 content_policy_violation,审核不可用输出 503 safety_review_unavailable。

stream_redact.lua 改为 OpenAI SSE 全缓冲 PII 兜底,默认关闭;request_rewrite.lua 改为只重写最后一条 user 消息,默认关闭。

config.yaml 接口路径改为 /v1/chat/completions,停用缺模型文件的 guard_model 段与依赖 host.files 的 /upload 插件段,hook_timeout 调到 45s。

新增 tools/verify_plugins.py:13 个场景 57 项断言的契约校验。
This commit is contained in:
Автомата Калашникова committed 2026-11-27 17:25:18 +08:00
1 parent e1f944f16d
commit 9218bdf1e8
6 files changed
+1967 -1288

No files matched your search

+260 -584
View File
@@ -1,591 +1,277 @@
-- Full-buffer SSE redaction example.
-- ============================================================================
-- stream_redact.lua —— OpenAI SSE 全缓冲 PII 脱敏(Lua 插件接口 v1)
--
-- Scope: SSE only. Non-streaming responses are explicitly blocked by on_response
-- so they cannot silently bypass this streaming-only redaction rule.
-- All configured text events are held until normal end so sensitive values split
-- across frames/array blocks can be detected. The administrator MUST configure
-- terminal_error_events and control_event_names from the real Agent protocol;
-- no guessed event-name list is silently treated as authoritative.
-- Terminal errors discard held body text. Their own data is scrubbed for the
-- supported deterministic patterns before being sent to the client.
-- 定位
-- response_guard 已经做「语义审核 + 脱敏」,本插件是第二道确定性兜底:
-- 把整条流缓冲到结束,再统一脱敏后一次性放行,因此能命中跨帧拆分的
-- 身份证号/手机号/卡号。代价是客户端拿不到增量输出,默认 enabled: false。
--
-- The local buffer limit counts a conservative estimated footprint, not merely
-- raw text bytes: event.data is weighted 3x and each frame has a fixed overhead.
-- The host's max_plugin_buffer_bytes and Lua memory limits remain authoritative.
-- This deterministic example is not a complete DLP implementation.
-- OpenAI 协议
-- 只处理 SSE(POST /v1/chat/completions,stream=true):
-- 正文路径 : choices[*].delta.content
-- 终止帧 : data: [DONE]
-- 非流式响应不归本插件管(response_guard 已覆盖),直接放行。
--
-- 拦截输出(与 response_guard 保持一致的 OpenAI 形态)
-- data: {"error":{"message":...,"type":"server_error",
-- "param":null,"code":"safety_review_unavailable"}}
-- ============================================================================
local plugin = {}
local config = {}
local states = {}
local DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
local HARD_MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_TEXT_EVENT = "text_delta"
local DEFAULT_CONTENT_PATH = { "data", "content" }
local settings = nil
local MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_PATH = "choices.*.delta.content"
local function request_key(ctx)
if type(ctx) ~= "table" then return nil end
local key = ctx.request_id
if type(key) ~= "string" or key == "" then return nil end
return key
if type(ctx) ~= "table" then return nil end
local key = ctx.request_id
if type(key) ~= "string" or key == "" then return nil end
return key
end
local function contains_cr_lf_nul(value)
for i = 1, #value do
local b = string.byte(value, i)
if b == 0 or b == 10 or b == 13 then return true end
end
return false
end
local function parse_content_path(value)
if value == nil then
local out = {}
for i, part in ipairs(DEFAULT_CONTENT_PATH) do out[i] = part end
return out
end
local parts = {}
if type(value) == "string" then
if value == "" or string.sub(value, 1, 1) == "."
or string.sub(value, -1) == "." or string.find(value, "%.%.") then
return nil
end
for part in string.gmatch(value, "[^%.]+") do
if part == "" or contains_cr_lf_nul(part) then return nil end
-- A single wildcard supports homogeneous content-block arrays,
-- e.g. content.*.text. Every selected leaf must be a string.
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
if type(value) == "table" then
for i, part in ipairs(value) do
if type(part) ~= "string" or part == "" or contains_cr_lf_nul(part) then
return nil
end
parts[i] = part
end
local count = 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
count = count + 1
end
if count == 0 or count ~= #parts then return nil end
return parts
end
return nil
end
local function event_name_set(value, label, must_be_non_empty)
if type(value) ~= "table" then
error("stream_redact: config." .. label .. " must be an array of event names")
end
local set, count, max_index = {}, 0, 0
for k, name in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then
error("stream_redact: config." .. label .. " must be a dense array")
end
if type(name) ~= "string" or name == "" or contains_cr_lf_nul(name) then
error("stream_redact: config." .. label .. " entries must be non-empty event names without CR/LF/NUL")
end
if set[name] then
error("stream_redact: duplicate event name in config." .. label)
end
set[name] = true
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index or (must_be_non_empty and count == 0) then
error("stream_redact: config." .. label .. " must be a dense" .. (must_be_non_empty and " non-empty" or "") .. " array")
end
return set
end
local function normalize_settings(options)
if options == nil then
options = {}
end
if type(options) ~= "table" then
error("stream_redact: config must be a table")
end
local max_buffer_bytes = options.max_buffer_bytes
if max_buffer_bytes == nil then
max_buffer_bytes = DEFAULT_MAX_BUFFER_BYTES
end
if type(max_buffer_bytes) ~= "number" or max_buffer_bytes ~= math.floor(max_buffer_bytes)
or max_buffer_bytes < 1 or max_buffer_bytes > HARD_MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to 327680")
end
local text_event = options.text_event
if text_event == nil then
text_event = DEFAULT_TEXT_EVENT
end
if type(text_event) ~= "string" or text_event == "" or contains_cr_lf_nul(text_event) then
error("stream_redact: config.text_event must be a non-empty event name without CR/LF/NUL")
end
-- These lists are intentionally required: the true Agent event protocol has
-- not been certified, so shipping hard-coded guesses can silently hold errors.
local terminal_error_events = event_name_set(options.terminal_error_events, "terminal_error_events", true)
local control_event_names = event_name_set(options.control_event_names, "control_event_names", true)
local redact_event_names
if options.redact_event_names == nil then
redact_event_names = { [text_event] = true }
else
redact_event_names = event_name_set(options.redact_event_names, "redact_event_names", true)
if not redact_event_names[text_event] then
error("stream_redact: config.redact_event_names must include config.text_event")
end
end
for name in pairs(terminal_error_events) do
if not control_event_names[name] then
error("stream_redact: every terminal_error_event must also be listed in control_event_names")
end
if redact_event_names[name] then
error("stream_redact: terminal error events are scrubbed separately and cannot be in redact_event_names")
end
end
if control_event_names[text_event] then
error("stream_redact: config.text_event cannot be a control or terminal event")
end
local content_path = parse_content_path(options.content_path)
if not content_path then
error("stream_redact: config.content_path must be a dot path or non-empty string array (use * for a dense content array)")
end
return {
max_buffer_bytes = max_buffer_bytes,
text_event = text_event,
content_path = content_path,
redact_event_names = redact_event_names,
terminal_error_events = terminal_error_events,
control_event_names = control_event_names,
}
end
local function copy_set(source)
local out = {}
for k, v in pairs(source) do out[k] = v end
return out
end
local function copy_settings(source)
local path = {}
for i, part in ipairs(source.content_path) do
path[i] = part
end
return {
max_buffer_bytes = source.max_buffer_bytes,
text_event = source.text_event,
content_path = path,
redact_event_names = copy_set(source.redact_event_names),
terminal_error_events = copy_set(source.terminal_error_events),
control_event_names = copy_set(source.control_event_names),
}
end
local function clear_state(key)
if key ~= nil then states[key] = nil end
if key then states[key] = nil end
end
local function block_and_clear(key, reason)
clear_state(key)
return { action = "block", reason = reason or "stream redaction failed" }
local function is_continuation(byte)
return byte ~= nil and byte >= 0x80 and byte <= 0xBF
end
local function finite_number(value)
return type(value) == "number" and value == value
and value ~= math.huge and value ~= -math.huge
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
-- Estimate retained + processing footprint rather than counting raw body bytes.
-- The 3x data weight budgets for raw event JSON, joined text/masked text, and
-- transient decoded/encoded structures; 128 bytes/frame budgets Lua table data.
local function estimate_event_bytes(event)
if type(event) ~= "table" then return nil end
if type(event.has_data) ~= "boolean" then return nil end
if event.event ~= nil and type(event.event) ~= "string" then return nil end
if event.id ~= nil and type(event.id) ~= "string" then return nil end
if event.data ~= nil and type(event.data) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
if not event.has_data and event.data ~= nil and event.data ~= "" then return nil end
if event.event and contains_cr_lf_nul(event.event) then return nil end
if event.id and contains_cr_lf_nul(event.id) then return nil end
if event.comments ~= nil and type(event.comments) ~= "table" then return nil end
if event.retry ~= nil then
if not finite_number(event.retry) or event.retry < 0
or event.retry ~= math.floor(event.retry) then
return nil
local function parse_path(value)
if type(value) ~= "string" or value == "" then return nil end
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
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 == nil or child == host.json.null 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
local size = 128
if event.event then size = size + #event.event end
if event.id then size = size + #event.id end
if event.has_data and event.data then size = size + 3 * #event.data end
if event.retry ~= nil then size = size + #tostring(event.retry) end
if event.comments then
local count = 0
for k, comment in pairs(event.comments) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k)
or type(comment) ~= "string" then
return nil
end
count = count + 1
end
if count ~= #event.comments then return nil end
for _, comment in ipairs(event.comments) do
size = size + #comment + 16
end
if type(node) ~= "table" then
malformed = true
return false
end
return size
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 dense_array_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 ~= math.floor(k) 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
-- Resolve one path to one or more string leaves. `*` expands a dense array
-- such as content.*.text. Any missing/non-string leaf fails closed to avoid
-- silently skipping a potentially textual block.
local function get_content_locations(payload, path)
local found = {}
local function walk(node, depth)
if depth > #path then
if type(node) ~= "string" then return false end
found[#found + 1] = { parent = nil, key = nil, content = node }
return true
end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length or length == 0 then return false end
for i = 1, length do
local before = #found
if not walk(node[i], depth + 1) or #found == before then return false end
end
return true
end
if type(node) ~= "table" then return false end
local child = node[segment]
if child == nil then return false end
if depth == #path then
if type(child) ~= "string" then return false end
found[#found + 1] = { parent = node, key = segment, content = child }
return true
end
return walk(child, depth + 1)
end
if not walk(payload, 1) or #found == 0 then return nil end
-- For wildcard paths, resolve the parent/key pairs from the original tree
-- through a second walk. The first walk's temporary leaf parent is unused.
local locations = {}
local function walk_locations(node, depth)
if depth > #path then return end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length then return end
for i = 1, length do
if depth == #path then
-- A terminal wildcard (e.g. content.*) makes each array
-- element itself the string leaf, so its parent is the
-- array and its key is the numeric index.
if type(node[i]) ~= "string" then return end
locations[#locations + 1] = { parent = node, key = i, content = node[i] }
else
walk_locations(node[i], depth + 1)
end
end
return
end
if type(node) ~= "table" then return end
if depth == #path then
locations[#locations + 1] = { parent = node, key = segment, content = node[segment] }
return
end
walk_locations(node[segment], depth + 1)
end
walk_locations(payload, 1)
if #locations ~= #found then return nil end
return locations
end
local function is_leap_year(year)
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
end
local ID_WEIGHTS = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }
local ID_CHECK_CHARS = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }
local function valid_cn_resident_id(token)
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
return false
end
local year = tonumber(string.sub(token, 7, 10))
local month = tonumber(string.sub(token, 11, 12))
local day = tonumber(string.sub(token, 13, 14))
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
return false
end
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if day < 1 or day > days[month] then return false end
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
return false
end
local year = tonumber(string.sub(token, 7, 10))
local month = tonumber(string.sub(token, 11, 12))
local day = tonumber(string.sub(token, 13, 14))
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
return false
end
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if day < 1 or day > days[month] then return false end
local sum = 0
for i = 1, 17 do
local digit = tonumber(string.sub(token, i, i))
if not digit then return false end
sum = sum + digit * ID_WEIGHTS[i]
end
local expected = ID_CHECK_CHARS[(sum % 11) + 1]
return string.upper(string.sub(token, 18, 18)) == expected
local sum = 0
for i = 1, 17 do
local digit = tonumber(string.sub(token, i, i))
if not digit then return false end
sum = sum + digit * ID_WEIGHTS[i]
end
return string.upper(string.sub(token, 18, 18)) == ID_CHECK_CHARS[(sum % 11) + 1]
end
-- Conservative token-based patterns:
-- * valid-format 18-char mainland resident IDs (date + checksum checked)
-- * 11-digit mainland mobile-number candidates (prefix check only)
-- Longer contiguous digit runs, spaced/hyphenated values, 16-digit cards,
-- passport numbers and semantic secrets are outside this example's coverage.
-- 字节长度不变:身份证/手机号按位替换成 *
local function mask_sensitive_tokens(text)
return (string.gsub(text, "[%dXx]+", function(token)
if valid_cn_resident_id(token) then
return string.rep("*", #token)
end
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
return string.rep("*", #token)
end
return token
end))
return (string.gsub(text, "[%dXx]+", function(token)
if valid_cn_resident_id(token) then
return string.rep("*", #token)
end
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
return string.rep("*", #token)
end
return token
end))
end
local function error_frame(code, message)
local body = host.json.encode({
error = {
message = message,
type = "server_error",
param = host.json.null,
code = code,
},
})
return { has_data = true, data = body }
end
local function fail(key, code, message)
clear_state(key)
return { action = "replace", events = host.json.array({ error_frame(code, message) }) }
end
local function estimate_event_bytes(event)
if type(event) ~= "table" then return nil end
if type(event.has_data) ~= "boolean" then return nil end
if event.event ~= nil and type(event.event) ~= "string" then return nil end
if event.id ~= nil and type(event.id) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
local size = 128
if event.event then size = size + #event.event end
if event.id then size = size + #event.id end
if event.has_data and event.data then size = size + 3 * #event.data end
if event.comments then
for _, comment in ipairs(event.comments) do
if type(comment) ~= "string" then return nil end
size = size + #comment + 16
end
end
return size
end
local function redact_and_release(key, state)
local text_parts = {}
local entries = {}
local combined = table.concat(state.texts)
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
-- First pass: extract all configured string leaves without retaining decoded
-- payload tables. Wildcard paths support homogeneous content-block arrays.
for index, event in ipairs(state.frames) do
if state.settings.redact_event_names[event.event] and event.has_data then
local ok, payload = pcall(host.json.decode, event.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "invalid text event payload")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then
return block_and_clear(key, "text event payload does not match configured content_path")
end
local lengths = {}
for _, location in ipairs(locations) do
local content = location.content
lengths[#lengths + 1] = #content
text_parts[#text_parts + 1] = content
end
entries[#entries + 1] = { frame_index = index, content_lengths = lengths }
payload = nil
end
end
local combined = table.concat(text_parts)
text_parts = nil
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return block_and_clear(key, "redaction changed byte length")
end
combined = nil
-- Second pass: decode/mutate/encode one payload at a time to lower peak memory.
local offset = 1
for _, entry in ipairs(entries) do
local frame = state.frames[entry.frame_index]
local ok, payload = pcall(host.json.decode, frame.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "text event re-decode failed")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations or #locations ~= #entry.content_lengths then
return block_and_clear(key, "text event structure changed during redaction")
end
for j, location in ipairs(locations) do
local old_content = location.content
local expected_length = entry.content_lengths[j]
if type(old_content) ~= "string" or #old_content ~= expected_length then
return block_and_clear(key, "text event changed during redaction")
end
local replacement = ""
if expected_length > 0 then
replacement = string.sub(masked, offset, offset + expected_length - 1)
end
offset = offset + expected_length
location.parent[location.key] = replacement
end
local encode_ok, encoded = pcall(host.json.encode, payload)
payload = nil
if not encode_ok or type(encoded) ~= "string" then
return block_and_clear(key, "text event serialization failed")
end
frame.data = encoded
end
masked = nil
entries = nil
local ok, released = pcall(host.json.array, state.frames)
if not ok or type(released) ~= "table" then
return block_and_clear(key, "event array creation failed")
end
clear_state(key)
return { action = "replace", events = released }
end
local function pending_text_tail(state, limit)
-- Maintained incrementally while frames are buffered; terminal-error handling
-- must not re-decode every pending frame on a failure path.
local tail = state.text_tail or ""
if #tail > limit then return string.sub(tail, -limit) end
return tail
end
local function update_pending_text_tail(state, event)
if event.has_data ~= true or not state.settings.redact_event_names[event.event] then
return true
end
local decode_ok, payload = pcall(host.json.decode, event.data)
if not decode_ok or type(payload) ~= "table" then return false end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then return false end
local tail = state.text_tail or ""
for _, location in ipairs(locations) do
local joined = tail .. location.content
if #joined > 18 then
tail = string.sub(joined, -18)
else
tail = joined
end
end
state.text_tail = tail
return true
end
local function mask_with_context(value, context)
local prefix = context or ""
local probe = prefix .. value
local masked = mask_sensitive_tokens(probe)
if #masked ~= #probe then return nil end
return string.sub(masked, #prefix + 1)
end
local function redact_terminal_error_event(key, state, event)
-- Pending response text is never released after an upstream failure.
-- Keep only a short text tail long enough to detect supported patterns
-- split between the last held text frame and the error payload.
local context = pending_text_tail(state, 18)
if context == nil then
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
return { action = "block", reason = "cannot safely inspect pending text before terminal error" }
end
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
if event.has_data ~= true or type(event.data) ~= "string" or event.data == "" then
return { action = "pass" }
end
-- Error payloads are not assumed to be body-free. Prefer JSON-aware string
-- value redaction; if this isn't JSON, scrub raw text. The last 18 bytes of
-- held text are prepended only for matching, then removed from the output.
local decoded_ok, payload = pcall(host.json.decode, event.data)
if decoded_ok then
local changed = false
local function scrub(value)
if type(value) == "string" then
local masked_value = mask_with_context(value, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= value then changed = true end
return masked_value
end
if type(value) == "table" then
for k, child in pairs(value) do
if type(child) == "string" then
local masked_value = mask_with_context(child, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= child then changed = true end
value[k] = masked_value
elseif type(child) == "table" then
scrub(child)
end
end
end
return value
end
local scrub_ok, cleaned = pcall(scrub, payload)
if not scrub_ok then
return { action = "block", reason = "terminal error redaction failed" }
end
payload = cleaned
if not changed then return { action = "pass" } end
local encode_ok, encoded = pcall(host.json.encode, payload)
if not encode_ok or type(encoded) ~= "string" then
return { action = "block", reason = "terminal error payload serialization failed" }
end
event.data = encoded
local events = {}
local offset = 1
for _, entry in ipairs(state.frames) do
if #entry.lengths == 0 then
events[#events + 1] = entry.event
else
local masked = mask_with_context(event.data, context)
if masked == nil then
return { action = "block", reason = "terminal error redaction failed" }
local ok_decode, decoded = pcall(host.json.decode, entry.event.data)
if not ok_decode or type(decoded) ~= "table" then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed or #locations ~= #entry.lengths then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
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
if masked == event.data then return { action = "pass" } end
event.data = masked
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 fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local copy = {}
for k, v in pairs(entry.event) do copy[k] = v end
copy.data = encoded
events[#events + 1] = copy
end
end
local array_ok, single = pcall(host.json.array, { event })
if not array_ok or type(single) ~= "table" then
return { action = "block", reason = "terminal error event array creation failed" }
end
return { action = "replace", events = single }
clear_state(key)
return { action = "replace", events = host.json.array(events) }
end
function plugin.init(ctx, options)
-- init may run during startup validation and request setup; do not clear states.
settings = normalize_settings(options)
return nil
if type(options) ~= "table" then
error("stream_redact config must be a table")
end
local content_path = parse_path(options.content_path or DEFAULT_PATH)
if not content_path then
error("stream_redact: config.content_path must be a dot path like 'choices.*.delta.content'")
end
local max_buffer_bytes = tonumber(options.max_buffer_bytes) or MAX_BUFFER_BYTES
if max_buffer_bytes < 1 or max_buffer_bytes % 1 ~= 0 or max_buffer_bytes > MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to " .. MAX_BUFFER_BYTES)
end
config = {
content_path = content_path,
max_buffer_bytes = max_buffer_bytes,
}
return nil
end
function plugin.on_response(ctx, response)
-- This example's guarantee is SSE-only. Refuse ordinary responses rather
-- than silently passing unredacted content through the same enabled rule.
if type(response) ~= "table" then
return { action = "block", reason = "invalid response object" }
end
if response.streaming == true then
return nil
end
return { action = "block", reason = "stream_redact only supports SSE responses" }
-- 非流式由 response_guard 负责,这里不重复加工
if response.streaming ~= true then return { action = "pass" } end
return nil
end
function plugin.on_event(ctx, event)
@@ -594,58 +280,55 @@ function plugin.on_event(ctx, event)
return { action = "block", reason = "missing request id" }
end
local existing = states[key]
local size = estimate_event_bytes(event)
if not size then
return block_and_clear(key, "invalid SSE event")
end
local state = existing
-- Once a terminal failure was observed, *all* subsequent events, including
-- duplicate terminal errors, are rejected. This check must precede name lookup.
if state and state.aborted then
return { action = "block", reason = "event received after terminal error" }
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local state = states[key]
if not state then
if not settings then
return { action = "block", reason = "plugin not initialized" }
end
state = {
settings = copy_settings(settings),
frames = {},
buffer_bytes = 0,
text_tail = "",
}
state = { frames = {}, buffer_bytes = 0, texts = {} }
states[key] = state
end
-- Terminal error names come only from the validated, request-snapshotted config.
if event.event and state.settings.terminal_error_events[event.event] then
return redact_terminal_error_event(key, state, event)
if state.aborted then
return { action = "replace", events = host.json.array() }
end
-- Valid no-data SSE frames (typically comment heartbeats) carry no content.
-- They pass immediately, but only after checking terminal state above.
if event.has_data == false then
return { action = "pass" }
if state.buffer_bytes + size > config.max_buffer_bytes then
state.aborted = true
return fail(key, "response_too_large",
"The model response exceeded the redaction buffer limit.")
end
if state.buffer_bytes + size > state.settings.max_buffer_bytes then
return block_and_clear(key, "estimated stream redaction buffer limit exceeded")
local entry = { event = event, lengths = {} }
if event.has_data == true and type(event.data) == "string" and event.data ~= ""
and event.data ~= "[DONE]" then
local ok_decode, decoded = pcall(host.json.decode, event.data)
if not ok_decode or type(decoded) ~= "table" then
state.aborted = true
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed then
state.aborted = true
return fail(key, "unexpected_stream_shape",
"The response stream shape was not recognised.")
end
for i, location in ipairs(locations) do
local text = location.parent[location.key]
entry.lengths[i] = #text
state.texts[#state.texts + 1] = text
end
end
-- Validate and update the <=18-byte cross-frame inspection tail as each
-- configured text-bearing event arrives. This avoids O(frame_count) decode
-- work if a terminal error arrives after a large buffered response.
if not update_pending_text_tail(state, event) then
return block_and_clear(key, "text event payload does not match configured content_path")
end
state.frames[#state.frames + 1] = event
state.frames[#state.frames + 1] = entry
state.buffer_bytes = state.buffer_bytes + size
if event.has_data == true and event.data == "[DONE]" then
return redact_and_release(key, state)
end
return { action = "hold" }
end
@@ -655,24 +338,17 @@ function plugin.on_end(ctx)
return { action = "block", reason = "missing request id at end" }
end
local state = states[key]
if not state then
return nil
end
if not state then return nil end
if state.aborted then
clear_state(key)
return nil
end
if #state.frames == 0 then
clear_state(key)
return nil
end
return redact_and_release(key, state)
end
function plugin.close(ctx)
-- Only clear this request. On abnormal close, held text is deliberately dropped.
clear_state(request_key(ctx))
clear_state(request_key(ctx))
return nil
end
return plugin