Metadata-Version: 2.4
Name: kaito-guardrail-core
Version: 0.2.2
Summary: KAITO-owned guardrail scanners and streaming utilities
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/kaito-project/kaito-guardrail-core
Project-URL: Source, https://github.com/kaito-project/kaito-guardrail-core
Project-URL: Issues, https://github.com/kaito-project/kaito-guardrail-core/issues
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Operating System :: OS Independent
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: bc-detect-secrets==1.5.43
Requires-Dist: json-repair==0.60.1
Requires-Dist: regex==2024.11.6
Requires-Dist: tiktoken==0.12.0
Dynamic: license-file

# KAITO Guardrail Core

`kaito-guardrail-core` provides KAITO-owned scanners and standard-library-only
streaming utilities. `guardrail_core.streaming.sse` and
`guardrail_core.streaming.openai` frame SSE events and parse/build OpenAI chat
chunks; they do not scan or enforce policy.

`guardrail_core.streaming.window` provides a policy-independent text window for
scan-before-release buffering.

## Scanner configuration (0.2.0)

`guardrail_core.config` exposes scanner schemas, along with
`parse_scanner_config()` and `build_scanner()`. Applications
own policy loading and failure handling; they must not recreate a scanner registry.

The following example configures all eight supported scanner types:

```python
from guardrail_core.config import build_scanner, parse_scanner_config

scanner_configs = [
    {
        "type": "ban_substrings",
        "substrings": ["secret"],
        "match_type": "word",
        "case_sensitive": False,
        "contains_all": False,
        "action": "redact",
    },
    {"type": "invisible_text", "action": "redact"},
    {
        "type": "regex",
        "patterns": [r"\bINTERNAL-\d+\b"],
        "is_blocked": True,
        "match_type": "search",
        "action": "block",
    },
    {
        "type": "json",
        "required_elements": 1,
        "repair": True,
        "action": "redact",
    },
    {
        "type": "reading_time",
        "max_time": 2.0,
        "truncate": True,
        "action": "redact",
    },
    {
        "type": "token_limit",
        "limit": 4096,
        "encoding_name": "cl100k_base",
        "action": "block",
    },
    {"type": "secrets", "redact_mode": "all", "action": "redact"},
    {
        "type": "sensitive",
        "detectors": ["email", "phone", "credit_card", "ip_address"],
        "action": "redact",
    },
]
scanners = [build_scanner(parse_scanner_config(raw)) for raw in scanner_configs]

result = scanners[0].scan("", "a secret")
assert result.output == "a [REDACTED]"
```

These are independent configuration examples, not a recommended scanner chain:
choose scanners appropriate to the content (for example, `json` expects JSON).

Entries use a flattened mapping with `type`, optional `action` (`block` or
`redact`), and scanner-specific fields. The default action is `block`. Type and
field names accept snake_case, camelCase, and hyphenated spelling. Scanner order
and policy-level actions remain the caller's responsibility when using these
low-level construction APIs directly.

The strict parser rejects unknown scanners, unknown or duplicate normalized
fields, invalid actions, and malformed scanner settings with `ValueError`.
It does not log and skip invalid entries. Construction exceptions from
`build_scanner()` propagate unchanged. The schema classes retain their existing
`from_dict()` and `build()` methods.

Configuration and construction stay in `guardrail_core.config`; sensitive-data
detection and redaction live in an internal scanner module. Consumers continue
to use the same configuration APIs.

## Complete-output policy scanning (unreleased)

`guardrail_core.buffered.scan_policy_output()` owns complete-text policy
decisions, independently of JSON framing or gateway transport:

```python
from guardrail_core.buffered import scan_policy_output
from guardrail_core.config import parse_scanner_config

result = scan_policy_output(
    [parse_scanner_config({
        "type": "ban_substrings",
        "substrings": ["secret"],
        "action": "redact",
    })],
    prompt="",
    output="a secret",
)
assert not result.blocked
assert result.output == "a [REDACTED]"
```

The function builds fresh scanners on every call, then executes them in
configured order, honoring per-scanner action overrides and `default_action`.
Unlike the streaming adapter, it does not reorder redactors before blockers or
restrict policies to streaming-capable scanners. Each scanner is evaluated
separately so repeated scanner types cannot hide an earlier block.

`PolicyScanResult.output` is the complete allowed text, including an empty
sanitized string. A blocked result has `blocked=True` and `output=None`; never
release the original output after a block. Redaction hits with unchanged or
non-string output block. Secrets redaction shares the streaming adapter's
verification: sanitization must not grow the text, and a second scan must pass
without changing it. Gateway consumers must not reproduce that verification.

Empty configurations, invalid actions, and non-string input are rejected.
Scanner construction and execution errors propagate; consumers own transport
error reporting and fail-closed handling. The low-level `scan_output()` API and
its existing tuple contract are unchanged.

## Streaming scanner adapter

`ScannerWindowAdapter` connects configured scanners to `StreamingBufferWindow`.
Redactors run before blockers, preserving relative order within each group.
It handles word-boundary context, derives the minimum holdback, and verifies
Secrets redaction before release.
Configurations, including nested lists, are copied at construction; later caller
changes do not affect the adapter.

```python
from guardrail_core.config import parse_scanner_config
from guardrail_core.streaming.scanners import ScannerWindowAdapter
from guardrail_core.streaming.window import StreamingBufferWindow

scanner = ScannerWindowAdapter([
    parse_scanner_config({
        "type": "ban_substrings",
        "substrings": ["secret"],
        "action": "redact",
    }),
])
window = StreamingBufferWindow(scanner, holdback_len=scanner.holdback_len)
```

| Scanner | Supported actions | Restrictions |
| --- | --- | --- |
| `ban_substrings` | `block`, `redact` | `word` or `str`; `contains_all=False` |
| `invisible_text` | `block`, `redact` | None |
| `secrets` | `block`, `redact` | Redaction requires `redact_mode="all"` |
| `sensitive` | `block`, `redact` | Email, phone, credit card, IPv4 |

Unsupported configurations raise `StreamingPolicyError` before construction.
Construction errors propagate; scan exceptions are wrapped by the window in
`WindowScanError`.

Holdback defaults to at least 256 Unicode code points and increases for longer
substrings. Smaller explicit bounds are rejected. Detection is limited to the
retained window; arbitrary-length Secrets/Sensitive matches are not guaranteed.

Release only chunks returned by the window. Flush only after validated normal
completion; discard the window on failure or cancellation. Consumers own stream
lifecycle, transport, and refusal responses.

## Installation and development

This repository originated from
[`kaito-project/kaito` main at `74d6eeeefe314e91f5c636de10c5b5c21cb21b64`](https://github.com/kaito-project/kaito/tree/74d6eeeefe314e91f5c636de10c5b5c21cb21b64/guardrail_core).

Install the published package:

```sh
python -m pip install kaito-guardrail-core
```

For local development:

```sh
python -m venv .venv
source .venv/bin/activate
python -m pip install -e . -r requirements-dev.txt
python -m build
python -m twine check --strict dist/*
python -m pytest tests
python -m ruff check --output-format=github .
python -m ruff format --check .
```

CI tests the installed wheel outside the source tree in a fresh environment on
Python 3.12 through 3.14. The distribution name is `kaito-guardrail-core`;
Python imports use `guardrail_core`.

The tokenizer dependency uses `tiktoken` 0.12.0, which provides Python 3.14 wheels.
The older 0.11.0 release cannot build its PyO3 extension on Python 3.14.

## Streaming window

`guardrail_core.streaming.window` retains output tails to detect cross-chunk
matches, releasing only scanner-approved prefixes.

`holdback_len` is measured in Unicode code points and must be sufficient for the
scanner's cross-chunk matching requirements.

```mermaid
flowchart TD
    Feed["feed(text)"] --> Buffer["Buffer text"]
    Buffer -->|Exceeds holdback| Scan["Scan entire buffer"]
    Buffer -->|Within holdback| Hold["Retain tail"]
    Scan -->|Allow / redact| Emit["Release approved prefix; retain tail"]
    Scan -->|Block| Block["Discard buffer; stop output"]
    Scan -->|Error| Error["Discard buffer; raise WindowScanError"]
    EOF["Normal EOF: flush()"] --> Final["Scan remaining text"]
    Final -->|Allow / redact| Release["Release remaining text"]
    Final -->|Block| Block
    Final -->|Error| Error
    Fail["Parse failure / cancellation"] --> Discard["Discard window; do not flush"]
```

Example (prints `hello world`; replace `print` with downstream emission):

```python
from guardrail_core.streaming.window import (
    StreamingBufferWindow,
    WindowScanError,
    WindowScanResult,
)


class Scanner:
    def scan(
        self, text: str, *, flush: bool = False, preceding_char: str = ""
    ) -> WindowScanResult:
        return WindowScanResult(blocked="secret" in text)


window = StreamingBufferWindow(Scanner(), holdback_len=len("secret") - 1)
chunks = ["hello ", "world"]

try:
    for text in chunks:
        result = window.feed(text)
        print("".join(result.chunks), end="")
        if result.blocked:
            print("[blocked]")
            break
    else:
        result = window.flush()
        print("[blocked]" if result.blocked else "".join(result.chunks), end="")
except WindowScanError:
    print("[scan failed]")
```

Use `chunks = ["safe se", "cret"]` to exercise cross-chunk blocking. Parse errors
and cancellation must propagate without entering the normal-EOF `else` branch.

`Scanner` is illustrative; replace it with your scanner adapter. The caller is
responsible for closing the upstream stream and generating product-specific
refusal responses.

## Byte-oriented SSE framing

```python
from guardrail_core.streaming.sse import SSEFramer
from guardrail_core.streaming.openai import parse_openai_chat_sse_event

framer = SSEFramer(max_event_bytes=1024 * 1024)
for chunk in [b'data: {"choices":[]}\r', b"\n\r", b"\n"]:
    for event in framer.feed(chunk):
        result = parse_openai_chat_sse_event(event)
        print(result.status, result.payload)
for event in framer.finish():
    print(event.data)
```

Call `feed(bytes)` in stream order and `finish()` exactly once at EOF. Both return
lists of complete `SSEEvent` objects. LF, CRLF, CR, mixed endings, and arbitrary
byte boundaries are supported. Complete events use strict UTF-8 decoding.
EOF never supplies a missing event terminator.

- `event.raw_bytes`: exact received bytes, **including** line endings and the
  terminating blank line, suitable for lossless forwarding.
- `event.raw`: decoded event body, excluding its final line ending and blank line.
- `event.lines`: body lines, including comments and non-data fields.
- `event.data`: joined data fields, or `None` when no data fields exist.
- `SSEEvent.from_raw(text)`: parse an already decoded event **body**, without
  framing; its `raw_bytes` defaults to the UTF-8 encoding of that body.

### Errors and resource bounds

`SSEFramingError` is a `ValueError` with these subclasses:

| Exception | Meaning |
| --- | --- |
| `SSEDecodeError` | A complete event is not valid UTF-8; the original decode error is chained. |
| `SSEIncompleteEventError` | EOF left an unterminated event, including an incomplete UTF-8 sequence. |
| `SSEEventTooLargeError` | An event exceeded `max_event_bytes` (default 1 MiB). |

`max_event_bytes` must be a positive integer and counts wire bytes, including
delimiters, per event. Invalid limits and non-byte input raise `ValueError`/`TypeError`.

On failure, `error.raw_bytes` contains the failing event's buffered bytes (at most
the limit); `error.completed_events` retains earlier complete events from the same
call. Callers choose whether to forward them and how to handle failure.
After a framing error or `finish()`, the framer is unusable; further calls raise
`ValueError`.

## OpenAI parsing contract

`parse_openai_chat_sse_event(event)` returns `OpenAIChatChunkParseResult` with the
following statuses and convenience fields:

| Input | `OpenAIChatChunkParseStatus` |
| --- | --- |
| No data field, empty data, or whitespace-only data | `NO_DATA` |
| Data equal to `[DONE]` after stripping whitespace | `DONE` |
| Invalid JSON | `MALFORMED_JSON`, with `error` |
| Non-object payload, non-list choices, or non-object choice | `INVALID_PAYLOAD`, with `error` |
| Missing/non-integer choice index (including bool) | `INVALID_PAYLOAD`, with `error` |
| Missing/null delta | `PARSED`, treating delta as an empty object |
| Non-object, non-null delta | `INVALID_PAYLOAD`, with `error` |
| Missing/null content | `PARSED`, no text |
| Non-string, non-null content or finish_reason | `INVALID_PAYLOAD`, with `error` |
| Missing `choices` | `PARSED`, treating choices as an empty list |
| Valid choices, including empty, role-only, and multi-choice chunks | `PARSED` |

All choices are retained in order, including role-only and tool-call-only chunks;
indexes need not be zero or contiguous. Use `parsed_choices` for aligned content
and finish reasons, not the filtered `contents`/`finish_reasons` lists.
`payload` preserves the original fields, including invalid object payloads.

## SSE builders

The functions in `guardrail_core.streaming.openai` return UTF-8-encodable strings
with LF delimiters:

- `build_openai_chat_delta_sse_chunk(content, *, choice_index=0)`
- `build_openai_chat_finish_reason_sse_chunk(*, finish_reason="content_filter", choice_index=0)`
- `build_sse_done_chunk()`
- `build_sse_data_chunk(payload)` for arbitrary JSON object fields and choices

Text builders create new minimal chunks; use the generic builder with a retained
payload to preserve metadata, or forward `event.raw_bytes` for byte-exact replay.

## Publishing

Build from the repository root, using `pyproject.toml` for metadata and version.
Wheels exclude tests; source distributions include tests and build inputs.

### Publisher setup

Confirm maintainer access and configure:

- A project or pending publisher on both TestPyPI and PyPI for `kaito-guardrail-core`.
- A GitHub Trusted Publisher on each index: owner `kaito-project`, repository
  `kaito-guardrail-core`, workflow filename `release-guardrail-core.yaml`, and the corresponding
  GitHub environment below. Publishing uses GitHub OIDC, not an API token.
- GitHub environments `guardrail-core-testpypi` and `guardrail-core-pypi`, restricted
  to `main`. Require maintainer approval for `guardrail-core-pypi` before enabling
  production publishing.

Trusted Publishers and GitHub environments from `kaito-project/kaito` do not
transfer automatically. Configure them for this repository before running a
release, and coordinate with KAITO maintainers so only one repository publishes
the package. Never republish an existing version.

### Release workflow

After the intended package version merges into `main`, run the
[Release KAITO Guardrail Core workflow](.github/workflows/release-guardrail-core.yaml):

1. Select `main`. Set `release_version` to the metadata version and `release_commit`
   to its full lowercase 40-character SHA on `main`; the package tag must not exist.
2. Build and validate the source distribution and wheel; test the installed wheel
   outside the source checkout.
3. Publish to TestPyPI and verify the downloaded wheel byte-for-byte. Install its
   dependencies separately from PyPI; do not mix indexes.
4. Approve `guardrail-core-pypi`, then publish the same stored artifacts to PyPI
   without rebuilding.
5. Create `kaito-guardrail-core-v<version>` and a GitHub Release for that source
   commit, attaching the artifacts. Do not mark it as the repository's latest release.

### Recovery

For transient failures, rerun only failed jobs in the same run to reuse artifacts.
Never overwrite an existing version or rebuild different content under it.
Coordinate partial-upload recovery with maintainers; bump the version in a new PR
before the next release.

### Consumer adoption

Consumers must pin a version already published on production PyPI. Production
images install requirements, not library source; editable installs are for development.
