Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

97.5 KB
Raw Blame
"""Pixel Edge — internal OpenAI-compatible proxy.

Routes:
  GET  /health                — unauthenticated liveness
  GET  /preview/<site>/<path> — bearer-auth, immutable preview UDS relay
  GET  /v1/models             — bearer-auth, synthetic listing only
  GET  /v1/activity           — bearer-auth, content-free active-turn count
  GET  /v1/transition         — owner-service-auth, durable gate capability/status
  POST /v1/transition/{acquire,drain,release,recover} — owner-service-auth, bound gate control
  POST /v1/chat/completions   — bearer-auth, model rewrite, SSE passthrough

All other paths/methods return 404 (catch-all).
"""

import asyncio
import hashlib
import hmac
import json
import os
import re
import sys
from datetime import datetime
from urllib.parse import quote, urlsplit

from aiohttp import web, ClientSession, UnixConnector, TCPConnector, ClientTimeout, ClientError
from transition_gate import TransitionGate, GateError, strict_json, valid_binding
from runtime_identity import project_runtime_identity, unknown_runtime_identity
from chat_context import project_context, valid_history_snapshot
from image_admission import ImageWorkBudget
from access_mode import (public_status as public_access_status, valid_change as valid_access_change,
                         valid_model_control, public_model_control)


def valid_live_task_event(event):
    """Only bounded observations and explicitly public plans bypass the answer buffer."""
    if not isinstance(event, dict) or set(event) != {"object", "id", "pixel_task"} or event["object"] != "ods.task.activity":
        return False
    task = event["pixel_task"]
    extended = isinstance(task, dict) and task.get('schemaVersion') in (2, 3, 4)
    expected = {"schemaVersion", "runId", "startedAt", "finishedAt", "state", "calls", "failures", "blocked", "truncated", "activities"}
    if extended:
        expected |= {'events', 'context', 'goal'}
    if isinstance(task, dict) and task.get('schemaVersion') == 4:
        expected.add('projects')
    if not isinstance(task, dict) or set(task) != expected:
        return False
    if type(task["schemaVersion"]) is not int or task["schemaVersion"] not in {1, 2, 3, 4} or task["state"] != "running" or task["finishedAt"] is not None or type(task["truncated"]) is not bool:
        return False
    if not isinstance(event["id"], str) or not re.fullmatch(r"chatcmpl_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", event["id"], re.I) or task["runId"] != event["id"]:
        return False
    stamp = task["startedAt"]
    if not isinstance(stamp, str) or not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z", stamp):
        return False
    try:
        datetime.fromisoformat(stamp.replace("Z", "+00:00"))
    except ValueError:
        return False
    if extended and not valid_task_details(task):
        return False
    count_keys = ("calls", "failures", "blocked")
    if any(type(task[key]) is not int or not 0 <= task[key] <= 512 for key in count_keys):
        return False
    rows = task["activities"]
    if not isinstance(rows, list) or len(rows) > 8:
        return False
    seen, sums = set(), dict.fromkeys(count_keys, 0)
    for row in rows:
        if not isinstance(row, dict) or set(row) != {"kind", *count_keys} or not isinstance(row["kind"], str) or row["kind"] not in {"read", "agent", "run", "edit", "browser", "preview", "action", "unknown"} or row["kind"] in seen:
            return False
        if any(type(row[key]) is not int for key in count_keys) or not 0 <= row["blocked"] <= row["failures"] <= row["calls"] <= 512 or row["calls"] == 0:
            return False
        seen.add(row["kind"])
        for key in count_keys:
            sums[key] += row[key]
    return all(sums[key] == task[key] for key in count_keys)

def valid_activity_display(value):
    if value is None:
        return True
    def text(s,n):
        return isinstance(s,str) and 0 < len(s.strip()) <= len(s) <= n and not re.search(r'[\x00-\x1f\x7f]',s)
    if not isinstance(value,dict) or set(value) != {'type','label','detail','sources','steps','change'} or value['type'] not in ('text','search','tool','trace','steps') or not text(value['label'],160):
        return False
    if (value['detail'] is not None and not text(value['detail'],400)) or not isinstance(value['sources'],list) or len(value['sources'])>3 or not isinstance(value['steps'],list) or len(value['steps'])>8:
        return False
    for source in value['sources']:
        if not isinstance(source,dict) or set(source)!={'title','url'} or not text(source['title'],120) or not text(source['url'],512):
            return False
        try:
            url=urlsplit(source['url'])
            if url.scheme not in ('http','https') or not url.hostname or url.username or url.password:
                return False
        except ValueError:
            return False
    seen=set()
    for step in value['steps']:
        if not isinstance(step,dict) or set(step)!={'id','title','status'} or not isinstance(step['id'],str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,31}',step['id']) or step['id'] in seen or not text(step['title'],160) or step['status'] not in ('pending','running','completed','blocked'):
            return False
        seen.add(step['id'])
    if value['change'] is not None:
        c=value['change']
        def code(s):
            return isinstance(s,str) and len(s)<=1000 and not re.search(r'[\x00-\x08\x0b-\x1f\x7f]',s)
        if value['type']!='tool' or not isinstance(c,dict) or set(c)!={'file','kind','before','after','truncated'} or not text(c['file'],120) or c['kind'] not in ('write','edit','patch') or not code(c['before']) or not code(c['after']) or type(c['truncated']) is not bool:
            return False
    return (value['type']=='search' or not value['sources']) and (value['type']=='steps' or not value['steps'])

def valid_task_details(task):
    def timestamp(value):
        if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z", value):
            return False
        try:
            datetime.fromisoformat(value.replace('Z', '+00:00'))
            return True
        except ValueError:
            return False

    def text(value, maximum):
        return isinstance(value, str) and 0 < len(value.strip()) <= len(value) <= maximum and not re.search(r'[\x00-\x1f\x7f]', value)

    if task['schemaVersion'] == 4:
        projects = task.get('projects')
        if not isinstance(projects, list) or len(projects) > 8:
            return False
        seen = set()
        for project in projects:
            if (not isinstance(project, dict) or set(project) != {'schemaVersion', 'kind', 'relativeDirectory', 'observedAt'}
                    or type(project['schemaVersion']) is not int or project['schemaVersion'] != 1
                    or project['kind'] != 'ods-workspace-project' or not isinstance(project['relativeDirectory'], str)
                    or not re.fullmatch(r'Playground/[A-Za-z0-9][A-Za-z0-9._-]{0,63}', project['relativeDirectory'])
                    or project['relativeDirectory'].endswith('.')
                    or re.match(r'Playground/(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)', project['relativeDirectory'], re.I)
                    or not timestamp(project['observedAt']) or project['relativeDirectory'] in seen):
                return False
            seen.add(project['relativeDirectory'])

    events = task['events']
    if type(task['calls']) is not int or not isinstance(events, list) or len(events) != min(task['calls'], 24):
        return False
    for sequence, event in enumerate(events, start=task['calls'] - len(events) + 1):
        if not isinstance(event, dict) or set(event) != ({'sequence','kind','state','startedAt','finishedAt'} | ({'display'} if task['schemaVersion']>=3 else set())):
            return False
        if task['schemaVersion']>=3 and not valid_activity_display(event['display']):
            return False
        if type(event['sequence']) is not int or event['sequence'] != sequence or event['kind'] not in ('read','agent','run','edit','browser','preview','action','unknown') or event['state'] not in ('running','completed','failed','blocked'):
            return False
        if not timestamp(event['startedAt']) or event['startedAt'] < task['startedAt']:
            return False
        if event['state'] == 'running':
            if event['finishedAt'] is not None:
                return False
        elif not timestamp(event['finishedAt']) or event['finishedAt'] < event['startedAt']:
            return False
    context = task['context']
    if context is not None and (not isinstance(context, dict) or set(context) != {'used','window','measuredAt'} or any(type(context[k]) is not int or not 1 <= context[k] <= 10_000_000 for k in ('used','window')) or not timestamp(context['measuredAt']) or context['measuredAt'] < task['startedAt']):
        return False
    goal = task['goal']
    if goal is not None:
        if not isinstance(goal,dict) or set(goal) != {'status','summary','steps'} or goal['status'] not in ('active','completed','blocked','waiting') or not text(goal['summary'],300) or not isinstance(goal['steps'],list) or len(goal['steps']) > 8:
            return False
        seen = set()
        for step in goal['steps']:
            if not isinstance(step,dict) or set(step) != {'id','title','status'} or not isinstance(step['id'],str) or not re.fullmatch(r'[a-z][a-z0-9_]{0,31}',step['id']) or step['id'] in seen or not text(step['title'],160) or step['status'] not in ('pending','running','completed','blocked'):
                return False
            seen.add(step['id'])
        if goal['status'] == 'completed' and (not goal['steps'] or any(step['status'] != 'completed' for step in goal['steps'])):
            return False
    return True

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

_BEARER_TOKEN = os.environ.get("PIXEL_OPENWEBUI_KEY", "")
_SOCKET_PATH = os.environ.get("PIXEL_INGRESS_SOCKET", "/pixel-runtime/pixel-ingress.sock")
_PREVIEW_BEARER_TOKEN = os.environ.get("PIXEL_PREVIEW_PROXY_KEY", "")
_PREVIEW_SOCKET_PATH = os.environ.get(
    "PIXEL_PREVIEW_SOCKET", "/pixel-preview-runtime/http.sock"
)
_PUBLIC_MODEL = "portal/default"
_LEGACY_MODEL = "pixel/default"
_ALLOWED_MODELS = (_PUBLIC_MODEL, _LEGACY_MODEL)
_LISTEN_PORT = int(os.environ.get("PIXEL_EDGE_PORT_INTERNAL", "9595"))

# Header names (case-insensitive) that may be forwarded to upstream.
_SAFE_HEADERS = frozenset({
    "accept",
    "user-agent",
})

# Hop-by-hop headers per RFC 7230.
_HOP_BY_HOP = frozenset({
    "connection",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "te",
    "trailer",
    "transfer-encoding",
    "upgrade",
})

_MAX_BODY = 8 * 1024 * 1024          # Full history envelope; ingress validates 4 MiB text
_MAX_IMAGE_BODY = 16 * 1024 * 1024  # Encoded envelope, not an extra text allowance
_IMAGE_BODY_TIMEOUT = 30
_MAX_CANCEL_BODY = 256
_MAX_RESPONSE_BYTES = 2 * 1024 * 1024  # 2 MiB non-stream response cap
_MAX_CANCEL_RESPONSE_BYTES = 1024
_MAX_PREVIEW_RESPONSE_BYTES = 4 * 1024 * 1024

_CONNECT_TIMEOUT = 5
# The host ingress is capped at 32 minutes. Pixel Edge sits outside that
# trusted boundary, so both its total and no-first-byte budgets allow one
# additional minute before failing closed.
_TOTAL_TIMEOUT = 1980
_SOCK_READ_TIMEOUT = 1980
_MAX_SSE_LINE = 1024 * 1024
_MAX_SSE_PENDING_BYTES = 1024 * 1024
_MAX_SSE_PENDING_LINES = 4096

_UPSTREAM_REWRITE = "openclaw/default"
_SAFE_CHAT_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
_PREVIEW_SITE_ID = re.compile(r"^site-[a-f0-9]{24}$")
_PREVIEW_PATH_COMPONENT = re.compile(r"^(?!__ods_)(?!__pycache__$)[A-Za-z0-9_\[][A-Za-z0-9._\[\]-]{0,127}$")
_ARTIFACT_DRAFT_PREFIX = re.compile(
    r"^\s*(?:please\s+)?(?:build|write|draft|document|compose|create|edit|update|"
    r"refactor|implement|generate)\b",
    re.IGNORECASE,
)
_ARTIFACT_NOUN = re.compile(
    r"\b(?:app(?:lication)?|code|config(?:uration)?|documentation|example|file|"
    r"fixture|page|project|readme|script|site|snippet|test|web(?:site|page)?|"
    r"workspace)\b",
    re.IGNORECASE,
)
_RESERVED_ASSISTANT_REPLIES = frozenset({
    "NO_REPLY",
    "No response from OpenClaw.",
})
_SHORT_TEST_MESSAGE = re.compile(
    r"^\s*(?:(?:just\s+)?test(?:ing)?(?:\s+[\w.-]+){0,4}|ping|hello|hi|hey)"
    r"\s*[.!?]*\s*$",
    re.IGNORECASE,
)
_SHORT_TEST_REPLY = (
    "Portal is online and responding. What would you like me to help with?"
)
_EMPTY_REPLY = (
    "I couldn't produce a useful response to that request. Please try again or "
    "tell me what you'd like me to do differently."
)
# A final reply that only repeats the owner's message is compared, and held
# while streaming, only when both texts are at most this many characters.
_MAX_ECHO_CHARS = 8192
_INTERACTIVE_DELIVERY_CONTRACT = (
    "\n\n[ODS Portal delivery requirement: Answer the owner's complete message above. "
    "If it asks for exact text, copy that full exact text. Do not answer with a "
    "generic acknowledgement. Do not output NO_REPLY.]"
)
_HOST_INSPECTION_SCOPE = re.compile(
    r"\b(?:computer|host|laptop|machine|system)\b",
    re.IGNORECASE,
)
_HOST_INSPECTION_INTENT = re.compile(
    r"\b(?:check|describe|inspect|list|report|show|tell|verify)\b",
    re.IGNORECASE,
)
_WORKSPACE_MUTATION_SCOPE = re.compile(
    r"(?:/workspace(?:/[A-Za-z0-9._/-]+)?|\b(?:directory|directories|file|files)\b)",
    re.IGNORECASE,
)
_WORKSPACE_MUTATION_INTENT = re.compile(
    r"\b(?:add|build|change|create|edit|generate|implement|make|modify|patch|"
    r"save|update|write)\b",
    re.IGNORECASE,
)
_RUN_COMMAND_AND_WAIT = re.compile(
    r"\b(?:run|execute)\b[\s\S]{0,512}\bcommand\b[\s\S]{0,4096}"
    r"\b(?:wait|finish|complete|terminal|real\s+result)\b",
    re.IGNORECASE,
)
_EXACT_SINGLE_LINE_FILE = re.compile(
    r"\bcreate\s+(?:the\s+)?file\s+"
    r"(?P<path>(?:/workspace/)?[A-Za-z0-9_-][A-Za-z0-9._-]*"
    r"(?:/[A-Za-z0-9_-][A-Za-z0-9._-]*)*)"
    r"(?:\s+in\s+(?:the|your)\s+writable\s+workspace)?"
    r"\s+with\s+exactly\s+this\s+"
    r"single\s+line\s+followed\s+by\s+(?:a|one)\s+newline:\s*"
    r"(?P<content>[^\r\n]{1,4096}?)(?=\s+Then\b)",
    re.IGNORECASE,
)
_WORKSPACE_MUTATION_ROUTE = (
    "\n[ODS Portal workspace task route: Perform the requested workspace mutation "
    "before verification. When tool_call is visible, use it with id write and normal "
    "write args for every new file you author. edit cannot create a file and requires a non-empty "
    "oldText copied from an existing file. Use edit or apply_patch only after reading "
    "an existing file. Then use exec only for "
    "readback, tests, the requested digest, or copies of existing files: make copies and "
    "JSON maps of file contents with one short command that reads the real files, such as "
    "cp or python3 with json.dump, never by re-typing them. Do not repeatedly list directories "
    "or hash proposed text instead of the created file.]"
)
_RUN_COMMAND_AND_WAIT_ROUTE = (
    "\n[ODS Portal command completion route: Call exec exactly once for the owner's "
    "command. If exec returns a running process session, do not call exec again. "
    "Use the visible tool_call control with id process and args containing action "
    "poll plus that exact returned sessionId, and keep polling only that session "
    "until its terminal output is available. Report the real terminal output; do "
    "not simulate, shorten, or restart the command.]"
)
_HOST_ACTION_RULES = (
    (re.compile(r"\b(?:operating\s+system|os|platform)\b", re.IGNORECASE), "host.os-release"),
    (re.compile(r"\bkernel\b", re.IGNORECASE), "host.kernel"),
    (re.compile(r"\b(?:memory|ram)\b", re.IGNORECASE), "host.memory"),
    (re.compile(r"\b(?:disks?|filesystem|mount(?:ed|s)?|storage)\b", re.IGNORECASE), "host.storage"),
    (re.compile(r"\bprocess(?:es)?\b", re.IGNORECASE), "host.processes"),
    (re.compile(r"\b(?:cpu|processor|architecture)\b", re.IGNORECASE), "host.cpu"),
    (re.compile(r"\b(?:gpu|graphics(?:\s+(?:card|processor))?|video\s+card)\b", re.IGNORECASE), "host.gpu"),
    (re.compile(r"\b(?:hostname|identity)\b", re.IGNORECASE), "host.identity"),
    (re.compile(r"\buptime\b", re.IGNORECASE), "host.uptime"),
    (re.compile(r"\bservices?\b", re.IGNORECASE), "host.services"),
    (re.compile(r"\b(?:listening\s+ports?|open\s+ports?)\b", re.IGNORECASE), "host.listening-ports"),
    (re.compile(r"\b(?:network\s+addresses?|ip\s+addresses?)\b", re.IGNORECASE), "host.network-addresses"),
    (re.compile(r"\b(?:network\s+routes?|routing\s+table)\b", re.IGNORECASE), "host.network-routes"),
    (re.compile(r"\btailscale\b", re.IGNORECASE), "host.tailscale"),
)
_NETWORK_DISCLOSURE_EXCLUSION = re.compile(
    r"\b(?:do\s+not|don't|never|must\s+not|should\s+not)\s+"
    r"(?:include|report|show|list|reveal|disclose|expose)\b"
    r"[^.!?;\n]{0,120}\b(?:network(?:\s+(?:location|details?))?|"
    r"interfaces?|addresses?|ip\s+addresses?)\b",
    re.IGNORECASE,
)
_ADDRESS_BEARING_HOST_ACTIONS = {
    "host.network-addresses",
    "host.network-routes",
    "host.listening-ports",
}
_CANCEL_EVENTS_KEY = web.AppKey("pixel_cancel_events", dict)
_CHAT_ACTIVITY_KEY = web.AppKey("pixel_chat_activity", dict)
_ACTIVE_REQUESTS_KEY = web.AppKey("pixel_active_requests", set)
_COMPACTIONS_KEY = web.AppKey("pixel_compactions", dict)
_TRANSITION_GATE_KEY = web.AppKey("pixel_transition_gate", TransitionGate)
_IMAGE_WORK_KEY = web.AppKey("pixel_image_work", ImageWorkBudget)


def _validate_config() -> str:
    """Return the raw bearer token after validating it is well-formed.

    Exits with a non-zero code if the token is missing/blank/oversized.
    """
    if not _BEARER_TOKEN or _BEARER_TOKEN != _BEARER_TOKEN.strip():
        print("FATAL: PIXEL_OPENWEBUI_KEY is not set or blank", file=sys.stderr)
        sys.exit(1)
    if len(_BEARER_TOKEN) < 32 or len(_BEARER_TOKEN) > 4096 or any(ord(ch) < 33 for ch in _BEARER_TOKEN):
        print("FATAL: PIXEL_OPENWEBUI_KEY has an invalid length or character", file=sys.stderr)
        sys.exit(1)
    return _BEARER_TOKEN


def _validate_preview_config() -> str:
    if (
        not _PREVIEW_BEARER_TOKEN
        or _PREVIEW_BEARER_TOKEN != _PREVIEW_BEARER_TOKEN.strip()
        or len(_PREVIEW_BEARER_TOKEN) < 32
        or len(_PREVIEW_BEARER_TOKEN) > 4096
        or any(ord(ch) < 33 for ch in _PREVIEW_BEARER_TOKEN)
    ):
        print("FATAL: PIXEL_PREVIEW_PROXY_KEY is invalid", file=sys.stderr)
        sys.exit(1)
    return _PREVIEW_BEARER_TOKEN


config_token = _validate_config()
preview_proxy_token = _validate_preview_config()


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _constant_time_compare(a: str, b: str) -> bool:
    return hmac.compare_digest(a.encode("utf-8", "replace"),
                               b.encode("utf-8", "replace"))


def _check_auth(request: web.Request):
    """Return a 401 Response on failure, or None on success."""
    auth = request.headers.get("Authorization", "")
    if not auth.startswith("Bearer "):
        return web.json_response({"error": "unauthorized"}, status=401)
    token = auth[len("Bearer "):]
    if not _constant_time_compare(token, config_token):
        return web.json_response({"error": "unauthorized"}, status=401)
    return None


def _check_preview_auth(request: web.Request):
    auth = request.headers.get("Authorization", "")
    if not auth.startswith("Bearer "):
        return web.json_response({"error": "unauthorized"}, status=401)
    token = auth[len("Bearer "):]
    if not _constant_time_compare(token, preview_proxy_token):
        return web.json_response({"error": "unauthorized"}, status=401)
    return None


def _sanitize_headers(headers: dict) -> dict:
    """Strip blocked/hop-by-hop headers and anything not on the safe list."""
    out = {}
    for name, value in headers.items():
        low = name.lower()
        if low.startswith("x-openclaw-") or low in _HOP_BY_HOP or low not in _SAFE_HEADERS:
            continue
        out[name] = value
    return out


def _rewrite_json_model(raw: bytes, response_model: str = _LEGACY_MODEL) -> bytes:
    """Rewrite exact JSON ``model`` fields without altering assistant text."""
    try:
        parsed = json.loads(raw)
    except (json.JSONDecodeError, ValueError):
        return raw

    def _walk(obj):
        if isinstance(obj, list):
            return [_walk(v) for v in obj]
        if isinstance(obj, dict):
            return {
                k: (response_model if k == "model" and v == _UPSTREAM_REWRITE else _walk(v))
                for k, v in obj.items()
            }
        return obj

    return json.dumps(_walk(parsed)).encode("utf-8")


def _latest_user_text(data: dict) -> str:
    messages = data.get("messages")
    if not isinstance(messages, list):
        return ""
    for message in reversed(messages):
        if isinstance(message, dict) and message.get("role") == "user":
            return _message_text(message.get("content")).strip()
    return ""


def _empty_reply_fallback(data: dict) -> str:
    text = _latest_user_text(data)
    if len(text) <= 160 and _SHORT_TEST_MESSAGE.fullmatch(text):
        return _SHORT_TEST_REPLY
    return _EMPTY_REPLY


def _positive_host_inspection_clauses(text: str) -> list[str]:
    """Select requested host facts without reviving excluded or historical ones."""
    if not _HOST_INSPECTION_SCOPE.search(text):
        return []
    clauses = re.split(
        r"[.!?;\n]+|,\s*(?=(?:and\s+then|but|however|instead|then)\b)|"
        r"\b(?:but|however|instead)\s+|"
        r"\band\s+(?=(?:do\s+not|don['\u2019]t|never|avoid|skip|omit|exclude)\b)",
        text,
        flags=re.IGNORECASE,
    )
    negation = re.compile(
        r"^\s*(?:(?:and|but|then)\s+)?(?:please\s+)?"
        r"(?:do\s+not|don['\u2019]t|never|must\s+not|should\s+not|"
        r"avoid|skip|omit|exclude|no)\b",
        re.IGNORECASE,
    )
    return [
        clause for clause in clauses
        if not negation.search(clause)
        and _HOST_INSPECTION_INTENT.search(clause)
        and (_HOST_INSPECTION_SCOPE.search(clause)
             or any(pattern.search(clause) for pattern, _ in _HOST_ACTION_RULES))
    ]


def _workspace_mutation_positions(text: str) -> set[int]:
    """Find positive owner directives for coaching, not tool authorization."""
    def mask_content(match):
        value = match.group(0)
        # A quoted destination is still a path; other quoted bytes are data.
        if re.fullmatch(r"['\"`](/workspace(?:/[A-Za-z0-9._/-]+)?)['\"`]", value):
            return " " + value[1:-1] + " "
        return "".join("\n" if char == "\n" else " " for char in value)

    # A backslash escapes any character, a line break included, and an open
    # quote may end in one. Every quote can then match to the end of the
    # text, which keeps the scan linear (a failed match per quote made it
    # quadratic in the length of the owner text).
    instructions = re.sub(
        r"```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|(?m:^\s*>[^\n]*)|"
        r"`[^`\n]*`|\"(?:\\[\s\S]|[^\"\\])*(?:\"|\\?\Z)|"
        r"(?<!\w)'(?:\\[\s\S]|[^'\\])*(?:'|\\?\Z)|"
        r"\u201c[^\u201d]*(?:\u201d|$)|(?<!\w)\u2018[^\u2019]*(?:\u2019|$)",
        mask_content, text,
    )
    negated = re.compile(
        r"^\s*(?:please\s+)?(?:do\s+not|don['\u2019]t|never|must\s+not|"
        r"should\s+not|avoid|skip|omit|exclude|no)\b", re.IGNORECASE,
    )
    directive = re.compile(
        r"(?:^|\band\s+)(?:(?:please|now|first|next|also)\s+)*"
        r"(?:(?:can|could|would|will)\s+you\s+(?:please\s+)?|"
        r"I\s+(?:want|need)\s+you\s+to\s+|you\s+(?:may|can|should|must)\s+)?"
        r"(?P<verb>" + _WORKSPACE_MUTATION_INTENT.pattern + r")", re.IGNORECASE,
    )
    positions = set()
    for clause in re.finditer(
        r"(?:^|[.!?;\n]|\b(?:but|however|instead|then)\b)\s*"
        r"(?P<clause>.*?)(?=$|[.!?;\n]|\b(?:but|however|instead|then)\b)",
        instructions, re.IGNORECASE,
    ):
        value = clause.group("clause")
        # A file mentioned in an earlier read-only clause does not turn a
        # later "write the answer" directive into a workspace mutation.
        if _WORKSPACE_MUTATION_SCOPE.search(value) and not negated.search(value):
            positions.update(clause.start("clause") + match.start("verb")
                             for match in directive.finditer(value))
    return positions


def _with_interactive_delivery_contract(data: dict) -> dict:
    """Append the ODS delivery contract to the latest user content.

    OpenClaw's generic system prompt documents ``NO_REPLY`` for asynchronous
    channel turns. Small local models can over-select that sentinel even though
    Pixel's later system overlay forbids it for owner-authored webchat. Keeping
    the correction adjacent to the current user instruction gives every model
    the same first-turn contract without retrying (and potentially repeating)
    a tool-using operation.
    """
    owner_text = _latest_user_text(data)
    contract = _INTERACTIVE_DELIVERY_CONTRACT
    host_clauses = _positive_host_inspection_clauses(owner_text)
    remote_inspection = re.search(
        r"\b(?:reachability|connectivity|ping|probe|resolve|network[ -]peer|"
        r"remote[ -](?:host|hostname|identity)|(?:LAN|network)\s+target)\b",
        owner_text, re.IGNORECASE,
    ) and re.search(r"\b(?:check|inspect|test|verify|ping|probe|resolve)\b", owner_text, re.IGNORECASE) and re.search(
        r"\b(?:LAN|network|SSH|Tailscale|remote|reachability|connectivity)\b", owner_text, re.IGNORECASE,
    )
    if remote_inspection:
        # Guidance is not endpoint authorization. The runtime binds the owner
        # target and permissions. Do not prescribe a local identity receipt as
        # a substitute for a remote operation or force one tool-call sequence.
        contract += (
            "\n[ODS Portal network inspection route: Discover the available "
            "Operations tools using tool_call. Use host.network-peer for bounded "
            "reachability of the owner's explicit endpoint and requested ports. "
            "Keep remote reachability, protocol banners and authenticated remote "
            "identity distinct. A local host identity receipt does not establish "
            "remote identity. Honor exclusions and resolve ambiguous targets "
            "before contact. Complete independently requested local observations "
            "and workspace files in the order the task needs.]"
        )
    elif (
        host_clauses
        and not (_ARTIFACT_DRAFT_PREFIX.search(owner_text) and _ARTIFACT_NOUN.search(owner_text))
    ):
        positive_host_text = " ".join(host_clauses)
        excludes_network_location = bool(_NETWORK_DISCLOSURE_EXCLUSION.search(owner_text))
        actions = [
            action
            for pattern, action in _HOST_ACTION_RULES
            if pattern.search(positive_host_text)
            and not (excludes_network_location and action in _ADDRESS_BEARING_HOST_ACTIONS)
        ]
        route = (
            "\n[ODS Portal host inspection route: Generic sandbox commands and "
            "status projections cannot establish host facts. Use the visible "
            "tool_call Tool Search control for the deferred Operations tools. "
        )
        if actions:
            observe_args = json.dumps({"actions": actions}, separators=(",", ":"))
            route += (
                "Use tool_call with id pixel_ods_host_observe "
                f"and args {observe_args}. This one read-only tool returns the "
                "terminal Operations receipt. "
            )
        else:
            route += (
                "Call tool_call with id pixel_ops_inventory and args {} to select "
                "the matching read-only ods-host actions. "
            )
        route += (
            "After terminal host evidence, continue any separately required ODS "
            "projection or workspace step before answering. Do not use generic "
            "sandbox commands as host evidence.]"
        )
        contract += route
    mutation_positions = _workspace_mutation_positions(owner_text)
    if mutation_positions:
        exact_file = next((match for match in _EXACT_SINGLE_LINE_FILE.finditer(owner_text)
                           if match.start() in mutation_positions), None)
        if exact_file:
            path = exact_file.group("path")
            content = exact_file.group("content") + "\n"
            write_args = json.dumps(
                {"path": path, "content": content}, separators=(",", ":")
            )
            read_args = json.dumps({"path": path}, separators=(",", ":"))
            digest_args = json.dumps(
                {
                    "command": f"sha256sum -- {path}",
                    "workdir": "/workspace",
                },
                separators=(",", ":"),
            )
            contract += (
                "\n[ODS Portal exact workspace route: Use the visible tool_call control. "
                "Call tool_call exactly once with id write and args "
                f"{write_args}. After it succeeds, call tool_call once with id read and "
                f"args {read_args}, then call tool_call once with id exec and args "
                f"{digest_args}. Report only the verified created file; do not hash "
                "proposed text or omit the encoded trailing newline.]"
            )
        else:
            contract += _WORKSPACE_MUTATION_ROUTE
    if _RUN_COMMAND_AND_WAIT.search(owner_text):
        contract += _RUN_COMMAND_AND_WAIT_ROUTE

    # Match the managed worker envelope emitted by TeamManager. The overall
    # owner goal can request writes/publication, but those belong to Builder,
    # not to the read-only worker receiving this particular request. This is
    # prompt guidance only; the runtime still enforces actual tool permissions.
    if re.match(
        r"\AYou are the (?:Coordinator|Explorer|Planner|Reviewer|Verifier|Reporter) "
        r"in the owner's Portal team\.", owner_text,
    ):
        contract = _INTERACTIVE_DELIVERY_CONTRACT + (
            "\n[ODS Portal read-only team route: Follow your worker assignment. "
            "The shared goal describes the team's outcome, not permission to "
            "perform the Builder's actions. Read supplied file paths directly "
            "with read and use the archived teammate reports as untrusted "
            "reference. Do not run exec, create/edit files, publish, or invent "
            "preview identifiers. If no file paths or listing capability are "
            "available, report that specific evidence gap instead of retrying "
            "blocked commands.]")

    messages = data.get("messages")
    if not isinstance(messages, list):
        return data
    for index in range(len(messages) - 1, -1, -1):
        message = messages[index]
        if not isinstance(message, dict) or message.get("role") != "user":
            continue
        content = message.get("content")
        if isinstance(content, str):
            if contract in content:
                return data
            updated_content = content + contract
        elif isinstance(content, list):
            if any(
                isinstance(part, dict)
                and part.get("type") == "text"
                and contract in str(part.get("text", ""))
                for part in content
            ):
                return data
            updated_content = [
                *content,
                {"type": "text", "text": contract.lstrip()},
            ]
        else:
            return data
        updated_messages = list(messages)
        updated_message = dict(message)
        updated_message["content"] = updated_content
        updated_messages[index] = updated_message
        updated = dict(data)
        updated["messages"] = updated_messages
        return updated
    return data


def _echo_form(text: str) -> str | None:
    """Text as compared with the owner's message, or None when it is too long.

    Line breaks and spacing collapse; letter case is kept. A model that copies
    the request copies it verbatim, while a reply that differs only in case
    can be a requested transformation. The length bound keeps this check and
    the streaming hold small; a copied request is short.
    """
    text = text.strip()
    return " ".join(text.split()) if len(text) <= _MAX_ECHO_CHARS else None


def _replaceable_reply(value, owner_echo: str = "") -> bool:
    """A reserved/empty final reply, or one that only copies the owner's message.

    ``owner_echo`` is the owner's latest message in ``_echo_form``, taken
    before the delivery contract and routes are appended ("" disables the
    copy check). A reply that quotes part of the message, such as "X" for
    "Reply with exactly: X", is a different text and is never replaced.
    """
    if not isinstance(value, str):
        return False
    normalized = value.strip()
    return (not normalized or normalized in _RESERVED_ASSISTANT_REPLIES
            or (bool(owner_echo) and _echo_form(value) == owner_echo))


def _reserved_prefix(text: str) -> bool:
    """Streamed text that can still become an empty or reserved reply."""
    normalized = text.strip()
    return not normalized or any(
        reserved.startswith(normalized) for reserved in _RESERVED_ASSISTANT_REPLIES
    )


def _replaceable_prefix(text: str, owner_echo: str = "") -> bool:
    """Streamed text that can still become a replaceable final reply."""
    if _reserved_prefix(text):
        return True
    form = _echo_form(text) if owner_echo else None
    return form is not None and owner_echo.startswith(form)


def _rewrite_json_response(raw: bytes, fallback: str,
                           response_model: str = _LEGACY_MODEL,
                           owner_echo: str = "") -> bytes:
    """Rewrite model identity and replace only an exact reserved/empty or copied final reply."""
    try:
        parsed = json.loads(_rewrite_json_model(raw, response_model))
    except (json.JSONDecodeError, ValueError):
        return raw
    choices = parsed.get("choices") if isinstance(parsed, dict) else None
    if isinstance(choices, list):
        for choice in choices:
            if not isinstance(choice, dict):
                continue
            message = choice.get("message")
            if isinstance(message, dict) and _replaceable_reply(message.get("content"), owner_echo):
                message["content"] = fallback
    return json.dumps(parsed).encode("utf-8")


def _normalize_sse_line(line: bytes) -> bytes:
    # CRLF and the optional space after "data:" carry the same SSE field.
    line = line.removesuffix(b"\r")
    if line.startswith(b"data:") and not line.startswith(b"data: "):
        line = b"data: " + line[5:]
    return line


def _sse_event(line: bytes):
    if not line.startswith(b"data: ") or line == b"data: [DONE]":
        return None, None, None
    try:
        event = json.loads(line[6:])
    except (json.JSONDecodeError, ValueError, UnicodeDecodeError):
        return None, None, None
    choices = event.get("choices") if isinstance(event, dict) else None
    if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
        return event, None, None
    choice = choices[0]
    delta = choice.get("delta")
    content = delta.get("content") if isinstance(delta, dict) else None
    return event, content if isinstance(content, str) else None, choice.get("finish_reason")


def _fallback_sse_line(template: dict, fallback: str, *, finished: bool) -> bytes:
    event = {
        key: template[key]
        for key in ("id", "object", "created", "model")
        if key in template
    }
    event["choices"] = [{
        "index": 0,
        "delta": {} if finished else {"content": fallback},
        "finish_reason": "stop" if finished else None,
    }]
    return b"data: " + json.dumps(event).encode("utf-8")


async def _read_bounded(content, limit: int) -> bytes:
    chunks = []
    total = 0
    async for chunk in content.iter_any():
        total += len(chunk)
        if total > limit:
            raise ValueError("response too large")
        chunks.append(chunk)
    return b"".join(chunks)


def _message_text(content) -> str:
    """Extract text from one OpenAI-compatible message content value."""
    if isinstance(content, str):
        return content
    if not isinstance(content, list):
        return ""
    parts = []
    for part in content:
        if not isinstance(part, dict):
            continue
        value = part.get("text")
        if not isinstance(value, str):
            value = part.get("content")
        if isinstance(value, str):
            parts.append(value)
    return "\n".join(parts)


# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------

async def _ingress_ready() -> bool:
    connector = UnixConnector(path=_SOCKET_PATH)
    timeout = ClientTimeout(total=3, sock_connect=2, sock_read=2)
    try:
        async with ClientSession(connector=connector, timeout=timeout) as session:
            async with session.get("http://pixel-upstream/health") as resp:
                if resp.status != 200:
                    raise ConnectionError("ingress not ready")
                body = await resp.json(content_type=None)
                if body != {"status": "ok"}:
                    raise ConnectionError("ingress not ready")
    except Exception:
        return False
    return True


async def handle_health(_request: web.Request):
    """Report ready only when the private host ingress and gateway are ready."""
    if not await _ingress_ready():
        return web.json_response({"status": "unavailable"}, status=503)
    return web.json_response({"status": "ok"})


async def handle_models(request: web.Request):
    fail = _check_auth(request)
    # aiohttp Response objects may be falsey, including an intentional 401.
    # Check the sentinel explicitly or an unauthenticated request can fall
    # through to the protected handler.
    if fail is not None:
        return fail
    if not await _ingress_ready():
        return web.json_response({"error": "service unavailable"}, status=503)

    data = [{"id": _PUBLIC_MODEL, "name": "Portal", "object": "model", "owned_by": "ods"}]
    return web.json_response({"object": "list", "data": data})


async def handle_runtime_identity(request: web.Request):
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.query_string:
        return web.json_response({"error": "invalid request"}, status=400)
    try:
        connector = UnixConnector(path=_SOCKET_PATH)
        timeout = ClientTimeout(total=3, sock_connect=2, sock_read=2)
        async with ClientSession(connector=connector, timeout=timeout) as session:
            async with session.get("http://pixel-upstream/v1/runtime-identity", allow_redirects=False) as response:
                if response.status != 200 or response.content_type != "application/json":
                    raise ValueError("unavailable")
                raw = bytearray()
                async for chunk in response.content.iter_chunked(4096):
                    raw.extend(chunk)
                    if len(raw) > 8192:
                        raise ValueError("too large")
                result = project_runtime_identity(strict_json(bytes(raw)))
    except (ValueError, TypeError, OSError, asyncio.TimeoutError, ClientError, RecursionError):
        result = unknown_runtime_identity()
    return web.json_response(result, headers={"Cache-Control": "no-store"})


_EXAMPLE_PROJECT_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
_EXAMPLE_PREVIEW_KEYS = frozenset(("bytes", "entrySha256", "files", "kind", "port", "relativeDirectory",
                                   "schemaVersion", "sha256", "siteId", "url"))
_SHA256 = re.compile(r"[a-f0-9]{64}")
_EXAMPLE_REFUSALS = {404: "example-project-unavailable", 409: "example-project-not-previewable",
                     422: "example-project-not-playable"}


def _example_projects(value) -> dict:
    """The shipped example projects present in the owner's workspace."""
    projects = value.get("projects") if isinstance(value, dict) else None
    if (not isinstance(value, dict) or set(value) != {"schemaVersion", "projects"}
            or type(value["schemaVersion"]) is not int or value["schemaVersion"] != 1
            or not isinstance(projects, list) or len(projects) > 8
            or any(not isinstance(name, str) or not _EXAMPLE_PROJECT_NAME.fullmatch(name) for name in projects)
            or len(set(projects)) != len(projects)):
        raise ValueError("invalid example projects")
    return {"schemaVersion": 1, "projects": list(projects)}


def _example_preview(value, name: str) -> dict:
    """One verified receipt for Playground/<name>, exactly as a model run delivers it."""
    preview = value.get("preview") if isinstance(value, dict) else None

    def integer(key, low, high):
        return type(preview.get(key)) is int and low <= preview[key] <= high

    if (not isinstance(value, dict) or set(value) != {"schemaVersion", "preview"}
            or type(value["schemaVersion"]) is not int or value["schemaVersion"] != 1
            or not isinstance(preview, dict) or set(preview) != _EXAMPLE_PREVIEW_KEYS
            or type(preview["schemaVersion"]) is not int or preview["schemaVersion"] != 1
            or preview["kind"] != "ods-pixel-workspace-preview"
            or preview["relativeDirectory"] != f"Playground/{name}"
            or not isinstance(preview["sha256"], str) or not _SHA256.fullmatch(preview["sha256"])
            or not isinstance(preview["entrySha256"], str) or not _SHA256.fullmatch(preview["entrySha256"])
            or preview["siteId"] != f"site-{preview['sha256'][:24]}"
            or not integer("port", 1, 65535) or not integer("files", 1, 128) or not integer("bytes", 1, 16 * 1024 * 1024)
            or preview["url"] != f"http://{preview['siteId']}.localhost:{preview['port']}/{preview['siteId']}/"):
        raise ValueError("invalid example preview")
    return {"schemaVersion": 1, "preview": {key: preview[key] for key in sorted(_EXAMPLE_PREVIEW_KEYS)}}


async def handle_example_projects(request: web.Request):
    """List the shipped example projects, or open one with no model run.

    Portal's sidebar shows Playground/elf-of-doom like any other project while
    its folder exists. Opening it asks the host to publish that existing
    folder through the create-only preview service; nothing is written to the
    workspace and no model runs.
    """
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.query_string:
        return web.json_response({"error": "invalid request"}, status=400)
    opening = request.method == "POST"
    name = None
    if opening:
        if request.content_type != "application/json":
            return web.json_response({"error": "Content-Type must be application/json"}, status=415)
        try:
            data = strict_json(await _read_bounded(request.content, _MAX_CANCEL_BODY))
            if (not isinstance(data, dict) or set(data) != {"name"} or not isinstance(data["name"], str)
                    or not _EXAMPLE_PROJECT_NAME.fullmatch(data["name"])):
                raise ValueError("invalid example project request")
            name = data["name"]
        except (ValueError, TypeError, UnicodeError, RecursionError):
            return web.json_response({"error": "invalid example project request"}, status=400)
    try:
        timeout = ClientTimeout(total=38 if opening else 4, sock_connect=2)
        async with ClientSession(connector=UnixConnector(path=_SOCKET_PATH), timeout=timeout) as session:
            upstream_request = (session.post("http://pixel-upstream/v1/example-projects", json={"name": name},
                                             headers={"Accept": "application/json"}, allow_redirects=False)
                                if opening else
                                session.get("http://pixel-upstream/v1/example-projects",
                                            headers={"Accept": "application/json"}, allow_redirects=False))
            async with upstream_request as upstream:
                # 404: the folder is gone. 409: the host refused files in it.
                # 422: a folder of that name is there but cannot open as the example.
                if opening and upstream.status in _EXAMPLE_REFUSALS:
                    return web.json_response({"error": _EXAMPLE_REFUSALS[upstream.status]}, status=upstream.status,
                                             headers={"Cache-Control": "no-store"})
                if upstream.status != 200 or upstream.content_type != "application/json":
                    raise ValueError("unavailable")
                value = strict_json(await _read_bounded(upstream.content, 8192))
        result = _example_preview(value, name) if opening else _example_projects(value)
    except (ValueError, TypeError, UnicodeError, RecursionError, OSError, asyncio.TimeoutError, ClientError):
        error = "example-project-preview-unavailable" if opening else "example-projects-unavailable"
        return web.json_response({"error": error}, status=503, headers={"Cache-Control": "no-store"})
    return web.json_response(result, headers={"Cache-Control": "no-store"})


async def handle_activity(request: web.Request):
    """Return only the number of in-flight turns for safe model coordination."""
    fail = _check_auth(request)
    if fail is not None:
        return fail
    streams = len(request.app[_ACTIVE_REQUESTS_KEY])
    return web.json_response({"active": streams > 0, "streams": streams})


async def handle_chat_activity(request: web.Request):
    """Project only the requested opaque chat's witnessed lifecycle."""
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"}, status=415)
    if request.query_string or (request.content_length and request.content_length > _MAX_CANCEL_BODY):
        return web.json_response({"error": "invalid activity request"}, status=400)
    try:
        raw = await request.read()
        if len(raw) > _MAX_CANCEL_BODY:
            raise ValueError("request too large")
        data = strict_json(raw)
        if (not isinstance(data, dict) or set(data) != {"user"}
                or not isinstance(data["user"], str) or not _SAFE_CHAT_ID.fullmatch(data["user"])):
            raise ValueError("invalid activity request")
    except (ValueError, UnicodeDecodeError, TypeError):
        return web.json_response({"error": "invalid activity request"}, status=400)
    chat_id = data["user"]
    state = "active" if request.app[_CANCEL_EVENTS_KEY].get(chat_id) else request.app[_CHAT_ACTIVITY_KEY].get(chat_id, "unknown")
    return web.json_response({"state": state}, headers={"Cache-Control": "no-store"})


async def handle_chat_settle(request: web.Request):
    """Ask the ingress to settle a chat it proves idle; never stop a run.

    A restart can leave a turn's outcome unknown while nothing runs any more.
    The ingress proves that under its history lock and records the turn as
    interrupted. A stream still passing through this edge, a held lock or a
    busy native session answers "active" and nothing changes.
    """
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"}, status=415)
    if request.query_string or (request.content_length and request.content_length > _MAX_CANCEL_BODY):
        return web.json_response({"error": "invalid settle request"}, status=400)
    try:
        raw = await request.read()
        if len(raw) > _MAX_CANCEL_BODY:
            raise ValueError("request too large")
        data = strict_json(raw)
        if (not isinstance(data, dict) or set(data) != {"user"}
                or not isinstance(data["user"], str) or not _SAFE_CHAT_ID.fullmatch(data["user"])):
            raise ValueError("invalid settle request")
    except (ValueError, UnicodeDecodeError, TypeError):
        return web.json_response({"error": "invalid settle request"}, status=400)
    chat_id = data["user"]
    if request.app[_CANCEL_EVENTS_KEY].get(chat_id):
        return web.json_response({"state": "active"}, headers={"Cache-Control": "no-store"})
    try:
        connector = UnixConnector(path=_SOCKET_PATH)
        # The ingress bounds its own native read at 5 s under the history lock.
        timeout = ClientTimeout(total=8, sock_connect=2, sock_read=7)
        async with ClientSession(connector=connector, timeout=timeout) as session:
            async with session.post(
                "http://pixel-upstream/v1/chat/settle",
                json={"user": chat_id},
                headers={"Content-Type": "application/json", "Accept": "application/json"},
            ) as resp:
                if resp.status != 200 or "application/json" not in resp.headers.get("Content-Type", "").lower():
                    raise ValueError("settle unconfirmed")
                result = strict_json(await _read_bounded(resp.content, _MAX_CANCEL_RESPONSE_BYTES))
        if (not isinstance(result, dict) or set(result) != {"state"}
                or result["state"] not in ("settled", "active")):
            raise ValueError("invalid settle receipt")
    except (ConnectionError, OSError, asyncio.TimeoutError, ClientError, ValueError, TypeError,
            UnicodeError, RecursionError):
        return web.json_response({"error": "Portal settle unconfirmed"}, status=502)
    if result["state"] == "settled" and not request.app[_CANCEL_EVENTS_KEY].get(chat_id):
        _remember_chat_activity(request.app, chat_id, "terminal")
    return web.json_response({"state": result["state"]}, headers={"Cache-Control": "no-store"})


async def _context_upstream(data, *, compact=False):
    connector = UnixConnector(path=_SOCKET_PATH)
    timeout = ClientTimeout(total=18, sock_connect=2, sock_read=16)
    async with ClientSession(connector=connector, timeout=timeout) as session:
        async with session.post(f"http://pixel-upstream/v1/chat/{'compact' if compact else 'context'}",
                                json=data, headers={"Content-Type": "application/json", "Accept": "application/json"}) as response:
            if response.status in {409, 423, 429}:
                raise GateError("context_busy", response.status)
            if response.status != 200 or "application/json" not in response.headers.get("Content-Type", "").lower():
                raise ValueError("invalid context response")
            return project_context(strict_json(await _read_bounded(response.content, 16 * 1024)))


def _compact_terminal(result, request_id):
    operation = result["compaction"]
    # A restarted native process cannot still be running this job. Its outcome
    # remains unknown; releasing admission is not a claim of successful compact.
    return (operation.get("requestId") == request_id and (
        operation["status"] in {"completed", "skipped", "failed"}
        or operation["status"] == "unknown" and operation.get("reason") == "runtime-restarted"))


async def _watch_compaction(app, identity, token):
    # Native work outlives the initiating HTTP response. Keep model transitions
    # fenced until a matching terminal receipt is observed, including after a
    # temporary transport failure. Shutdown leaves the durable gate interrupted.
    try:
        while True:
            await asyncio.sleep(2)
            try:
                result = await _context_upstream({"user": identity[0]})
            except Exception:
                continue
            if _compact_terminal(result, identity[1]):
                await app[_TRANSITION_GATE_KEY].finish(token)
                app[_COMPACTIONS_KEY].pop(identity, None)
                return
    except asyncio.CancelledError:
        return


async def handle_chat_context(request: web.Request):
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"}, status=415)
    compact = request.path == "/v1/chat/compact"
    try:
        if request.query_string:
            raise ValueError("query not allowed")
        data = strict_json(await _read_bounded(request.content, 512))
        keys = {"user", "request_id"} if compact else {"user"}
        if (not isinstance(data, dict) or set(data) != keys
                or any(not isinstance(item, str) or not _SAFE_CHAT_ID.fullmatch(item) for item in data.values())):
            raise ValueError("invalid context request")
    except (ValueError, TypeError, UnicodeError, RecursionError):
        return web.json_response({"error": "invalid context request"}, status=400)
    token = None
    identity = (data["user"], data.get("request_id"))
    existing = request.app[_COMPACTIONS_KEY].get(identity)
    if compact and existing is None:
        if request.app[_CANCEL_EVENTS_KEY].get(data["user"]) or any(
                user == data["user"] for user, _ in request.app[_COMPACTIONS_KEY]):
            return web.json_response({"error": "context_busy"}, status=423)
        token = object()
        try:
            await request.app[_TRANSITION_GATE_KEY].admit(token)
        except GateError as exc:
            return web.json_response({"error": exc.reason}, status=exc.status)
        # Reserve before awaiting upstream so a duplicate POST cannot create a
        # second lifetime token. Native ingress also deduplicates by request ID.
        request.app[_COMPACTIONS_KEY][identity] = (token, None)
    try:
        result = await _context_upstream(data, compact=compact)
        if compact and token is not None and (
                _compact_terminal(result, data["request_id"])
                or result["status"] != "unavailable" and (
                    result["compaction"].get("requestId") != data["request_id"]
                    or result["compaction"]["status"] == "idle")):
            # A missing session or a busy runtime can reject admission with a
            # valid status projection. There is no job to watch in that case.
            await request.app[_TRANSITION_GATE_KEY].finish(token)
            request.app[_COMPACTIONS_KEY].pop(identity, None)
            token = None
        return web.json_response(result, headers={"Cache-Control": "no-store"})
    except GateError as exc:
        if token is not None:
            await request.app[_TRANSITION_GATE_KEY].finish(token)
            request.app[_COMPACTIONS_KEY].pop(identity, None)
            token = None
        return web.json_response({"error": exc.reason}, status=exc.status)
    except Exception:
        return web.json_response({"error": "context status unavailable"}, status=502)
    finally:
        if token is not None:
            task = asyncio.create_task(_watch_compaction(request.app, identity, token))
            request.app[_COMPACTIONS_KEY][identity] = (token, task)


async def handle_chat_images_delete(request: web.Request):
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.content_type != "application/json" or request.query_string:
        return web.json_response({"error": "invalid image deletion request"}, status=400)
    try:
        data = strict_json(await _read_bounded(request.content, 512))
        if (not isinstance(data, dict) or set(data) != {"user"}
                or not isinstance(data["user"], str) or not _SAFE_CHAT_ID.fullmatch(data["user"])):
            raise ValueError("invalid request")
    except (ValueError, TypeError, UnicodeError, RecursionError):
        return web.json_response({"error": "invalid image deletion request"}, status=400)
    if request.app[_CANCEL_EVENTS_KEY].get(data["user"]) or any(user == data["user"] for user, _ in request.app[_COMPACTIONS_KEY]):
        return web.json_response({"error": "conversation_busy"}, status=409)
    try:
        async with ClientSession(connector=UnixConnector(path=_SOCKET_PATH), timeout=ClientTimeout(total=18)) as session:
            async with session.post("http://pixel-upstream/v1/chat/images-delete", json=data,
                                    headers={"Content-Type": "application/json", "Accept": "application/json"}) as upstream:
                if upstream.status in {409, 423, 429}:
                    return web.json_response({"error": "conversation_busy"}, status=upstream.status)
                if upstream.status != 200 or "application/json" not in upstream.headers.get("Content-Type", "").lower():
                    raise ValueError("invalid deletion receipt")
                receipt = strict_json(await _read_bounded(upstream.content, 256))
                if (receipt != {"schemaVersion": 1, "deleted": True}
                        or type(receipt.get("schemaVersion")) is not int or receipt.get("deleted") is not True):
                    raise ValueError("invalid deletion receipt")
        return web.json_response(receipt, headers={"Cache-Control": "no-store"})
    except Exception:
        return web.json_response({"error": "conversation image deletion unconfirmed; retry"}, status=503)


def _finish_chat_activity(app, chat_id, cancel_event, terminal):
    active = app[_CANCEL_EVENTS_KEY].get(chat_id)
    if active is None:
        return
    active.discard(cancel_event)
    history = app[_CHAT_ACTIVITY_KEY]
    # One uncertain sibling means this batch cannot be called terminal.
    state = "unknown" if not terminal or history.get(chat_id) == "unknown" else "terminal"
    if not active:
        app[_CANCEL_EVENTS_KEY].pop(chat_id, None)
    _remember_chat_activity(app, chat_id, state)


def _remember_chat_activity(app, chat_id, state):
    history = app[_CHAT_ACTIVITY_KEY]
    history[chat_id] = state
    # No chat content or request IDs persist; eviction/restart means unknown.
    for previous in tuple(history):
        if len(history) <= 1024:
            break
        if previous not in app[_CANCEL_EVENTS_KEY]:
            history.pop(previous, None)


def _access_transport():
    transport = os.environ.get('PIXEL_ACCESS_TRANSPORT', 'unix')
    if transport == 'unix':
        return UnixConnector(path=_SOCKET_PATH), 'http://pixel-upstream'
    if transport == 'docker-desktop-host':
        port = os.environ.get('PIXEL_NATIVE_ACCESS_PORT', '18790')
        if not re.fullmatch(r'[1-9][0-9]{0,4}', port) or int(port) > 65535:
            raise ValueError('invalid-native-access-port')
        return TCPConnector(), 'http://host.docker.internal:' + port
    raise ValueError('invalid-access-transport')


async def handle_access_mode(request: web.Request):
    fail = _check_preview_auth(request)
    if fail is not None:
        return fail
    # Sharing the chat key would let ordinary inference callers grant access.
    if _constant_time_compare(config_token, preview_proxy_token):
        return web.json_response({'error': 'owner-auth-unavailable'}, status=503)
    if request.query_string:
        return web.json_response({'error': 'invalid-request'}, status=400)
    data = None
    if request.method == 'POST':
        if request.content_type != 'application/json':
            return web.json_response({'error': 'invalid-content-type'}, status=415)
        try:
            data = strict_json(await _read_bounded(request.content, 1024))
            if not valid_access_change(data):
                raise ValueError()
        except (ValueError, OSError, RecursionError):
            return web.json_response({'error': 'invalid-request'}, status=400)
    elif request.can_read_body:
        return web.json_response({'error': 'invalid-request'}, status=400)
    try:
        connector, origin = _access_transport()
        timeout = ClientTimeout(total=308 if data is not None else 21, sock_connect=3)
        async with ClientSession(connector=connector, timeout=timeout, trust_env=False) as session:
            async with session.request(request.method, origin + '/v1/access-mode',
                    json=data, allow_redirects=False,
                    headers={'Authorization': 'Bearer ' + preview_proxy_token}) as response:
                raw = await _read_bounded(response.content, 65536)
                if response.status != 200:
                    # Never retry an ambiguous transition. The controller's
                    # durable journal, not this transport, owns recovery.
                    status = response.status if response.status in (400, 403, 409, 503) else 503
                    return web.json_response({'error': 'access-change-unconfirmed' if data else 'access-service-unavailable'}, status=status)
                value = public_access_status(strict_json(raw))
        return web.json_response(value, headers={'Cache-Control':'no-store'})
    except Exception:
        return web.json_response({'error':'access-service-unavailable'}, status=503)


_CONTROLLER_REASON = re.compile(r'[a-z0-9][a-z0-9-]{0,63}')


def _controller_reason(raw: bytes) -> str | None:
    """The controller's own refusal code, when it is a plain token.

    A code such as model-runtime-mismatch tells the owner what to fix; free
    text (which could carry a path or credential) is never relayed.
    """
    try:
        value = strict_json(raw)
    except (ValueError, RecursionError):
        return None
    code = value.get('error') if isinstance(value, dict) else None
    return code if isinstance(code, str) and _CONTROLLER_REASON.fullmatch(code) else None


async def handle_model_control(request: web.Request):
    """Private model lifecycle control; ordinary chat callers cannot mutate it."""
    fail = _check_preview_auth(request)
    if fail is not None:
        return fail
    if _constant_time_compare(config_token, preview_proxy_token):
        return web.json_response({'error': 'owner-auth-unavailable'}, status=503)
    if request.query_string:
        return web.json_response({'error': 'invalid-request'}, status=400)
    if request.content_type != 'application/json':
        return web.json_response({'error': 'invalid-content-type'}, status=415)
    try:
        data = strict_json(await _read_bounded(request.content, 2048))
        if not valid_model_control(data):
            raise ValueError()
    except (ValueError, OSError, RecursionError):
        return web.json_response({'error': 'invalid-request'}, status=400)
    try:
        connector, origin = _access_transport()
        timeout = ClientTimeout(total=21 if data['operation'] == 'model-status' else 308, sock_connect=3)
        async with ClientSession(connector=connector, timeout=timeout, trust_env=False) as session:
            async with session.post(origin + '/v1/model-control', json=data, allow_redirects=False,
                    headers={'Authorization': 'Bearer ' + preview_proxy_token}) as response:
                raw = await _read_bounded(response.content, 65536)
                if response.status != 200:
                    status = response.status if response.status in (400, 403, 409, 503) else 503
                    return web.json_response({'error': _controller_reason(raw) or 'model-change-unconfirmed'},
                                             status=status)
                value = public_model_control(strict_json(raw))
        return web.json_response(value, headers={'Cache-Control': 'no-store'})
    except Exception:
        # A lost reply does not cancel the controller's durable transaction.
        # Status reconciliation belongs to the caller; mutations are never retried here.
        return web.json_response({'error': 'model-control-unavailable'}, status=503)


async def handle_transition(request: web.Request):
    # Reuse the server-injected Dashboard credential, never the model/chat key.
    # This credential already authenticates the private preview relay and must
    # remain inaccessible to browsers, model text, and generated artifacts.
    fail = _check_preview_auth(request)
    if fail is not None:
        return fail
    if request.query_string:
        return web.json_response({"error": "query parameters are not allowed"}, status=400)
    gate = request.app[_TRANSITION_GATE_KEY]
    if request.method in ("GET", "HEAD"):
        return web.json_response(await gate.status(), headers={"Cache-Control": "no-store"})
    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"}, status=415)
    raw = bytearray()
    try:
        async for chunk in request.content.iter_chunked(512):
            raw.extend(chunk)
            if len(raw) > 1024:
                return web.json_response({"error": "request too large"}, status=413)
        data = strict_json(raw)
    except (ValueError, OSError, RecursionError):
        return web.json_response({"error": "invalid JSON"}, status=400)
    if (not isinstance(data, dict) or set(data) != {"token", "revision"}
            or not all(valid_binding(value) for value in data.values())):
        return web.json_response({"error": "exact token and revision bindings required"}, status=400)
    try:
        operation = request.match_info["operation"]
        if operation == "release":
            result = await gate.release(data["token"], data["revision"])
        else:
            result = await gate.acquire(data["token"], data["revision"], recover=operation == "recover", drain=operation == "drain")
    except GateError as exc:
        return web.json_response({"error": exc.reason}, status=exc.status,
                                 headers={"Cache-Control": "no-store"})
    return web.json_response(result, headers={"Cache-Control": "no-store"})


async def handle_chat_completions(request: web.Request):
    fail = _check_auth(request)
    if fail is not None:
        return fail

    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"},
                                 status=415)

    encodings = request.headers.getall("Content-Encoding", [])
    if encodings and [value.strip().lower() for value in encodings] != ["identity"]:
        return web.json_response({"error": "compressed chat requests are not supported"}, status=415)
    flags = request.headers.getall("X-ODS-Image-Turn", [])
    if flags not in ([], ["1"]):
        return web.json_response({"error": "invalid image envelope"}, status=400)
    image_turn = bool(flags)
    limit = _MAX_IMAGE_BODY if image_turn else _MAX_BODY
    if request.content_length and request.content_length > limit:
        return web.json_response({"error": "request too large"}, status=413)
    lease = request.app[_IMAGE_WORK_KEY].acquire() if image_turn else None
    if image_turn and lease is None:
        return web.json_response({"error": "image processing busy; retry shortly"}, status=429,
                                 headers={"Retry-After": "1", "Cache-Control": "no-store"})
    reservation = [lease]
    try:
        return await _handle_admitted_chat(request, image_turn, reservation, limit)
    finally:
        if reservation[0] is not None:
            reservation[0].release()


def _has_current_images(data):
    messages = data.get("messages") if isinstance(data, dict) else None
    return isinstance(messages, list) and any(
        isinstance(message, dict) and ("images" in message or (
            isinstance(message.get("content"), list) and any(
                isinstance(part, dict) and part.get("type") == "image_url"
                for part in message["content"]))) for message in messages)


class ImageEnvelopeComplexity(ValueError):
    pass


def _check_image_structure(body):
    # 2000 history messages with four two-field references each require fewer
    # than 80000 delimiters. 128 Ki leaves room for the envelope and current
    # message while bounding object/list amplification before JSON allocation.
    structural = depth = 0
    quoted = escaped = False
    for character in body:
        if quoted:
            if escaped:
                escaped = False
            elif character == '\\':
                escaped = True
            elif character == '"':
                quoted = False
        elif character == '"':
            quoted = True
        elif character in '{}[],:':
            structural += 1
            if character in '{[':
                depth += 1
            elif character in '}]':
                depth -= 1
            if structural > 128 * 1024 or depth > 32:
                raise ImageEnvelopeComplexity('image envelope structure limit')
    # Syntax, escapes, duplicate keys and schema remain the JSON decoder's job.


def _parse_image_envelope(body):
    _check_image_structure(body)
    data = strict_json(body)
    del body  # Release encoded source before decoding/hash-checking images.
    route = data.get("image_route") if isinstance(data, dict) else None
    snapshot = data.get("history_snapshot") if isinstance(data, dict) else None
    messages = data.get("messages") if isinstance(data, dict) else None
    if (not isinstance(route, dict) or set(route) != {"routeFingerprint", "unknownConsent"}
            or not valid_binding(route.get("routeFingerprint")) or type(route.get("unknownConsent")) is not bool
            or not isinstance(snapshot, dict) or snapshot.get("schemaVersion") != 2
            or not isinstance(messages, list) or not messages
            or not isinstance(messages[-1], dict) or not messages[-1].get("images")
            or any(_has_current_images({"messages": [message]}) for message in messages[:-1])
            or not valid_history_snapshot(data)):
        raise ValueError("invalid image envelope")
    return data


def _parse_owned_image_envelope(holder):
    # Transfer the sole encoded-source reference to the worker. The HTTP
    # coroutine and executor argument tuple must not retain it during hashing.
    return _parse_image_envelope(holder.pop())


async def _encoded_image_envelope(data):
    # Avoid materializing a full JSON string plus its UTF-8 copy alongside the
    # decoded image/history envelope. Each encoded output chunk stays bounded.
    for token in json.JSONEncoder().iterencode(data):
        for start in range(0, len(token), 32768):
            yield token[start:start + 32768].encode("utf-8")
        await asyncio.sleep(0)


async def _read_image_envelope(content, limit):
    # The internal API uses ensure_ascii=True. Keeping the JSON source ASCII
    # avoids a single literal emoji widening an entire base64 envelope to four
    # bytes per character. JSON escapes still preserve arbitrary Unicode text.
    chunks = []
    pending = bytearray()
    size = 0
    async for chunk in content.iter_any():
        size += len(chunk)
        if size > limit:
            raise ValueError("request too large")
        for offset in range(0, len(chunk), 65536):
            pending.extend(chunk[offset:offset + 65536])
            if len(pending) >= 65536:
                chunks.append(pending.decode("ascii"))
                pending.clear()
    if pending:
        chunks.append(pending.decode("ascii"))
    return "".join(chunks)


async def _handle_admitted_chat(request, image_turn, reservation, limit):

    try:
        # Enforce this route's cap for both Content-Length and chunked bodies.
        # Request.read() otherwise applies aiohttp's default 1 MiB cap first.
        if image_turn:
            async with asyncio.timeout(_IMAGE_BODY_TIMEOUT):
                body = await _read_image_envelope(request.content, limit)
        else:
            body = await _read_bounded(request.content, limit)
    except UnicodeDecodeError:
        return web.json_response({"error": "image envelope requires ASCII-escaped JSON"}, status=400)
    except ValueError:
        return web.json_response({"error": "request too large"}, status=413)
    except TimeoutError:
        return web.json_response({"error": "image request timed out"}, status=408)
    except Exception:
        return web.json_response({"error": "bad request"}, status=400)

    try:
        if image_turn:
            source_holder = [body]
            del body
            data = await reservation[0].run(_parse_owned_image_envelope, source_holder)
        else:
            data = json.loads(body)
    except ImageEnvelopeComplexity:
        return web.json_response({"error": "image envelope structure limit"}, status=413)
    except (json.JSONDecodeError, ValueError, RecursionError):
        return web.json_response({"error": "invalid JSON"}, status=400)

    if not isinstance(data, dict):
        return web.json_response({"error": "JSON object required"}, status=400)
    # Image bytes cannot evade their resource slot by omitting the explicit
    # envelope header. Old text/history-only requests retain their 8 MiB cap.
    if not image_turn and _has_current_images(data):
        if data.get('history_snapshot') is not None or any(
                isinstance(message, dict) and 'images' in message for message in data['messages']):
            return web.json_response({"error": "image envelope required"}, status=400)
        # Preserve the existing small OpenAI multimodal surface without giving
        # it the larger, reference-bound Portal envelope allowance.
        reservation[0] = request.app[_IMAGE_WORK_KEY].acquire()
        if reservation[0] is None:
            return web.json_response({"error": "image processing busy; retry shortly"}, status=429,
                                     headers={"Retry-After": "1", "Cache-Control": "no-store"})
    if not image_turn and not valid_history_snapshot(data):
        return web.json_response({"error": "invalid conversation history"}, status=400)
    if not image_turn:
        del body  # Do not retain a second full encoded envelope through streaming.

    req_model = data.get("model", "")
    if req_model not in _ALLOWED_MODELS:
        return web.json_response({"error": "model not allowed"}, status=400)
    empty_reply_fallback = _empty_reply_fallback(data)
    # The owner's own words, before the delivery contract is appended. A final
    # reply that only repeats them answers nothing and gets the fallback too.
    owner_echo = _echo_form(_latest_user_text(data)) or ""
    upstream_data = _with_interactive_delivery_contract(data)
    # Let the selected model's runtime/profile supply omitted sampling values.
    # A universal greedy override can defeat the model's recommended settings
    # and cause repetitive generations. Explicit client settings pass through;
    # tool authorization remains the responsibility of the broker and harness.
    request_token = object()
    chat_id = data.get("user")
    cancel_event = None
    activity = {"terminal": False}
    upstream_data["model"] = _UPSTREAM_REWRITE

    fwd_headers = _sanitize_headers(dict(request.headers))
    fwd_headers["Content-Type"] = "application/json"
    if image_turn:
        # Never forward an unvalidated caller-supplied image-header value.
        fwd_headers["X-ODS-Image-Turn"] = "1"

    try:
        await request.app[_TRANSITION_GATE_KEY].admit(request_token)
    except GateError as exc:
        return web.json_response({"error": exc.reason}, status=exc.status)
    try:
        if isinstance(chat_id, str) and _SAFE_CHAT_ID.fullmatch(chat_id):
            cancel_event = asyncio.Event()
            if not request.app[_CANCEL_EVENTS_KEY].get(chat_id):
                request.app[_CHAT_ACTIVITY_KEY].pop(chat_id, None)
            request.app[_CANCEL_EVENTS_KEY].setdefault(chat_id, set()).add(cancel_event)
        # The gateway knows the owner's enabled tools and their network policy.
        # A URL in chat is not an outbound fetch by this transport. Let an
        # authorized browser handle local previews; public-fetch restrictions
        # and the unavailable-browser response remain enforced by the harness.
        connector = UnixConnector(path=_SOCKET_PATH)
        timeout = ClientTimeout(total=_TOTAL_TIMEOUT,
                                sock_connect=_CONNECT_TIMEOUT,
                                sock_read=_SOCK_READ_TIMEOUT)
        async with ClientSession(connector=connector, timeout=timeout) as session:
            payload = ({"data": _encoded_image_envelope(upstream_data)} if image_turn
                       else {"json": upstream_data})
            async with session.post("http://pixel-upstream/v1/chat/completions",
                                    **payload, headers=fwd_headers) as resp:
                if image_turn:
                    # Request encoding owns its data until sending finishes;
                    # the response stream needs none of the image/history tree.
                    del payload, upstream_data, data
                ctype = resp.headers.get("Content-Type", "").lower()

                if resp.status >= 400:
                    status = 400 if 400 <= resp.status < 500 else 502
                    return web.json_response({"error": "Portal request rejected"}, status=status)

                if "text/event-stream" in ctype:
                    return await _stream_upstream(
                        request, resp, empty_reply_fallback, cancel_event, activity,
                        response_model=req_model, owner_echo=owner_echo
                    )

                if "application/json" not in ctype:
                    return web.json_response({"error": "invalid upstream response"}, status=502)

                # Non-streaming: cap bytes, then rewrite model identifiers.
                resp_body = bytearray()
                async for chunk in resp.content.iter_any():
                    resp_body.extend(chunk)
                    if len(resp_body) > _MAX_RESPONSE_BYTES:
                        return web.json_response({"error": "upstream response too large"},
                                                 status=502)

                rewritten = _rewrite_json_response(bytes(resp_body), empty_reply_fallback, req_model,
                                                   owner_echo)
                activity["terminal"] = True
                return web.Response(status=resp.status, body=rewritten,
                                    content_type="application/json")
    except (ConnectionError, OSError, asyncio.TimeoutError):
        return web.json_response({"error": "service unavailable"}, status=502)
    except Exception:
        return web.json_response({"error": "bad gateway"}, status=502)
    finally:
        await request.app[_TRANSITION_GATE_KEY].finish(request_token)
        if cancel_event is not None:
            _finish_chat_activity(request.app, chat_id, cancel_event,
                                  activity["terminal"] or cancel_event.is_set())


async def handle_chat_cancel(request: web.Request):
    """Relay one authenticated, bounded cancellation to the private ingress."""
    fail = _check_auth(request)
    if fail is not None:
        return fail
    if request.content_type != "application/json":
        return web.json_response({"error": "Content-Type must be application/json"},
                                 status=415)
    if request.content_length and request.content_length > _MAX_CANCEL_BODY:
        return web.json_response({"error": "request too large"}, status=413)

    try:
        raw = await request.read()
    except Exception:
        return web.json_response({"error": "bad request"}, status=400)
    if len(raw) > _MAX_CANCEL_BODY:
        return web.json_response({"error": "request too large"}, status=413)
    try:
        data = json.loads(raw)
    except (json.JSONDecodeError, ValueError):
        return web.json_response({"error": "invalid JSON"}, status=400)
    if (
        not isinstance(data, dict)
        or set(data) != {"user"}
        or not isinstance(data.get("user"), str)
        or not _SAFE_CHAT_ID.fullmatch(data["user"])
    ):
        return web.json_response({"error": "invalid cancellation request"}, status=400)

    connector = UnixConnector(path=_SOCKET_PATH)
    # Outlive the ingress's 16 s harness + managed-project cancellation budget.
    timeout = ClientTimeout(total=20, sock_connect=2, sock_read=18)
    try:
        async with ClientSession(connector=connector, timeout=timeout) as session:
            async with session.post(
                "http://pixel-upstream/v1/chat/cancel",
                json={"user": data["user"]},
                headers={"Content-Type": "application/json", "Accept": "application/json"},
            ) as resp:
                if resp.status != 200:
                    return web.json_response({"error": "Portal cancellation failed"}, status=502)
                if "application/json" not in resp.headers.get("Content-Type", "").lower():
                    return web.json_response({"error": "Portal cancellation failed"}, status=502)
                raw_result = await _read_bounded(resp.content, _MAX_CANCEL_RESPONSE_BYTES)
                result = json.loads(raw_result)
                if (
                    not isinstance(result, dict)
                    or set(result) != {"aborted"}
                    or not isinstance(result.get("aborted"), bool)
                ):
                    return web.json_response({"error": "Portal cancellation failed"}, status=502)
                if result["aborted"]:
                    active = request.app[_CANCEL_EVENTS_KEY].get(data["user"], ())
                    for event in tuple(active):
                        event.set()
                    if not active:
                        # A native run can outlive the disconnected edge stream.
                        # Only its exact cancellation acknowledgement resolves it.
                        _remember_chat_activity(request.app, data["user"], "terminal")
                return web.json_response({"aborted": result["aborted"]})
    except (ConnectionError, OSError, asyncio.TimeoutError, json.JSONDecodeError, ValueError):
        return web.json_response({"error": "Portal cancellation failed"}, status=502)
    except Exception:
        return web.json_response({"error": "Portal cancellation failed"}, status=502)


async def _stream_upstream(
    request: web.Request,
    resp,
    empty_reply_fallback: str,
    cancel_event: asyncio.Event | None = None,
    activity: dict | None = None,
    response_model: str = _LEGACY_MODEL,
    owner_echo: str = "",
):
    """Stream bounded SSE while replacing only a reserved/empty or copied final reply.

    Answer text is withheld only while it can still become such a reply: empty,
    a prefix of a reserved reply, or a prefix of the owner's own message
    (``owner_echo``). It is flushed as soon as it diverges.
    """
    response = web.StreamResponse(
        status=resp.status,
        headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
    )
    await response.prepare(request)
    buffered = bytearray()
    pending = []
    pending_bytes = 0
    pending_text = ""
    passthrough = False

    async def queue_pending(line, event, content, finish_reason):
        nonlocal pending_bytes, passthrough
        # The line cap alone does not bound many small reasoning/empty frames.
        size = len(line) + 1
        if (pending_bytes + size > _MAX_SSE_PENDING_BYTES
                or len(pending) >= _MAX_SSE_PENDING_LINES):
            if _reserved_prefix(pending_text):
                raise ValueError("SSE prelude exceeded limit")
            # Only a possible copy of the owner's message is withheld. That
            # check is best effort: release the text unchanged at the existing
            # bound instead of failing the answer.
            await flush_pending()
            await response.write(line + b"\n")
            passthrough = True
            return
        pending.append((line, event, content, finish_reason))
        pending_bytes += size

    async def flush_pending():
        nonlocal pending, pending_bytes
        for item in pending:
            await response.write(item[0] + b"\n")
        pending = []
        pending_bytes = 0

    async def replace_pending(template: dict, *, synthesize_finish: bool):
        nonlocal pending, pending_bytes
        # Preserve role/metadata events, but never expose the reserved text.
        for line, _event, content, finish_reason in pending:
            if content is None and finish_reason is None:
                await response.write(line + b"\n")
        await response.write(
            _fallback_sse_line(template, empty_reply_fallback, finished=False) + b"\n\n"
        )
        if synthesize_finish:
            await response.write(
                _fallback_sse_line(template, empty_reply_fallback, finished=True) + b"\n\n"
            )
        pending = []
        pending_bytes = 0

    try:
        async for chunk in resp.content.iter_any():
            buffered.extend(chunk)
            if len(buffered) > _MAX_SSE_LINE and b"\n" not in buffered:
                raise ValueError("SSE line exceeded limit")
            while b"\n" in buffered:
                line, _, remainder = buffered.partition(b"\n")
                buffered = bytearray(remainder)
                line = _normalize_sse_line(line)
                if cancel_event is not None and cancel_event.is_set():
                    pending = []
                    await response.write(b"data: [DONE]\n\n")
                    passthrough = True
                    return response
                if len(line) > _MAX_SSE_LINE:
                    raise ValueError("SSE line exceeded limit")
                # Only the real upstream terminator is lifecycle evidence;
                # locally synthesized error/fallback frames do not prove it.
                if line.rstrip(b"\r") == b"data: [DONE]" and activity is not None:
                    activity["terminal"] = True
                if line.startswith(b"data: ") and line != b"data: [DONE]":
                    line = b"data: " + _rewrite_json_model(line[6:], response_model)
                if passthrough:
                    await response.write(line + b"\n")
                    continue

                if line == b"data: [DONE]":
                    if _replaceable_reply(pending_text, owner_echo):
                        template = next(
                            (item[1] for item in reversed(pending) if isinstance(item[1], dict)),
                            {"model": response_model},
                        )
                        await replace_pending(template, synthesize_finish=True)
                    else:
                        await flush_pending()
                    await response.write(line + b"\n")
                    passthrough = True
                    continue

                event, content, finish_reason = _sse_event(line)
                if isinstance(event, dict) and event.get('object') == 'ods.task.activity':
                    if valid_live_task_event(event):
                        await response.write(line + b"\n\n")
                    continue
                if isinstance(event, dict) and "error" in event:
                    await flush_pending()
                    await response.write(line + b"\n")
                    passthrough = True
                    continue
                if finish_reason is not None:
                    if _replaceable_reply(pending_text, owner_echo):
                        template = event if isinstance(event, dict) else next(
                            (item[1] for item in reversed(pending) if isinstance(item[1], dict)),
                            {"model": response_model},
                        )
                        await replace_pending(template, synthesize_finish=False)
                    else:
                        await flush_pending()
                    await response.write(line + b"\n")
                    passthrough = True
                    continue

                await queue_pending(line, event, content, finish_reason)
                if content is not None and not passthrough:
                    pending_text += content
                    if not _replaceable_prefix(pending_text, owner_echo):
                        await flush_pending()
                        passthrough = True
        if cancel_event is not None and cancel_event.is_set():
            pending = []
            await response.write(b"data: [DONE]\n\n")
            return response
        if buffered:
            if len(buffered) > _MAX_SSE_LINE:
                raise ValueError("SSE line exceeded limit")
            line = _normalize_sse_line(bytes(buffered))
            if line.rstrip(b"\r") == b"data: [DONE]" and activity is not None:
                activity["terminal"] = True
            if line.startswith(b"data: ") and line != b"data: [DONE]":
                line = b"data: " + _rewrite_json_model(line[6:], response_model)
            if passthrough:
                await response.write(line)
            else:
                event, content, finish_reason = _sse_event(line)
                await queue_pending(line, event, content, finish_reason)
                if content is not None and not passthrough:
                    pending_text += content
        if not passthrough and pending:
            if _replaceable_reply(pending_text, owner_echo):
                template = next(
                    (item[1] for item in reversed(pending) if isinstance(item[1], dict)),
                    {"model": response_model},
                )
                has_finish = any(item[3] is not None for item in pending)
                await replace_pending(template, synthesize_finish=not has_finish)
            else:
                await flush_pending()
    except (ConnectionError, OSError, asyncio.TimeoutError) as exc:
        if cancel_event is not None and cancel_event.is_set():
            await response.write(b"data: [DONE]\n\n")
        else:
            # Fixed diagnostic category only, never payloads or exception text.
            print(f'pixel-edge stream failed ({type(exc).__name__})', file=sys.stderr)
            await response.write(b'data: {"error":"upstream error"}\n\ndata: [DONE]\n\n')
    except Exception as exc:
        if cancel_event is not None and cancel_event.is_set():
            await response.write(b"data: [DONE]\n\n")
        else:
            print(f'pixel-edge stream failed ({type(exc).__name__})', file=sys.stderr)
            await response.write(b'data: {"error":"upstream error"}\n\ndata: [DONE]\n\n')
    return response


_REMOTE_PREVIEW_CSP = (
    "sandbox allow-scripts allow-forms allow-downloads; default-src 'self' data: blob:; "
    "connect-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; "
    "font-src 'self' data:; script-src 'self' 'unsafe-inline'; "
    "style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'; "
    "form-action 'none'; frame-ancestors 'self'"
)


def _preview_upstream_path(site_id: str, tail: str) -> str | None:
    if _PREVIEW_SITE_ID.fullmatch(site_id) is None:
        return None
    if not tail:
        return f"/{site_id}/"
    # Exact host-generated metadata endpoints; other __ods_ names remain
    # reserved. Framework underscore assets still select immutable files only.
    if tail in {"__ods_manifest__.json", "__ods_view__.html"}:
        return f"/{site_id}/{tail}"
    if re.fullmatch(r"__ods_changes__/(?:initial|site-[a-f0-9]{24})\.json", tail):
        return f"/{site_id}/{tail}"
    if re.fullmatch(r'__ods_source__/source-[a-f0-9]{24}\.json', tail):
        return f'/{site_id}/{tail}'
    # Match the host static server: a directory URL selects its index file.
    if tail.endswith("/"):
        tail += "index.html"
    parts = tail.split("/")
    if any(_PREVIEW_PATH_COMPONENT.fullmatch(part) is None for part in parts):
        return None
    encoded = "/".join(quote(part, safe="") for part in parts)
    return f"/{site_id}/{encoded}"


async def handle_preview(request: web.Request):
    """Relay one immutable host snapshot without exposing its host listener."""
    fail = _check_preview_auth(request)
    if fail is not None:
        return fail
    upstream_path = _preview_upstream_path(
        request.match_info.get("site_id", ""), request.match_info.get("tail", "")
    )
    if upstream_path is None:
        return web.json_response({"error": "not found"}, status=404)

    connector = UnixConnector(path=_PREVIEW_SOCKET_PATH)
    timeout = ClientTimeout(total=10, sock_connect=3, sock_read=5)
    try:
        async with ClientSession(connector=connector, timeout=timeout) as session:
            async with session.request(
                "GET",
                f"http://pixel-preview.internal{upstream_path}",
                headers={"Host": "pixel-preview.internal"},
            ) as upstream:
                if upstream.status not in {200, 404}:
                    return web.json_response({"error": "preview unavailable"}, status=502)
                # read(n) may return only the first available transport chunk.
                # Verify the complete bounded snapshot, including for client HEAD.
                try:
                    body = await _read_bounded(upstream.content, _MAX_PREVIEW_RESPONSE_BYTES)
                except ValueError:
                    return web.json_response({"error": "preview too large"}, status=502)
                if upstream.status == 404:
                    return web.json_response({"error": "not found"}, status=404)
                content_type = upstream.headers.get(
                    "Content-Type", "application/octet-stream"
                )
                content_length = upstream.headers.get("Content-Length", str(len(body)))
                digest = upstream.headers.get("X-Preview-SHA256", "")
                if (
                    not content_length.isdigit()
                    or int(content_length) > _MAX_PREVIEW_RESPONSE_BYTES
                    or int(content_length) != len(body)
                    or not re.fullmatch(r"[a-f0-9]{64}", digest)
                    or not hmac.compare_digest(
                        hashlib.sha256(body).hexdigest(), digest
                    )
                ):
                    return web.json_response({"error": "invalid preview response"}, status=502)
    except (OSError, asyncio.TimeoutError):
        return web.json_response({"error": "preview unavailable"}, status=503)
    except Exception:
        return web.json_response({"error": "preview unavailable"}, status=502)

    headers = {
        "Content-Type": content_type,
        "Cache-Control": "no-store",
        "Content-Security-Policy": _REMOTE_PREVIEW_CSP,
        "Cross-Origin-Opener-Policy": "same-origin",
        # The preview document has an opaque sandbox origin. Its own CSS and
        # scripts are cross-origin loads even on the same Dashboard route.
        # These digest-verified snapshot bytes carry no portal authority;
        # retain the opaque CSP sandbox and the proxy authentication above.
        "Cross-Origin-Resource-Policy": "cross-origin",
        # CORP alone does not authorize module imports or fetch() from an
        # opaque frame. This applies only to authenticated, digest-verified
        # static snapshots, without allowing browser credentials.
        "Access-Control-Allow-Origin": "*",
        "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
        "Referrer-Policy": "no-referrer",
        "X-Content-Type-Options": "nosniff",
        "X-Preview-SHA256": digest,
    }
    if '/__ods_source__/' in upstream_path:
        headers.pop('Access-Control-Allow-Origin', None)
        headers['Cross-Origin-Resource-Policy'] = 'same-origin'
        headers['Content-Security-Policy'] = "sandbox; default-src 'none'; frame-ancestors 'none'"
        headers['Content-Type'] = 'application/json; charset=utf-8'
    return web.Response(status=200, body=body, headers=headers)


async def handle_not_found(_request: web.Request):
    return web.json_response({"error": "not found"}, status=404)


# ---------------------------------------------------------------------------
# App factory
# ---------------------------------------------------------------------------

def create_app() -> web.Application:
    # Transport inflation happens before route body limits. The internal API
    # sends uncompressed JSON; do not allow a compressed body to bypass caps.
    app = web.Application(handler_args={"auto_decompress": False})
    # The 128 MiB Edge budget permits one decoded image envelope at a time.
    # Text, health and cancellation do not queue behind this image-only lease.
    app[_IMAGE_WORK_KEY] = ImageWorkBudget(1)
    app[_CANCEL_EVENTS_KEY] = {}
    app[_CHAT_ACTIVITY_KEY] = {}
    app[_ACTIVE_REQUESTS_KEY] = set()
    app[_COMPACTIONS_KEY] = {}
    compactions = app[_COMPACTIONS_KEY]
    gate = TransitionGate(
        os.environ.get("PIXEL_TRANSITION_STATE_DIR", ""), app[_ACTIVE_REQUESTS_KEY],
        owner_key_distinct=not _constant_time_compare(config_token, preview_proxy_token),
    )
    app[_TRANSITION_GATE_KEY] = gate

    async def stop_admission(_application):
        await gate.shutdown()
        tasks = [task for _, task in compactions.values() if task is not None]
        for task in tasks:
            task.cancel()
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)

    async def close_gate(_application):
        gate.close()

    app.on_shutdown.append(stop_admission)
    app.on_cleanup.append(close_gate)
    app.router.add_get("/health", handle_health)
    app.router.add_get("/preview/{site_id}/{tail:.*}", handle_preview)
    app.router.add_get("/v1/models", handle_models)
    app.router.add_get("/v1/runtime-identity", handle_runtime_identity, allow_head=False)
    app.router.add_get("/v1/example-projects", handle_example_projects, allow_head=False)
    app.router.add_post("/v1/example-projects", handle_example_projects)
    app.router.add_get("/v1/activity", handle_activity)
    app.router.add_get('/v1/access-mode', handle_access_mode, allow_head=False)
    app.router.add_post('/v1/access-mode', handle_access_mode)
    app.router.add_post('/v1/model-control', handle_model_control)
    app.router.add_get("/v1/transition", handle_transition)
    app.router.add_post("/v1/transition/{operation:acquire|drain|release|recover}", handle_transition)
    app.router.add_post("/v1/chat/completions", handle_chat_completions)
    app.router.add_post("/v1/chat/cancel", handle_chat_cancel)
    app.router.add_post("/v1/chat/activity", handle_chat_activity)
    app.router.add_post("/v1/chat/settle", handle_chat_settle)
    app.router.add_post("/v1/chat/context", handle_chat_context)
    app.router.add_post("/v1/chat/images-delete", handle_chat_images_delete)
    app.router.add_post("/v1/chat/compact", handle_chat_context)
    # Catch-all registered last: unmatched paths AND unmatched methods → 404.
    app.router.add_route("*", "/{tail:.*}", handle_not_found)
    return app


if __name__ == "__main__":
    web.run_app(create_app(), host="0.0.0.0", port=_LISTEN_PORT)