Connect OpenAI Realtime to the existing async StructuredTool and shared SearchToolRunner with backend-owned authority and per-turn source references. Add an operator-only smoke harness with persisted actor and provider opt-in. Enforce confirmed readiness delivery, strict function identity, canonical results and once-only continuations. Bound and pace generated audio, preserve turn correlation, and require acknowledged cleanup before response release. Handle Unicode arguments, UTF-8 replay budgets and user-ASR completion replays. Validate with 318 voice/runner/shutdown tests and 1563 provider-free tests. Three Windows symlink tests skip; 311 PostgreSQL tests are deselected. Real-provider, browser playback and PostgreSQL acceptance remain unrun.
97 lines
3.8 KiB
Python
97 lines
3.8 KiB
Python
"""Bound JSON work and escaped UTF-8 size before allocating serialization."""
|
|
import hashlib
|
|
import json
|
|
import math
|
|
|
|
class SerializationLimit(ValueError):
|
|
pass
|
|
|
|
def json_size(value, limit, *, ensure_ascii=True, work_only=False):
|
|
used = 0
|
|
def spend(size):
|
|
nonlocal used
|
|
used += size
|
|
if used > limit:
|
|
raise SerializationLimit("JSON byte limit")
|
|
def string(value):
|
|
if len(value) > limit:
|
|
raise SerializationLimit("JSON string limit")
|
|
spend(2)
|
|
for ch in value:
|
|
number = ord(ch)
|
|
if 0xD800 <= number <= 0xDFFF:
|
|
raise ValueError("Invalid Unicode scalar")
|
|
if ch in ('"', "\\") or ch in "\b\f\n\r\t":
|
|
spend(2)
|
|
elif number < 32:
|
|
spend(6)
|
|
elif ensure_ascii and number >= 127:
|
|
spend(6 if number <= 0xFFFF else 12)
|
|
else:
|
|
spend(1 if number < 128 else len(ch.encode("utf-8")))
|
|
def visit(item, depth=0):
|
|
if depth > 16:
|
|
raise SerializationLimit("JSON depth limit")
|
|
if isinstance(item, str):
|
|
string(item)
|
|
elif item is None:
|
|
spend(4)
|
|
elif type(item) is bool:
|
|
spend(4 if item else 5)
|
|
elif type(item) in (int, float):
|
|
if type(item) is int and item.bit_length() > limit * 4:
|
|
raise SerializationLimit("JSON integer limit")
|
|
if type(item) is float and not math.isfinite(item):
|
|
raise ValueError("Nonfinite JSON")
|
|
if work_only:
|
|
# Bound numeric work without charging canonical float spelling
|
|
# against the already admitted provider wire. Integer bit work
|
|
# stays proportional to its minimum input decimal digits.
|
|
spend(max(1, item.bit_length() // 4) if type(item) is int else 1)
|
|
else:
|
|
spend(len(json.dumps(item, allow_nan=False)))
|
|
elif isinstance(item, dict):
|
|
spend(2)
|
|
for index, (key, child) in enumerate(item.items()):
|
|
if not isinstance(key, str):
|
|
raise ValueError("JSON string keys required")
|
|
if index:
|
|
spend(1)
|
|
string(key)
|
|
spend(1)
|
|
visit(child, depth + 1)
|
|
elif isinstance(item, (list, tuple)):
|
|
spend(2)
|
|
for index, child in enumerate(item):
|
|
if index:
|
|
spend(1)
|
|
visit(child, depth + 1)
|
|
else:
|
|
raise ValueError("JSON value required")
|
|
visit(value)
|
|
return used
|
|
|
|
def bounded_json(value, limit, *, ensure_ascii=True):
|
|
size = json_size(value, limit, ensure_ascii=ensure_ascii)
|
|
wire = json.dumps(value, ensure_ascii=ensure_ascii, allow_nan=False,
|
|
separators=(",", ":"), sort_keys=True)
|
|
if len(wire.encode("utf-8")) != size:
|
|
raise ValueError("Serialization accounting mismatch")
|
|
return wire
|
|
|
|
def bounded_json_digest(value, limit):
|
|
"""Hash canonical UTF-8 incrementally after bounded scalar/depth/work checks.
|
|
|
|
The transport owns the actual wire-byte cap. Canonical numeric spelling may
|
|
expand after parsing; it must not redefine that admission decision. UTF-8
|
|
strings/structure and numeric bit work remain bounded before hash encoding.
|
|
Outbound bounded_json keeps its independent exact serialization accounting.
|
|
"""
|
|
json_size(value, limit, ensure_ascii=False, work_only=True)
|
|
digest = hashlib.sha256()
|
|
encoder = json.JSONEncoder(ensure_ascii=False, allow_nan=False,
|
|
separators=(",", ":"), sort_keys=True)
|
|
for chunk in encoder.iterencode(value):
|
|
digest.update(chunk.encode("utf-8"))
|
|
return digest
|