local plugin = {} local config = {} local requests = {} local DEFAULT_MAX_BUFFER_BYTES = 65536 local MAX_TAIL_BYTES = 512 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 block_and_clear(key, reason) clear(key) return { action = "block", reason = reason } end local DEFAULT_CONTENT_PATH = { "data", "content" } local DEFAULT_NON_TEXT_EVENTS = { heartbeat = true, ping = true, run_started = true, run_finished = true, tool_started = true, tool_finished = true, tool_call_started = true, tool_call_finished = true, run_error = true, run_completed = true, } local function copy_array(source) local out = {} for i, value in ipairs(source or {}) do out[i] = value end return out end local function copy_map(source) local out = {} for k, v in pairs(source or {}) do out[k] = v end return out end local function content_path(settings) local path = (settings or config).content_path if path == nil then return copy_array(DEFAULT_CONTENT_PATH) end if type(path) == "table" then local parts, count, max_index = {}, 0, 0 for k, part in pairs(path) do if type(k) ~= "number" or k < 1 or k % 1 ~= 0 or type(part) ~= "string" or part == "" then return nil end parts[k] = part count = count + 1 if k > max_index then max_index = k end end if count == 0 or count ~= max_index then return nil end return parts end if type(path) ~= "string" or path == "" then return nil end local parts, from = {}, 1 while true do local dot = path:find(".", from, true) local part = dot and path:sub(from, dot - 1) or path:sub(from) if part == "" then return nil end parts[#parts + 1] = part if not dot then break end from = dot + 1 end return parts end -- nil means use the defaults. If explicitly configured, reject malformed -- entries instead of silently dropping them and reporting the plugin ready. local function configured_non_text_events(settings) local configured = (settings or config).non_text_events if configured == nil then return copy_map(DEFAULT_NON_TEXT_EVENTS) end if type(configured) ~= "table" then return nil, "config.non_text_events must be an array or {name=true} map" end local result, mode, count, max_index = {}, nil, 0, 0 for k, v in pairs(configured) do if type(k) == "number" then if mode == "map" or k < 1 or k % 1 ~= 0 or type(v) ~= "string" or v == "" then return nil, "invalid config.non_text_events array entry" end mode = "array" result[v] = true count = count + 1 if k > max_index then max_index = k end elseif type(k) == "string" then if mode == "array" or k == "" or v ~= true then return nil, "invalid config.non_text_events map entry" end mode = "map" result[k] = true else return nil, "invalid config.non_text_events key" end end if mode == "array" and count ~= max_index then return nil, "config.non_text_events array must be contiguous" end return result end local function extract_content(event, path) if type(event.data) ~= "string" then return nil, "event data is not a string" end local ok, decoded = pcall(host.json.decode, event.data) if not ok or type(decoded) ~= "table" then return nil, "invalid event JSON" end local value = decoded for _, part in ipairs(path) do if type(value) ~= "table" then value = nil; break end value = value[part] end if type(value) == "string" then return value, nil, copy_array(path) end -- Default compatibility: some Agent adapters emit the assistant message -- object itself rather than wrapping its text under data.content. local is_default_path = #path == 2 and path[1] == "data" and path[2] == "content" if is_default_path and decoded.role == "assistant" and type(decoded.content) == "string" then return decoded.content, nil, { "content" } end return nil, "event payload has no configured text field" end -- Redaction is deliberately local and deterministic: the guard model decides -- whether content may pass, while these rules mask common secrets/identifiers -- in assistant output. This is not a substitute for application-specific DLP. local function redact_text(text) local out = text -- Bearer credentials and common API-key shapes. 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) -- Email address: preserve domain and the first local-part character. 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-character Chinese resident identity number (17 digits plus digit/X). 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) -- Numeric identifiers such as bank-card numbers, including digit groups -- separated by spaces or hyphens. Preserve separators and byte length. 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) -- Mainland China mobile numbers. 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) -- Common 10-digit phone numbers, optionally separated by spaces, dots or hyphens. out = out:gsub("(%d%d%d)[%s%.%-]?(%d%d%d)[%s%.%-]?(%d%d%d%d)", function(a, b, c) return a .. "***" .. c end) return out end local function redact_assistant_content(value) if type(value) ~= "table" then return false, nil end local changed = false if value.role == "assistant" and value.content ~= nil then if type(value.content) ~= "string" then return false, "assistant.content is not a supported string" end local masked = redact_text(value.content) if masked ~= value.content then value.content = masked changed = true end end for _, child in pairs(value) do if type(child) == "table" then local child_changed, child_err = redact_assistant_content(child) if child_err then return false, child_err end if child_changed then changed = true end end end return changed, nil 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 set_path(root, path, replacement) local current = root for i = 1, #path - 1 do if type(current) ~= "table" or type(current[path[i]]) ~= "table" then return false end current = current[path[i]] end if type(current) ~= "table" then return false end current[path[#path]] = replacement return true end local function event_with_content(event, path, original_content, replacement_content) if original_content == replacement_content then return event end local ok, decoded = pcall(host.json.decode, event.data) if not ok or type(decoded) ~= "table" or not set_path(decoded, path, replacement_content) then return nil, "failed to prepare redacted SSE event" end local encode_ok, encoded = pcall(host.json.encode, decoded) if not encode_ok or type(encoded) ~= "string" then return nil, "failed to encode redacted SSE event" end local copy = shallow_copy(event) copy.data = encoded return copy end -- Redact the concatenated pending text, not each delta independently. PII such -- as an email or phone number may be split across SSE frames. Redaction rules -- preserve byte length, allowing sanitized text to be mapped back to the exact -- original event boundaries without changing protocol ordering or IDs. local function redact_pending_events(state) local original = table.concat(state.chunks) local redacted = redact_text(original) if #redacted ~= #original then return nil, "redaction changed text byte length" end local result, offset = {}, 1 for i, event in ipairs(state.pending) do local original_chunk = state.chunks[i] if type(original_chunk) ~= "string" then return nil, "pending event/text buffer mismatch" end local replacement_chunk = redacted:sub(offset, offset + #original_chunk - 1) local event_path = state.pending_paths and state.pending_paths[i] or state.content_path local replacement_event, err = event_with_content( event, event_path, original_chunk, replacement_chunk) if not replacement_event then return nil, err end result[#result + 1] = replacement_event offset = offset + #original_chunk end if offset - 1 ~= #original then return nil, "pending event/text buffer length mismatch" end return result end local USER_INPUT_AUDIT_PROMPT = "Review the following user-provided input for safety before forwarding it to the Agent." local function moderate_text(model, prompt, text) local ok, result = pcall(host.llm.call, model, { task = "response_moderation", prompt = prompt or "", response = text, }) return ok and type(result) == "table" and result.safety == "Safe" 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) -- Only inspect a short suffix; scanning the whole response prefix for -- every dot creates avoidable repeated copying. 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 -- Decimal/version fragments such as 3.14 or v1.2: do not treat a dot -- as a sentence boundary when digits are on both sides. 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 local after_punct = i + punct_len if ch == "." and is_abbreviation_dot(s, i) then i = i + punct_len else local j = after_punct 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 -- Chinese sentence punctuation is a complete boundary even -- when the next sentence starts immediately with Han text. -- ASCII punctuation keeps the whitespace requirement to avoid -- splitting decimals/abbreviations and common inline syntax. 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 response_text(state) return table.concat(state.chunks) end local function utf8_safe_tail(s, max_bytes) local start = math.max(1, #s - max_bytes + 1) -- If truncation lands on a UTF-8 continuation byte, skip continuation -- bytes until the next code-point start. The tail is only for scanning; -- original events are always released unchanged. while start <= #s do local b = s:byte(start) if not b or b < 128 or b >= 192 then break end start = start + 1 end return s:sub(start) end -- Default protocol metadata/lifecycle signals. Admins should calibrate this -- list to the actual Agent protocol through config.non_text_events. Unknown -- data-bearing events are never passed just because their names are unfamiliar. local function moderate_and_release(key, terminal) local state = key and requests[key] -- An empty on_end is not evidence that buffered state should be erased: -- preserve it, so a later event cannot accidentally be treated as unknown. if not state or #state.pending == 0 then return nil end local ok, result = pcall(host.llm.call, state.config.model, { task = "response_moderation", prompt = state.prompt, response = response_text(state), }) if not ok or type(result) ~= "table" or result.safety ~= "Safe" then return block_and_clear(key, "moderation failed or unsafe") end -- Redact across frame boundaries after the original text passes moderation. -- Failure to transform/serialize a release batch must fail closed. local redaction_ok, sanitized_pending, redaction_err = pcall(redact_pending_events, state) if not redaction_ok or type(sanitized_pending) ~= "table" then return block_and_clear(key, redaction_err or "failed to redact response events") end -- The host contract documents host.json.array, but guard the conversion: -- a bridge/serialization failure must fail closed, not crash this hook. local array_ok, events = pcall(host.json.array, sanitized_pending) if not array_ok or type(events) ~= "table" then return block_and_clear(key, "failed to construct release event array") end -- A sentence-level release is not the end of the request: preserve the -- request prompt so subsequent text_delta events can be moderated too. state.pending = {} state.pending_paths = {} state.chunks = {} state.text_bytes = 0 state.tail = "" if terminal then clear(key) end return { action = "replace", events = events } end function plugin.init(ctx, options) if options ~= nil and type(options) ~= "table" then error("response_guard config must be a table") end local candidate = options or {} if type(candidate.model) ~= "string" or candidate.model:match("^%s*$") then error("response_guard requires config.model") end local path = content_path(candidate) if not path then error("response_guard: invalid config.content_path") end local events, events_err = configured_non_text_events(candidate) if not events then error("response_guard: " .. events_err) end if candidate.max_buffer_bytes ~= nil then local max_bytes = tonumber(candidate.max_buffer_bytes) if not max_bytes or max_bytes < 1 or max_bytes % 1 ~= 0 then error("response_guard: config.max_buffer_bytes must be a positive integer") end end local normalized = {} for k, v in pairs(candidate) do normalized[k] = v end normalized.content_path = path normalized.non_text_events = events config = normalized -- Do not reset requests here: hosts may invoke init during request -- initialization. Per-request state is created by on_request and removed -- by block/terminal release/close, preserving in-flight requests. return nil end function plugin.on_request(ctx, request) local key = key_for(ctx) if not key then return { action = "block", reason = "missing request_id" } end local body = type(request) == "table" and request.body or "" local ok, decoded = pcall(host.json.decode, body or "") if not ok or type(decoded) ~= "table" then clear(key) return { action = "block", reason = "invalid request JSON" } end local request_config = shallow_copy(config) request_config.content_path = copy_array(config.content_path) request_config.non_text_events = copy_map(config.non_text_events) local user_contents = {} if decoded.messages ~= nil then if type(decoded.messages) ~= "table" then clear(key) return { action = "block", reason = "request messages must be an array" } end local count, max_index = 0, 0 for k, _ in pairs(decoded.messages) do if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then clear(key) return { action = "block", reason = "request messages must be a dense array" } end count = count + 1 if k > max_index then max_index = k end end if count ~= max_index then clear(key) return { action = "block", reason = "request messages array is sparse" } end local user_count = 0 for i = 1, max_index do local message = decoded.messages[i] if type(message) ~= "table" or type(message.role) ~= "string" then clear(key) return { action = "block", reason = "invalid request message shape" } end if message.role == "user" then if type(message.content) ~= "string" then clear(key) return { action = "block", reason = "user message content must be a string" } end user_count = user_count + 1 if #user_contents >= 32 then clear(key) return { action = "block", reason = "too many user messages to moderate safely" } end user_contents[#user_contents + 1] = message.content end end if user_count == 0 then clear(key) return { action = "block", reason = "request has no user message to moderate" } end elseif type(decoded.message) == "string" then -- Backward compatibility for older single-message request bodies. user_contents[1] = decoded.message else clear(key) return { action = "block", reason = "request has no supported user content" } end -- Review all user turns in one model call to stay within the hook's latency -- and host-call budgets. The separator is for readability; the classifier -- still sees the full original user text. Worker token limits remain a -- second guardrail and any rejection fails closed. local combined_user_content = table.concat(user_contents, "\n\n---\n\n") if combined_user_content ~= "" and not moderate_text( request_config.model, USER_INPUT_AUDIT_PROMPT, combined_user_content) then clear(key) return { action = "block", reason = "user input moderation failed or unsafe" } end local latest_user = user_contents[#user_contents] or "" requests[key] = { config = request_config, content_path = request_config.content_path, non_text_events = request_config.non_text_events, prompt = latest_user, chunks = {}, text_bytes = 0, tail = "", pending = {}, pending_paths = {}, } return { action = "pass" } end -- The complete, non-streaming UTF-8 body is moderated here. SSE responses are -- handled only by on_event; never attempt to replace their JSON-null body. function plugin.on_response(ctx, response) if type(response) ~= "table" then return { action = "block", reason = "invalid response" } end 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 for non-streaming response" } end if type(response.body) ~= "string" then return block_and_clear(key, "non-streaming response body is not UTF-8 text") end local max_bytes = tonumber(state.config.max_buffer_bytes) or DEFAULT_MAX_BUFFER_BYTES if #response.body > max_bytes then return block_and_clear(key, "non-streaming response body exceeds moderation limit") end -- Audit the original, unredacted response first. Only Safe output is eligible -- for sanitization and release; every LLM/serialization failure blocks. if not moderate_text(state.config.model, state.prompt, response.body) then return block_and_clear(key, "moderation failed or unsafe") end local sanitized_body = response.body local decode_ok, decoded = pcall(host.json.decode, response.body) if decode_ok and type(decoded) == "table" then local changed, redact_err = redact_assistant_content(decoded) if redact_err then return block_and_clear(key, redact_err) end if changed then local encode_ok, encoded = pcall(host.json.encode, decoded) if not encode_ok or type(encoded) ~= "string" then return block_and_clear(key, "failed to encode redacted response") end sanitized_body = encoded end else -- A plain UTF-8 response is still scrubbed for common identifiers. sanitized_body = redact_text(response.body) end clear(key) if sanitized_body ~= response.body then local replacement = shallow_copy(response) replacement.body = sanitized_body return { action = "replace", value = replacement } end return { action = "pass" } end function plugin.on_event(ctx, event) if type(event) ~= "table" then return { action = "block", reason = "invalid event" } end if event.has_data == false then return nil end if event.data == nil then if event.has_data == true then return { action = "block", reason = "has_data is true but data is missing" } end return nil end -- An empty SSE data field contains no output text to moderate or redact. if event.data == "" then return nil end local key = key_for(ctx) local state = key and requests[key] or nil local event_name = type(event.event) == "string" and event.event or nil if not state then -- Preserve pre-request control frames only when they contain no text at -- the default output path. A text-bearing frame without state is blocked -- because neither moderation nor redaction can be safely performed. if event_name and DEFAULT_NON_TEXT_EVENTS[event_name] then local content = extract_content(event, DEFAULT_CONTENT_PATH) if content == nil then return nil end return { action = "block", reason = "text-bearing event has no request state" } end if not key then return { action = "block", reason = "missing request_id" } end return { action = "block", reason = "request state missing" } end local content, err, actual_content_path = extract_content(event, state.content_path) local allowlisted = event_name and state.non_text_events[event_name] if content == nil then if allowlisted then return nil end return block_and_clear(key, err or "data-bearing event has no extractable text") end local max_bytes = tonumber(state.config.max_buffer_bytes) or DEFAULT_MAX_BUFFER_BYTES if max_bytes < 1 then max_bytes = DEFAULT_MAX_BUFFER_BYTES end if state.text_bytes + #content > max_bytes then return block_and_clear(key, "response moderation buffer limit exceeded") end local scan = state.tail .. content state.chunks[#state.chunks + 1] = content -- moderate original, unredacted text state.text_bytes = state.text_bytes + #content state.tail = utf8_safe_tail(scan, MAX_TAIL_BYTES) state.pending[#state.pending + 1] = event -- redact the whole pending text on release state.pending_paths[#state.pending_paths + 1] = actual_content_path or state.content_path -- Whitelisted control names only bypass moderation if their payload has no -- text at the configured content path. Text-bearing frames get both review -- and redaction, just like ordinary assistant deltas. if has_sentence_boundary(scan) then return moderate_and_release(key) end return { action = "hold" } end function plugin.on_end(ctx) local key = key_for(ctx) local state = key and requests[key] or nil return moderate_and_release(key, true) end function plugin.close(ctx) -- An invalid/missing context must never clear unrelated requests. local key = key_for(ctx) if key then clear(key) end return nil end return plugin