astrbot_plugin_private_comp.../p4_runtime_gate.py

351 行
12 KiB
Python

# -*- coding: utf-8 -*-
"""Pure final reply gate for the P4 confinement runtime boundary.
This module is deliberately independent from AstrBot, persistence, P3, P5,
and the P4 ledger. A host must first reduce its authoritative P4 ledger into
the exact state shape below. In particular, passing a P4-A shadow state or a
P4-B preparation ledger directly is rejected rather than silently becoming a
live confinement decision.
Accepted state shape::
{
"schema_version": "p4.runtime_gate.state.v1",
"authority": "private_companion_p4",
"confinement_state": "none" | "active" | "released",
"confinement_until": "" | <timezone-aware ISO-8601 timestamp>,
"warmth": "guarded" | "neutral" | "warm" | "close",
}
``active`` needs a non-empty cutoff. The cutoff is used only to determine
whether confinement has expired; it is never returned to a caller. The input
has no score, penalty, identity, memory, or provenance fields, which keeps the
gate from becoming a second P3 or P5 authority.
All public functions are side-effect-free and return new JSON-compatible
dictionaries. ``event`` is intentionally never inspected: event carrier
fields are user-writable and cannot release or soften confinement.
"""
from __future__ import annotations
from datetime import datetime, timezone
from math import isfinite
from typing import Any
P4_RUNTIME_STATE_SCHEMA = "p4.runtime_gate.state.v1"
P4_RUNTIME_GATE_RESULT_SCHEMA = "p4.runtime_gate.result.v1"
P4_RUNTIME_AUTHORITY = "private_companion_p4"
SAFE_CONFINEMENT_REPLY = "现在只能进行简短、尊重且安全的交流。"
_UTC = timezone.utc
_WARMTH_TIERS = frozenset({"guarded", "neutral", "warm", "close"})
_CONFINEMENT_STATES = frozenset({"none", "active", "released"})
_STATE_FIELDS = frozenset({
"schema_version",
"authority",
"confinement_state",
"confinement_until",
"warmth",
})
_BOUNDARY_BY_TIER = {
"guarded": "请保持尊重、简短的交流。",
"neutral": "保持尊重、自然交流。",
"warm": "保持尊重与分寸。",
"close": "保持尊重与分寸。",
}
_BLOCKED_CONTEXT_DISPOSITION = {
"prompt": "cleared",
"tool": "cleared",
"external": "cleared",
}
_ALLOWED_CONTEXT_DISPOSITION = {
"prompt": "preserved",
"tool": "preserved",
"external": "preserved",
}
_MAX_JSON_DEPTH = 24
_MAX_JSON_CONTAINER_ITEMS = 256
_MAX_JSON_STRING_LENGTH = 32_768
_INVALID = object()
def build_warmth_projection(state: Any, *, now: Any | None = None) -> dict[str, str]:
"""Return only a finite warmth tier and a short boundary prompt.
Invalid, unknown, active, expired, and released states are deliberately
projected as ``guarded``. The result never contains state fields, score,
cutoff, message text, reason, or penalty information.
Pass an explicit timezone-aware ``now`` in tests or deterministic callers.
With no ``now`` the current UTC instant is used solely to determine expiry.
"""
evaluation = _evaluate_state(state, now=now)
tier = evaluation["warmth"] if evaluation["status"] == "normal" else "guarded"
return {"tier": tier, "boundary": _BOUNDARY_BY_TIER[tier]}
def apply_confinement_gate(
req: Any,
event: Any,
state: Any,
*,
now: Any | None = None,
) -> dict[str, Any]:
"""Apply the final P4 reply gate without mutating any input.
``req`` must be a plain JSON-compatible mapping. A valid normal, expired,
or released P4 state permits that mapping through as a copied request.
Active, unknown, corrupt, or malformed state fails closed: the returned
request contains only a sealed marker, prompt/tool/external context is
reported as cleared, and ``reply_template`` is the fixed safe reply.
``event`` is deliberately discarded before any access. No event-carried
``authorized``, ``p4_state``, owner, bridge, tool, or external fields can
influence this decision.
"""
del event
evaluation = _evaluate_state(state, now=now)
status = evaluation["status"]
projection = _projection_from_evaluation(evaluation)
if status == "active":
return _blocked_result("p4_confinement_active", projection)
if status == "invalid":
return _blocked_result("p4_state_invalid", projection)
request = _json_clone(req)
if request is _INVALID or type(request) is not dict:
return _blocked_result("p4_request_invalid", projection)
code = {
"normal": "p4_normal",
"expired": "p4_confinement_expired",
"released": "p4_confinement_released",
}[status]
return {
"schema_version": P4_RUNTIME_GATE_RESULT_SCHEMA,
"final": True,
"decision": "allow",
"code": code,
"warmth_projection": projection,
"reply_template": "",
"request": request,
"context_disposition": dict(_ALLOWED_CONTEXT_DISPOSITION),
"event_disposition": "ignored",
}
def apply_confinement_gate_idempotently(
candidate: Any,
event: Any,
state: Any,
*,
now: Any | None = None,
) -> dict[str, Any]:
"""Repeat-safe pre-send helper for an internal outbound pipeline.
The helper always re-checks P4 state before honoring an earlier final
result. Thus a formerly allowed result cannot pass during active or
invalid confinement. If the same safe result is supplied again under the
same allowed state, a fresh equal copy is returned rather than nesting it
as a provider request.
Use :func:`apply_confinement_gate` at the untrusted ingress boundary. This
helper is for a pipeline's own previous result, not a user-provided result
envelope.
"""
del event
evaluation = _evaluate_state(state, now=now)
status = evaluation["status"]
if status in {"active", "invalid"}:
return apply_confinement_gate(candidate, None, state, now=now)
if _is_repeat_safe_result(candidate, evaluation):
copied = _json_clone(candidate)
assert isinstance(copied, dict)
return copied
return apply_confinement_gate(candidate, None, state, now=now)
# A concise alias reads naturally at a final outbound send call site.
ensure_confinement_gate = apply_confinement_gate_idempotently
def _blocked_result(code: str, projection: dict[str, str]) -> dict[str, Any]:
"""Build a response that has no route back to original request content."""
return {
"schema_version": P4_RUNTIME_GATE_RESULT_SCHEMA,
"final": True,
"decision": "block",
"code": code,
"warmth_projection": dict(projection),
"reply_template": SAFE_CONFINEMENT_REPLY,
"request": {
"p4_runtime_gate": {
"schema_version": P4_RUNTIME_GATE_RESULT_SCHEMA,
"decision": "block",
"prompt_context": "cleared",
"tool_context": "cleared",
"external_context": "cleared",
}
},
"context_disposition": dict(_BLOCKED_CONTEXT_DISPOSITION),
"event_disposition": "ignored",
}
def _projection_from_evaluation(evaluation: dict[str, str]) -> dict[str, str]:
tier = evaluation["warmth"] if evaluation["status"] == "normal" else "guarded"
return {"tier": tier, "boundary": _BOUNDARY_BY_TIER[tier]}
def _evaluate_state(state: Any, *, now: Any | None) -> dict[str, str]:
"""Classify only the narrow runtime state contract; invalid is fail-closed."""
moment, valid_clock = _coerce_now(now)
if not valid_clock or type(state) is not dict or frozenset(state) != _STATE_FIELDS:
return {"status": "invalid", "warmth": "guarded"}
if state.get("schema_version") != P4_RUNTIME_STATE_SCHEMA:
return {"status": "invalid", "warmth": "guarded"}
if state.get("authority") != P4_RUNTIME_AUTHORITY:
return {"status": "invalid", "warmth": "guarded"}
confinement_state = state.get("confinement_state")
warmth = state.get("warmth")
cutoff = state.get("confinement_until")
if (
type(confinement_state) is not str
or confinement_state not in _CONFINEMENT_STATES
or type(warmth) is not str
or warmth not in _WARMTH_TIERS
or type(cutoff) is not str
):
return {"status": "invalid", "warmth": "guarded"}
if confinement_state == "active":
until = _parse_timestamp(cutoff)
if until is None:
return {"status": "invalid", "warmth": "guarded"}
if moment is not None and moment >= until:
return {"status": "expired", "warmth": "guarded"}
return {"status": "active", "warmth": "guarded"}
if cutoff != "":
return {"status": "invalid", "warmth": "guarded"}
if confinement_state == "released":
return {"status": "released", "warmth": "guarded"}
return {"status": "normal", "warmth": warmth}
def _coerce_now(value: Any | None) -> tuple[datetime | None, bool]:
if value is None:
return datetime.now(_UTC), True
if type(value) is datetime:
if value.tzinfo is None or value.utcoffset() is None:
return None, False
return value.astimezone(_UTC), True
if type(value) is str:
parsed = _parse_timestamp(value)
return (parsed, parsed is not None)
return None, False
def _parse_timestamp(value: Any) -> datetime | None:
if type(value) is not str or not value or value != value.strip() or len(value) > 64:
return None
text = f"{value[:-1]}+00:00" if value.endswith("Z") else value
try:
moment = datetime.fromisoformat(text)
except ValueError:
return None
if moment.tzinfo is None or moment.utcoffset() is None:
return None
return moment.astimezone(_UTC)
def _json_clone(value: Any, *, depth: int = 0) -> Any:
"""Copy bounded, plain JSON data without invoking foreign object hooks."""
if depth > _MAX_JSON_DEPTH:
return _INVALID
if value is None or type(value) is bool:
return value
if type(value) is str:
return value if len(value) <= _MAX_JSON_STRING_LENGTH else _INVALID
if type(value) is int:
return value
if type(value) is float:
return value if isfinite(value) else _INVALID
if type(value) is list:
if len(value) > _MAX_JSON_CONTAINER_ITEMS:
return _INVALID
copied_list: list[Any] = []
for item in value:
copied = _json_clone(item, depth=depth + 1)
if copied is _INVALID:
return _INVALID
copied_list.append(copied)
return copied_list
if type(value) is dict:
if len(value) > _MAX_JSON_CONTAINER_ITEMS:
return _INVALID
copied_dict: dict[str, Any] = {}
for key, item in value.items():
if type(key) is not str or len(key) > _MAX_JSON_STRING_LENGTH:
return _INVALID
copied = _json_clone(item, depth=depth + 1)
if copied is _INVALID:
return _INVALID
copied_dict[key] = copied
return copied_dict
return _INVALID
def _is_repeat_safe_result(candidate: Any, evaluation: dict[str, str]) -> bool:
"""Recognize only this module's exact allowed result shape.
This is an idempotency convenience, never an authorization shortcut: the
caller has already re-evaluated state before reaching this function.
"""
candidate_copy = _json_clone(candidate)
if candidate_copy is _INVALID or type(candidate_copy) is not dict:
return False
candidate = candidate_copy
required = {
"schema_version",
"final",
"decision",
"code",
"warmth_projection",
"reply_template",
"request",
"context_disposition",
"event_disposition",
}
if frozenset(candidate) != required:
return False
expected_code = {
"normal": "p4_normal",
"expired": "p4_confinement_expired",
"released": "p4_confinement_released",
}.get(evaluation["status"])
if (
candidate.get("schema_version") != P4_RUNTIME_GATE_RESULT_SCHEMA
or candidate.get("final") is not True
or candidate.get("decision") != "allow"
or candidate.get("code") != expected_code
or candidate.get("reply_template") != ""
or candidate.get("event_disposition") != "ignored"
or candidate.get("context_disposition") != _ALLOWED_CONTEXT_DISPOSITION
or candidate.get("warmth_projection") != _projection_from_evaluation(evaluation)
):
return False
copied = _json_clone(candidate.get("request"))
return copied is not _INVALID and type(copied) is dict