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.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
"""Bounded dashboard bridge to the internal Pixel edge service."""
from __future__ import annotations
import asyncio
try:
from asyncio import timeout as async_timeout
except ImportError: # Python 3.10; installed by this runtime's requirements.
from async_timeout import timeout as async_timeout
import hashlib
from model_activation_status import model_activation_status
import json
import logging
import os
import re
import time
from pathlib import Path
from typing import AsyncIterator, Callable, Literal
from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from host_agent_client import AgentClientError, AgentHTTPError, agent_reports_busy, async_request_json as request_agent_json
from runtime_projection import active_runtime_projection as _active_runtime_projection
from pixel_runtime_state import begin_pixel_stream, end_pixel_stream, try_begin_pixel_stream
from pixel_chat_results import ChatResultStore, ResultCapacity, ResultConflict, owner_namespace
from security import verify_api_key
from config import read_live_env_value
from context_policy import PIXEL_MIN_CONTEXT
from helpers import get_loaded_model, get_llama_context_size
from pixel_chat_identity import messages_with_identity
from pixel_chat_context import HistoryMessage, HistorySnapshot, public_context
from pixel_runtime_identity import project_runtime_identity, unknown_runtime_identity
from pixel_readiness import project_readiness
from routers.pixel_images import router as image_router, resolve_message_images, conversation_storage
from pixel_edge_read_client import borrow_edge_read_client, get_edge_read_client
logger = logging.getLogger(__name__)
_DEFAULT_EDGE_URL = "http://pixel-edge:9595"
_MODEL = "portal/default"
_CHAT_STREAM_TIMEOUT_SECONDS = 2040.0
_CLIENT_DISCONNECT_POLL_SECONDS = 0.25
_STREAM_KEEPALIVE_SECONDS = 15.0
_STREAM_KEEPALIVE = b": pixel working\n\n"
_CLIENT_CANCEL_TIMEOUT_SECONDS = 27.0
_MAX_KEY_LENGTH = 4096
_MAX_STATUS_BYTES = 64 * 1024
_READINESS_PROBE_SECONDS = 4.0
_MAX_SSE_LINE_BYTES = 1024 * 1024
_MAX_MESSAGE_CHARS = 16 * 1024
_MAX_TOTAL_MESSAGE_BYTES = 256 * 1024
_SAFE_CHAT_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
_OPS_JOB_ID = re.compile(r"^ops-[0-9]{13}-[a-f0-9]{12}$")
_OPS_PLAN_HASH = re.compile(r"^[a-f0-9]{64}$")
_OPS_STATUSES = frozenset(
{
"awaiting-approval",
"paused",
"queued",
"running",
"succeeded",
"failed",
"cancelled",
"rejected",
}
)
_CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
_MODEL_SWITCH_DETAIL = "Model switch in progress; Portal will be ready when activation completes"
_MODEL_UNLOADED_DETAIL = "The model is unloaded, so Portal is paused. Choose Resume model to load it again."
_MODEL_RECOVERY_DETAIL = ("A model switch stopped before it finished, so new messages are held. "
"Choose Recover model switch to finish or undo it.")
_RUNTIME_STOPPED_DETAIL = "The local model runtime is not running, so Portal is paused. Choose Resume model to start it."
# The Windows runtime ownership proof starts host processes and takes seconds.
# Bound it inside the Portal page's 15 s status deadline, and let one answer
# serve its 3 s polls while an unattended hold lasts.
_RUNTIME_PROOF_SECONDS = 10.0
_RUNTIME_PROOF_TTL_SECONDS = 30.0
# An unavailable runtime is found only after the edge and telemetry reads, so
# its optional Resume hint gets less of that deadline.
_RUNTIME_HINT_SECONDS = 6.0
_MODEL_HOLD_DETAIL = "A model transition is holding new messages. Check model update progress. If it has stopped, restore Sandbox in Portal permissions."
_CHAT_RECOVERY_DETAIL = ("Portal stopped during an earlier turn, so new messages are held "
"until its permissions are checked again.")
# Host lifecycle operations that never own or change the Portal model
# transaction. They take the lifecycle only to serialize with model work (the
# access monitor's reproof runs every 30 s), so a hold they overlap is still
# unattended. Mirrors _MODEL_RUNTIME_NEUTRAL_OPERATIONS in ods-host-agent.py.
_MODEL_NEUTRAL_OPERATIONS = frozenset({
"pixel_startup_reproof", "pixel_access_mode", "pixel_open_app",
"pixel_providers", "pixel_settings", "model_profile_recheck",
})
# The one-click fix Portal offers for a held state ("recovery" in status).
# Each names an existing API: the Sandbox actions POST /api/pixel/access-mode
# with {"mode": "sandboxed"} exactly as Portal permissions does; resume-model
# is Models' Resume model; recover-model is Models' Recover model switch.
_STATE_RECOVERY = {"model_unloaded": "resume-model", "model_recovery_required": "recover-model"}
_MODEL_CAPABILITY_DETAIL = (
"The active model is recorded as not agent-qualified. Tool-driven tasks "
"may be unreliable; chat and experiments remain available."
)
# Measured-profile advisories (WP4.3). The dashboard shows its own copy per
# reason; this text serves API readers and older dashboards.
_MODEL_SUPPORT_REASONS = {
"context-too-small": (
f"This model runs with less than {PIXEL_MIN_CONTEXT // 1024}K tokens of context, too small for "
f"Portal tasks. Set its context to {PIXEL_MIN_CONTEXT // 1024}K or more in Models, or switch model."
),
"tools-unavailable": (
"This model failed the tool-call check, so Portal tasks that use tools will likely fail. "
"Chat still works."
),
"not-profiled": (
"ODS has not checked this model yet, so Portal tasks may not work. To check it, choose "
"Check again on the running model in Models."
),
"thinking-always-on": (
"This model always thinks before it answers, so Portal tasks are slower and use more of its context."
),
}
def _validate_edge_url(raw: str) -> str:
"""Accept exactly the fixed internal Pixel edge origin."""
try:
parsed = urlparse(raw)
port = parsed.port
except (TypeError, ValueError) as exc:
raise ValueError("PIXEL_EDGE_URL is invalid") from exc
if parsed.scheme != "http":
raise ValueError("PIXEL_EDGE_URL scheme must be http")
if parsed.hostname != "pixel-edge" or port != 9595:
raise ValueError("PIXEL_EDGE_URL must use pixel-edge:9595")
if parsed.username or parsed.password or parsed.path or parsed.params or parsed.query or parsed.fragment:
raise ValueError("PIXEL_EDGE_URL must be an origin without userinfo, path, query, or fragment")
return _DEFAULT_EDGE_URL
def _pixel_config() -> tuple[str, str] | None:
"""Return validated runtime config, or None when Pixel is not enabled."""
raw_key = os.environ.get("PIXEL_OPENWEBUI_KEY", "")
if not raw_key:
return None
if raw_key != raw_key.strip() or len(raw_key) < 32 or len(raw_key) > _MAX_KEY_LENGTH:
raise RuntimeError("PIXEL_OPENWEBUI_KEY is invalid")
if _CONTROL.search(raw_key):
raise RuntimeError("PIXEL_OPENWEBUI_KEY is invalid")
raw_url = os.environ.get("PIXEL_EDGE_URL", _DEFAULT_EDGE_URL)
return _validate_edge_url(raw_url), raw_key
def _edge_headers(key: str, *, accept: str, image_turn: bool = False) -> dict[str, str]:
return {
"Authorization": f"Bearer {key}",
"Accept": accept,
"Content-Type": "application/json",
**({"X-ODS-Image-Turn": "1"} if image_turn else {}),
}
class _Message(HistoryMessage):
model_config = ConfigDict(extra="forbid", strict=True)
role: str
content: str = Field(max_length=_MAX_MESSAGE_CHARS)
@field_validator("role")
@classmethod
def _role(cls, value: str) -> str:
if value not in {"system", "user", "assistant"}:
raise ValueError("unsupported message role")
return value
class ImageRoute(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
routeFingerprint: str = Field(min_length=64, max_length=64, pattern=r"^[a-f0-9]{64}$")
unknownConsent: bool
class ChatStreamRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
chat_id: str
request_id: str | None = Field(default=None, pattern=r"^[A-Za-z0-9_-]{1,128}$")
messages: list[_Message] = Field(min_length=1, max_length=50)
history_snapshot: HistorySnapshot | None = None
image_route: ImageRoute | None = None
@field_validator("chat_id")
@classmethod
def _chat_id(cls, value: str) -> str:
if not _SAFE_CHAT_ID.fullmatch(value):
raise ValueError("invalid chat_id")
return value
@field_validator("messages")
@classmethod
def _total_size(cls, messages: list[_Message]) -> list[_Message]:
total = sum(len(item.content.encode("utf-8")) for item in messages)
if total > _MAX_TOTAL_MESSAGE_BYTES:
raise ValueError("aggregate message content is too large")
return messages
@model_validator(mode="after")
def _history_matches_turn(self):
image_messages = [index for index, message in enumerate(self.messages) if message.images is not None]
history_images = self.history_snapshot is not None and any(message.images for message in self.history_snapshot.messages)
if (image_messages or history_images) and self.image_route is None:
raise ValueError("Image conversations require a confirmed model route")
if image_messages:
if image_messages != [len(self.messages) - 1]:
raise ValueError("Earlier image messages belong in the persistent history snapshot")
if self.request_id is None or self.history_snapshot is None or self.history_snapshot.schemaVersion != 2:
raise ValueError("Image turns require persistent version 2 history and a request_id")
if self.history_snapshot is not None:
if self.request_id is None:
raise ValueError("Persistent history requires a request_id")
latest = self.history_snapshot.messages[-1]
if latest.role != "user" or latest.model_dump() != self.messages[-1].model_dump():
raise ValueError("Conversation history must end with the submitted user message")
return self
class ChatCancelRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
chat_id: str
request_id: str | None = Field(default=None, pattern=r"^[A-Za-z0-9_-]{1,128}$")
@field_validator("chat_id")
@classmethod
def _chat_id(cls, value: str) -> str:
if not _SAFE_CHAT_ID.fullmatch(value):
raise ValueError("invalid chat_id")
return value
router = APIRouter(prefix="/api/pixel", tags=["pixel"])
router.include_router(image_router)
_result_store: ChatResultStore | None = None
_result_tasks: dict[tuple[str, str, str], asyncio.Task] = {}
_result_preflights: set[tuple[str, str, str]] = set()
_result_stops: set[tuple[str, str]] = set()
# Chats whose last turn an activity check is settling right now. Kept apart
# from Stop's fence, so neither can remove the other's.
_result_settles: set[tuple[str, str]] = set()
_result_abort_ack: set[tuple[str, str, str]] = set()
def _chat_results() -> ChatResultStore:
global _result_store
if _result_store is None:
_result_store = ChatResultStore(Path(os.environ.get("ODS_DATA_DIR", "/data")) / "pixel-chat-results")
return _result_store
def _result_state(store, identity):
row = store.get(identity)
task = _result_tasks.get(identity)
if (row is not None and row["state"] == "active" and identity not in _result_preflights
and (task is None or task.done())):
# A producer may fail while committing its last bytes. The API process
# being alive does not prove that this particular task is still running.
row["state"] = "unresolved"
return row
class ChatResultRequest(ChatCancelRequest):
request_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,128}$")
async def _chat_context_request(body: ChatCancelRequest, *, compact: bool = False):
config = _pixel_config()
if config is None:
raise HTTPException(503, "Portal is not enabled")
edge_url, key = config
payload = {"user": body.chat_id}
if compact:
payload["request_id"] = body.request_id
try:
# Starting a compaction returns a job receipt promptly. CPU/model time
# belongs to the runtime job, not the browser's HTTP connection.
timeout = httpx.Timeout(connect=3.0, read=20.0, write=5.0, pool=3.0)
# Compaction mutates runtime state and retains its independent transport.
client_context = (httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False)
if compact else borrow_edge_read_client())
async with client_context as client:
async with client.stream(
"POST", f"{edge_url}/v1/chat/{'compact' if compact else 'context'}",
json=payload, headers=_edge_headers(key, accept="application/json"),
timeout=timeout,
) as response:
if response.status_code in {409, 423, 429}:
raise HTTPException(response.status_code, "Portal is busy. Wait for the current task to finish.")
if response.status_code != 200 or not response.headers.get("content-type", "").lower().startswith("application/json"):
raise ValueError("Invalid context response")
raw = await _bounded_response_bytes(response, 16 * 1024)
return public_context(json.loads(raw))
except (httpx.HTTPError, asyncio.TimeoutError):
# A timeout does not cancel a native compaction. The caller retains its
# request ID and reads /context before attempting any further mutation.
raise HTTPException(503, "Could not confirm context status. Check again before retrying compaction.") from None
except (ValueError, TypeError):
raise HTTPException(502, "Portal context status could not be verified") from None
async def _delete_native_conversation_images(chat_id):
config = _pixel_config()
if config is None:
raise HTTPException(503, "Portal is unavailable. Retry deletion when it is running.")
edge_url, key = config
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(22, connect=3), trust_env=False, follow_redirects=False) as client:
async with client.stream("POST", f"{edge_url}/v1/chat/images-delete", json={"user": chat_id},
headers=_edge_headers(key, accept="application/json")) as result:
if result.status_code in {409, 423, 429}:
raise HTTPException(409, "Conversation deletion is pending. Finish or recover its active work, then retry deletion.")
if result.status_code != 200 or not result.headers.get("content-type", "").lower().startswith("application/json"):
raise ValueError("invalid receipt")
receipt = json.loads(await _bounded_response_bytes(result, 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 receipt")
except HTTPException:
raise
except (httpx.HTTPError, ValueError, TypeError, asyncio.TimeoutError):
raise HTTPException(503, "Image deletion is not confirmed. Your local history is preserved; retry deletion.") from None
@router.post("/chat/context", dependencies=[Depends(verify_api_key)])
async def pixel_chat_context(body: ChatCancelRequest):
return await _chat_context_request(body)
@router.post("/chat/compact")
async def pixel_chat_compact(body: ChatResultRequest, owner: str = Depends(verify_api_key)):
await conversation_storage("assert_available", owner, body.chat_id)
store = _chat_results()
if store.has_pending((owner_namespace(owner), body.chat_id)):
raise HTTPException(423, "Recover or finish the current response before compacting this conversation")
issue = await _model_readiness_issue()
if issue is not None:
raise HTTPException(409, issue[1])
# The ingress serializes this mutation with chat admission, including other
# dashboard processes and clients. Never invoke native sessions.compact
# directly here: that RPC may abort an active run.
return await _chat_context_request(body, compact=True)
@router.post("/chat/result")
async def pixel_chat_result(body: ChatResultRequest, owner: str = Depends(verify_api_key)):
"""Read an owner's attempt without resubmitting any model request."""
store = _chat_results()
key = (owner_namespace(owner), body.chat_id, body.request_id)
row = _result_state(store, key)
if row is None:
return {"state": "unknown", "events": ""}
if (key[:2] in _result_stops and store.is_latest(key)
and row["state"] in {"active", "unresolved", "interrupted"}):
# The producer can finish before native Stop acknowledges its outcome.
# Do not let a subscriber finalize that provisional failure and forget
# the request identity while its exact cancellation is still pending.
return {"state": "active", "events": ""}
if row["state"] == "unresolved":
activity = await pixel_chat_activity(ChatCancelRequest(chat_id=body.chat_id), owner)
if activity["state"] == "terminal":
store.finish(key, "interrupted")
row = store.get(key)
events = b"" if row["state"] == "active" else b"".join(chunk["data"] for chunk in store.chunks(key))
return {"state": row["state"], "events": events.decode("utf-8", errors="replace")}
class PixelAccessChange(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
mode: Literal["sandboxed", "full-access"]
revision: str = Field(pattern=r"^[a-f0-9]{64}$")
confirmed: bool
class PixelAccessStatus(BaseModel):
# Project only the public mode contract; host credentials and receipts never
# cross into browser state, even if the upstream gains new fields.
model_config = ConfigDict(extra="ignore", strict=True)
available: bool
surface: Literal["linux-systemd", "wsl-systemd", "linux", "darwin", "windows"]
configured_mode: Literal["sandboxed", "full-access", "unknown"]
effective_mode: Literal["sandboxed", "full-access", "unknown"]
runtime_verified: bool
revision: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
busy: bool
pending: bool
reason: str | None = Field(default=None, pattern=r"^[a-z][a-z0-9-]{0,95}$")
scope: Literal["owner-host"]
def _access_projection(value):
try:
status = PixelAccessStatus.model_validate(value)
if (status.runtime_verified != (status.effective_mode != "unknown")
or status.runtime_verified and (not status.available or status.pending
or status.effective_mode != status.configured_mode)):
raise ValueError("inconsistent runtime proof")
return status.model_dump()
except (ValueError, TypeError):
raise HTTPException(status_code=502, detail="Portal access status could not be verified") from None
def _access_recovery(access, *, model_hold_possible=True) -> str | None:
"""The Portal permissions action that recovers this access state, if any.
Both actions send {"mode": "sandboxed", "confirmed": false}, exactly like
Verify Sandbox and Restore Sandbox; the host re-checks the revision and
refuses a busy runtime first. Nothing here can select Full Access, and an
unverified Full Access is left to the host's own same-mode reproof.
"""
if not access or not access["available"]:
return None
reason, mode = access["reason"], access["configured_mode"]
if reason == "chat-recovery-required":
# Settings offers only this while a chat is held: Enable Full Access waits.
return {"sandboxed": "verify-sandbox", "full-access": "restore-sandbox"}.get(mode)
if not access["pending"] and reason == "runtime-proof-required" and mode == "sandboxed":
return "verify-sandbox"
# An unfinished access change resumes only by restoring Sandbox. A held
# model transaction reads the same way but has its own recovery.
if access["pending"] and reason == "transition-recovery-required" and not model_hold_possible:
return "restore-sandbox"
return None
def _recovery_field(action: str | None) -> dict[str, str]:
return {"recovery": action} if action else {}
@router.get("/access-mode", dependencies=[Depends(verify_api_key)])
async def pixel_access_status():
try:
return _access_projection(await request_agent_json("GET", "/v1/pixel/access-mode", timeout=30.0))
except AgentClientError:
raise HTTPException(status_code=503, detail="Portal access service is unavailable") from None
@router.post("/access-mode", dependencies=[Depends(verify_api_key)])
async def pixel_access_change(change: PixelAccessChange):
if change.mode == "full-access" and not change.confirmed:
raise HTTPException(status_code=400, detail="Confirm the Full Access risk before enabling it")
try:
value = await request_agent_json("POST", "/v1/pixel/access-mode", payload=change.model_dump(), timeout=330.0)
return _access_projection(value)
except AgentHTTPError as exc:
if agent_reports_busy(exc):
# Refused before any change, unlike an unverified attempt.
raise HTTPException(status_code=409, detail={"code": "model_lifecycle_busy", "message": "ODS is busy with a model or Portal change. Nothing was changed; try again in a moment."}) from None
raise HTTPException(status_code=409, detail="The access change was not verified. Refresh status before retrying or restoring safer mode.") from None
except AgentClientError:
raise HTTPException(status_code=409, detail="The access change was not verified. Refresh status before retrying or restoring safer mode.") from None
async def _host_model_status() -> dict[str, object] | None:
try:
status = await request_agent_json("GET", "/v1/model/status", timeout=2.0)
except AgentClientError:
return None
return status if isinstance(status, dict) else None
async def _local_inference_issue(host_status: object) -> str | None:
# Gateway discovery proves the agent exists, not that its model server is
# reachable. Probe the configured host runtime without spending tokens.
runtime = _active_runtime_projection(host_status)
if runtime and runtime.get("source") == "remote-provider":
return None
# Only a llama-server on the Windows host has a separate process the
# agent must find alive; containers are probed by the service health loop.
if (read_live_env_value("LLM_BACKEND").lower() == "external"
or read_live_env_value("AMD_INFERENCE_LOCATION").lower() != "host"):
return None
try:
telemetry = await request_agent_json("GET", "/v1/llm/status", timeout=3.0)
if (isinstance(telemetry, dict)
and telemetry.get("schema_version") == "ods.host-llm-status.v1"
and isinstance(telemetry.get("health"), dict)
and telemetry["health"].get("status") == "ok"):
return None
except AgentHTTPError as error:
# Linux/WSL hosts do not implement Windows-native telemetry. Its
# absence cannot declare their otherwise discoverable agent offline.
if error.status_code == 501:
return None
except AgentClientError:
pass
return "The local model runtime is unavailable. Restore it in Models before sending another task."
def _unattended_model_hold(status: object) -> bool:
"""A held Portal model transaction that no host lifecycle operation owns.
A model switch owns the host's model_activation lifecycle until it ends,
so a hold without any operation will not finish by itself. Access checks
and settings saves also take the lifecycle, but never own a hold.
"""
if not isinstance(status, dict) or status.get("modelTransactionPending") is not True:
return False
operation = status.get("activeOperation")
return (not status.get("lifecycleActive") and not operation) or operation in _MODEL_NEUTRAL_OPERATIONS
def _model_readiness_issue_from_status(status: object, *, runtime_stopped: bool = False,
unload_ruled_out: bool = False) -> tuple[str, str] | None:
# Unload model keeps the Portal hold until Resume model. An unattended
# hold on a runtime the host proves stopped is that, not a switch.
if runtime_stopped and _unattended_model_hold(status):
return "model_unloaded", _MODEL_UNLOADED_DETAIL
# The host proves it is not an unload either: an interrupted switch that
# nothing will finish by itself. Recover model switch completes or undoes it.
if unload_ruled_out and _unattended_model_hold(status):
return "model_recovery_required", _MODEL_RECOVERY_DETAIL
if isinstance(status, dict) and status.get("modelTransactionPending") is True:
return "model_switching", _MODEL_SWITCH_DETAIL
switching = (
isinstance(status, dict)
and status.get("activeOperation") == "model_activation"
and bool(status.get("lifecycleActive") or status.get("activeOperation"))
)
if switching:
return "model_switching", _MODEL_SWITCH_DETAIL
return None
def _profile_support_reason(profile: dict, status: dict) -> str | None:
"""The most important measured advisory for the active model, if any.
A context below Portal's floor breaks every task, so it comes first; then
a failed tool check, a model never checked, and one that always thinks.
"""
runtime = _active_runtime_projection(status)
context = runtime.get("contextLength") if isinstance(runtime, dict) else None
if (runtime or {}).get("source") == "local-switchboard" and type(context) is int \
and 0 < context < PIXEL_MIN_CONTEXT:
return "context-too-small"
if profile.get("tools") is False:
return "tools-unavailable"
if profile.get("state") == "not-profiled":
return "not-profiled"
if profile.get("thinkingControl") == "always":
return "thinking-always-on"
return None
def _model_support_from_status(status: object) -> dict[str, str] | None:
"""Return fixed advisory metadata without turning model quality into access.
ODS model qualification is a recommendation signal. Pixel's brokers,
approvals, and typed capabilities enforce safety independently of model
intelligence, so an unqualified model remains usable and testable.
With ``ODS_MODEL_PROFILES=enabled`` the host reports the active model's
measured profile and the advisory names its reason; it never blocks a send.
"""
if not isinstance(status, dict):
return None
profile = status.get("activeModelProfile")
if isinstance(profile, dict):
reason = _profile_support_reason(profile, status)
if reason is not None:
return {"tier": "adaptive", "detail": _MODEL_SUPPORT_REASONS[reason], "reason": reason}
if status.get("activeAgentViable") is False:
# Keep the legacy wire value for rolling UI upgrades. It denotes an
# advisory, not evidence that the runtime adapts or the model can act.
return {"tier": "adaptive", "detail": _MODEL_CAPABILITY_DETAIL}
return None
async def _model_readiness_issue() -> tuple[str, str] | None:
"""Return a host-proven model transition or unload hold, if one holds Portal.
A failed host lifecycle probe alone does not take down the Pixel edge.
llama-server serves the one model it was started with, and the router
proves each response's model, so a recorded route needs no live
identity probe. Model quality metadata remains advisory.
"""
return await _model_readiness_issue_for_status(await _host_model_status())
async def _verified_external_host_runtime(host_status: object) -> dict[str, object] | None:
"""Identify a fixed external model from a live probe, never .env alone.
This is a status identity, not a model-switch or agent-quality proof. Do not
expose the configured origin, credentials, or provider response body.
"""
if (
not isinstance(host_status, dict)
or host_status.get("activeRuntime") is not None
or os.environ.get("LLM_BACKEND", "").strip().casefold() != "external"
or read_live_env_value("LLM_BACKEND").strip().casefold() != "external"
or read_live_env_value("ODS_MODEL_SWITCHBOARD").strip().casefold() != "observe"
or read_live_env_value("EXTERNAL_LLM_PROVIDER").strip().casefold() != "openai-compatible"
):
return None
expected = read_live_env_value("EXTERNAL_LLM_MODEL").strip()
if (
re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/+:-]{0,255}", expected) is None
or "://" in expected
):
return None
try:
loaded = await asyncio.wait_for(get_loaded_model(), timeout=3.0)
except (asyncio.TimeoutError, httpx.HTTPError, OSError, ValueError, TypeError):
return None
if loaded != expected:
return None
runtime: dict[str, object] = {"source": "external-host", "model": loaded}
try:
context = await asyncio.wait_for(get_llama_context_size(loaded), timeout=3.0)
except (asyncio.TimeoutError, httpx.HTTPError, OSError, ValueError, TypeError):
context = None
if type(context) is int and 1 <= context <= 10_000_000:
runtime["contextLength"] = context
return _active_runtime_projection({"activeRuntime": runtime})
_runtime_proof: tuple[float, bool | None] | None = None
def _runtime_unloaded(value: object) -> bool | None:
"""Whether a host runtime projection proves the model is unloaded.
True: the owned runtime is stopped, exactly the proof for which the Models
page offers Resume model. False: the host runs the model it owns, or owns
no runtime it could have unloaded. Anything else is unknown (None).
"""
if not isinstance(value, dict):
return None
fields = tuple(value.get(key) for key in ("managed", "canUnload", "running", "canActivate"))
if any(type(field) is not bool for field in fields):
return None
return {(True, True, False, False): True, (True, True, True, True): False,
(False, False, False, False): False}.get(fields)
async def _owned_runtime_unloaded(seconds: float | None = None) -> bool | None:
"""The host's _runtime_unloaded proof for the Windows runtime it owns.
A stopped runtime under a switch that did not reach its held phase is not
an unload. A failed, slow or invalid proof is unknown. It is remembered
too, so a slow host is not asked again on every poll.
"""
global _runtime_proof
if _runtime_proof is not None and time.monotonic() - _runtime_proof[0] < _RUNTIME_PROOF_TTL_SECONDS:
return _runtime_proof[1]
seconds = _RUNTIME_PROOF_SECONDS if seconds is None else seconds
try:
async with async_timeout(seconds):
unloaded = _runtime_unloaded(await request_agent_json(
"GET", "/v1/model/management", timeout=seconds))
if unloaded is True:
# Resume model restarts only an unload's held transaction. The
# host refuses it for a switch that stopped part-way and asks
# for recovery first, so that hold is not an unload.
try:
journal = await request_agent_json("GET", "/v1/model/recovery", timeout=seconds)
except AgentClientError:
journal = None
if isinstance(journal, dict) and journal.get("pending") is True and journal.get("phase") != "held":
unloaded = False
except (asyncio.TimeoutError, AgentClientError):
unloaded = None
_runtime_proof = (time.monotonic(), unloaded)
return unloaded
async def _model_readiness_issue_for_status(status: object) -> tuple[str, str] | None:
# Only an unattended hold needs the runtime proof; a switch in progress
# owns a host lifecycle operation.
unloaded = await _owned_runtime_unloaded() if _unattended_model_hold(status) else None
return _model_readiness_issue_from_status(status, runtime_stopped=unloaded is True,
unload_ruled_out=unloaded is False)
async def _model_activation_in_progress() -> bool:
"""Compatibility wrapper retained for focused lifecycle callers/tests."""
issue = await _model_readiness_issue()
return issue is not None and issue[0] == "model_switching"
async def _bounded_response_bytes(response: httpx.Response, limit: int) -> bytes:
chunks: list[bytes] = []
total = 0
async for chunk in response.aiter_bytes():
total += len(chunk)
if total > limit:
raise ValueError("response too large")
chunks.append(chunk)
return b"".join(chunks)
async def _current_access_readiness():
try:
# Bound the entire transport, including connect/retry time, rather
# than only its socket-read timeout. Diagnostics cannot gate chat.
async with async_timeout(_READINESS_PROBE_SECONDS):
value = await request_agent_json("GET", "/v1/pixel/access-mode", timeout=_READINESS_PROBE_SECONDS)
return _access_projection(value), None
except asyncio.TimeoutError:
return None, "access-probe-timeout"
except AgentClientError:
return None, "access-probe-unavailable"
except (HTTPException, ValueError, TypeError, RecursionError):
return None, "access-probe-invalid"
async def _current_runtime_identity(edge_url, key):
try:
async with async_timeout(_READINESS_PROBE_SECONDS):
client = get_edge_read_client()
async with client.stream("GET", f"{edge_url}/v1/runtime-identity",
headers=_edge_headers(key, accept="application/json"),
timeout=httpx.Timeout(_READINESS_PROBE_SECONDS)) as response:
if response.status_code == 200 and response.headers.get("content-type", "").lower().startswith("application/json"):
return project_runtime_identity(json.loads(await _bounded_response_bytes(response, 8192)))
except (httpx.HTTPError, asyncio.TimeoutError, ValueError, TypeError, RecursionError):
pass
return unknown_runtime_identity()
# The gateway can answer its model list late while it works through a large
# step. On the RTX Spark (2026-10-25) a status poll waited about 10 s while a
# 27 KB page was being written, its edge call failed, and the composer flashed
# "Portal is unavailable" mid-build. Within this grace a transient edge failure
# repeats the last available answer; definitive states (unloaded, switching,
# recovery, a missing model) answer at once and clear it.
_STATUS_GRACE_SECONDS = 20.0
_last_available_status: tuple[float, dict[str, object]] | None = None
@router.get("/status", dependencies=[Depends(verify_api_key)])
async def pixel_status(http_response: Response = None) -> dict[str, object]:
"""Return a fixed, nonsecret Pixel availability projection."""
global _last_available_status
# The browser-facing response is newly constructed, so upstream no-store
# headers do not survive automatically. Never cache a live identity check.
if http_response is not None:
http_response.headers["Cache-Control"] = "no-store"
result, transient = await _status_projection()
remembered = _last_available_status
if transient and remembered is not None and time.monotonic() - remembered[0] <= _STATUS_GRACE_SECONDS:
return dict(remembered[1])
_last_available_status = (time.monotonic(), dict(result)) if result.get("available") is True else None
return result
async def _status_projection() -> tuple[dict[str, object], bool]:
"""The status answer, and whether it is only a transient edge failure."""
config = _pixel_config()
if config is None:
return {"available": False, "model": None, "detail": "Portal is not enabled"}, False
host_status, (access, access_issue) = await asyncio.gather(
_host_model_status(), _current_access_readiness())
activation = model_activation_status(host_status)
activation_metadata = {"modelActivation": activation} if activation else {}
# Bootstrap promotion owns the root coordinator's journal rather than
# the host agent's model journal. Observe its validated hold before
# probing the backend that the coordinator may currently be restarting.
if access and access["available"] and access["pending"] and access["reason"] == "model-transition-pending":
return {**activation_metadata, "available": False, "model": None, "state": "model_transition_pending",
"detail": _MODEL_HOLD_DETAIL}, False
if access and access["available"] and access["reason"] == "chat-recovery-required":
return {**activation_metadata, "available": False, "model": None, "state": "chat_recovery_required",
"detail": _CHAT_RECOVERY_DETAIL, **_recovery_field(_access_recovery(access))}, False
readiness_issue = await _model_readiness_issue_for_status(host_status)
if readiness_issue is not None:
state, detail = readiness_issue
return {
**activation_metadata,
"available": False,
"model": None,
"state": state,
"detail": detail,
**_recovery_field(_STATE_RECOVERY.get(state)),
}, False
edge_url, key = config
try:
timeout = httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=5.0)
client = get_edge_read_client()
async with client.stream(
"GET",
f"{edge_url}/v1/models",
headers=_edge_headers(key, accept="application/json"),
timeout=timeout,
) as response:
if response.status_code != 200:
return {**activation_metadata, "available": False, "model": None, "detail": "Portal service is unavailable"}, True
if not response.headers.get("content-type", "").lower().startswith("application/json"):
return {**activation_metadata, "available": False, "model": None, "detail": "Portal service returned an invalid response"}, True
raw = await _bounded_response_bytes(response, _MAX_STATUS_BYTES)
payload = json.loads(raw)
models = payload.get("data") if isinstance(payload, dict) else None
available = isinstance(models, list) and any(
isinstance(item, dict) and item.get("id") == _MODEL for item in models
)
result: dict[str, object] = {
"available": available,
"model": _MODEL if available else None,
"detail": "Owner agent ready" if available else "Portal model is unavailable",
}
if available:
inference_issue = await _local_inference_issue(host_status)
if inference_issue:
# A stopped runtime the host owns gets Models' Resume model.
stopped = await _owned_runtime_unloaded(_RUNTIME_HINT_SECONDS) is True
# A health probe that misses its 3 s while the runtime generates
# a large step (RTX Spark, 2026-10-25) is not proof it stopped:
# only a runtime the host proves stopped answers at once.
return {**activation_metadata, "available": False, "model": None, "state": "model_unavailable",
"detail": _RUNTIME_STOPPED_DETAIL if stopped else inference_issue,
**_recovery_field("resume-model" if stopped else None)}, not stopped
runtime = _active_runtime_projection(host_status)
if available and runtime is None:
runtime = await _verified_external_host_runtime(host_status)
if available and runtime is not None:
result["runtime"] = runtime
model_support = _model_support_from_status(host_status)
if available and model_support is not None:
result["modelSupport"] = model_support
# Availability is not installed-release verification. A missing, old,
# or malformed diagnostic route must not disable otherwise working chat.
identity = unknown_runtime_identity()
if available:
identity = await _current_runtime_identity(edge_url, key)
result.update(activation_metadata)
result["runtimeIdentity"] = identity
result["runtimeMatchesRelease"] = identity["runtimeMatchesRelease"]
readiness = project_readiness(available, access, identity, access_issue)
result["readiness"] = readiness
if available:
# Only a host that reports no open model transaction lets a held
# access transition be offered Restore Sandbox.
settled = isinstance(host_status, dict) and host_status.get("modelTransactionPending") is False
result.update(_recovery_field(_access_recovery(access, model_hold_possible=not settled)))
result["detail"] = "Owner agent available; " + ("runtime files changed since initialization" if identity["state"] == "mismatch"
else "release identity is not fully verified")
if readiness["accessState"] == "failed":
result["detail"] = "Owner agent available; host access verification failed; effective access and release readiness are unverified"
elif readiness["accessState"] == "transitioning":
result["detail"] = ("Owner agent available; model transition needs recovery; release readiness is unverified"
if readiness["reasonCode"] == "model-transition-recovery-required" else
"Owner agent available; access transition is unfinished; release readiness is unverified")
return result, False
except (httpx.HTTPError, asyncio.TimeoutError) as exc:
# Exception text and request objects can contain upstream credentials.
# Retain the failure phase/type without logging those sensitive values.
logger.warning("Pixel edge status request failed (%s)", type(exc).__name__)
return {**activation_metadata, "available": False, "model": None, "detail": "Portal service is unavailable"}, True
except (json.JSONDecodeError, UnicodeDecodeError, ValueError, TypeError):
return {**activation_metadata, "available": False, "model": None, "detail": "Portal service returned an invalid response"}, True
@router.get("/ops/{job_id}", dependencies=[Depends(verify_api_key)])
async def pixel_operations_status(job_id: str, plan_hash: str) -> dict[str, object]:
"""Return only a host-verified, nonsecret Operations status receipt."""
if _OPS_JOB_ID.fullmatch(job_id) is None or _OPS_PLAN_HASH.fullmatch(plan_hash) is None:
raise HTTPException(status_code=400, detail="Invalid Portal Operations receipt")
try:
value = await request_agent_json(
"GET",
"/v1/pixel/ops-status",
params={"job_id": job_id, "plan_hash": plan_hash},
timeout=7.0,
)
except AgentClientError as exc:
raise HTTPException(status_code=503, detail="Portal Operations status is unavailable") from exc
expected = {
"schemaVersion",
"kind",
"jobId",
"planHash",
"status",
"riskTier",
"approvalRequired",
"updatedAt",
"approvalCommand",
}
command = value.get("approvalCommand")
if (
set(value) != expected
or value.get("schemaVersion") != 1
or value.get("kind") != "ods-pixel-operations-status"
or value.get("jobId") != job_id
or value.get("planHash") != plan_hash
or value.get("status") not in _OPS_STATUSES
or not isinstance(value.get("riskTier"), str)
or re.fullmatch(r"[a-z][a-z-]{0,31}", value["riskTier"]) is None
or not isinstance(value.get("approvalRequired"), bool)
or not isinstance(value.get("updatedAt"), str)
or not 1 <= len(value["updatedAt"]) <= 64
or (command is not None and (not isinstance(command, str) or not 1 <= len(command) <= 4096))
):
raise HTTPException(status_code=502, detail="Portal Operations returned an invalid status")
return {key: value[key] for key in expected}
def _error_event(message: str) -> bytes:
payload = {"error": {"message": message, "type": "pixel_dashboard_error"}}
return f"data: {json.dumps(payload)}\n\n".encode()
async def _cancel_edge_run(edge_url: str, key: str, chat_id: str) -> bool:
"""Best-effort cancellation over the fixed authenticated internal edge."""
# Edge can wait 20 s for harness and managed-project cleanup.
timeout = httpx.Timeout(connect=2.0, read=22.0, write=2.0, pool=2.0)
try:
async with httpx.AsyncClient(
timeout=timeout,
trust_env=False,
follow_redirects=False,
) as client:
async with client.stream(
"POST",
f"{edge_url}/v1/chat/cancel",
json={"user": chat_id},
headers=_edge_headers(key, accept="application/json"),
) as response:
if response.status_code != 200:
return False
if not response.headers.get("content-type", "").lower().startswith(
"application/json"
):
return False
raw = await _bounded_response_bytes(response, 1024)
parsed = json.loads(raw)
return (
isinstance(parsed, dict)
and set(parsed) == {"aborted"}
and parsed.get("aborted") is True
)
except (
httpx.HTTPError,
asyncio.TimeoutError,
json.JSONDecodeError,
UnicodeDecodeError,
ValueError,
TypeError,
):
return False
@router.post("/chat/cancel")
async def pixel_chat_cancel(body: ChatCancelRequest, owner: str = Depends(verify_api_key)) -> dict[str, bool]:
"""Cancel only the active run for this validated dashboard conversation.
The explicit endpoint makes the owner's Stop action independent of HTTP
disconnect propagation. The stream finalizer retains the same cancellation
call as an idempotent fallback for tab closes and network failures.
"""
config = _pixel_config()
if config is None:
raise HTTPException(status_code=503, detail="Portal is not enabled")
edge_url, key = config
if body.request_id is not None:
store = _chat_results()
identity = (owner_namespace(owner), body.chat_id, body.request_id)
row = _result_state(store, identity)
# Interrupted receipts still need native abort/idle confirmation. An
# old receipt must never cancel a successor in the same conversation.
if row is None or row["state"] not in {"active", "unresolved", "interrupted"}:
return {"aborted": False}
recovering_interrupted = row["state"] == "interrupted"
if recovering_interrupted and not store.is_latest(identity):
return {"aborted": False}
# A reserved attempt can still be checking local readiness and identity.
# There is no native run to cancel until its producer has been created.
if identity in _result_preflights:
return {"aborted": False}
if identity[:2] in _result_stops:
return {"aborted": False}
_result_stops.add(identity[:2])
try:
aborted = await _cancel_edge_run(edge_url, key, body.chat_id)
if aborted:
entry = store.get(identity)
if entry is None or entry["state"] == "complete":
return {"aborted": False}
_result_abort_ack.add(identity)
task = _result_tasks.get(identity)
if task is not None and not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
entry = store.get(identity)
if entry is None or entry["state"] == "complete":
return {"aborted": False}
# Native cancellation may end the producer with an upstream
# error before its acknowledgement returns. Use the fresh row:
# finish() deliberately cannot rewrite an interrupted receipt.
if entry["state"] == "interrupted":
return {"aborted": store.confirm_interrupted_cancel(identity)}
store.finish(identity, "cancelled")
return {"aborted": aborted}
finally:
_result_abort_ack.discard(identity)
_result_stops.discard(identity[:2])
if isinstance(owner, str):
conversation = (owner_namespace(owner), body.chat_id)
# A restarted API process has not opened the store yet, but receipts
# its predecessor left unfinished still hold this chat.
pending = _chat_results().pending_attempts(conversation)
if pending:
# A chat-level request ("Continue in this chat") never stops a turn
# this process is still streaming; that turn's own Stop names it.
# An attempt no producer owns any more is resolved by its exact ID.
if _owns_live_work(conversation):
return {"aborted": False}
return await pixel_chat_cancel(ChatCancelRequest(chat_id=body.chat_id, request_id=pending[0][2]), owner)
return {"aborted": await _cancel_edge_run(edge_url, key, body.chat_id)}
def _owns_live_work(conversation) -> bool:
"""True while this process streams, prepares or stops a turn of this chat."""
return (conversation in _result_stops
or any(identity[:2] == conversation for identity in _result_preflights)
or any(identity[:2] == conversation and not task.done() for identity, task in _result_tasks.items()))
async def _edge_chat_activity(edge_url: str, key: str, chat_id: str) -> str | None:
"""The edge's exact view of one chat, or None when it could not be read."""
try:
timeout = httpx.Timeout(connect=2.0, read=5.0, write=2.0, pool=2.0)
async with httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False) as client:
async with client.stream("POST", f"{edge_url}/v1/chat/activity",
json={"user": chat_id},
headers=_edge_headers(key, accept="application/json")) as response:
if response.status_code != 200 or not response.headers.get("content-type", "").lower().startswith("application/json"):
return None
raw = await _bounded_response_bytes(response, 1024)
parsed = json.loads(raw)
if (isinstance(parsed, dict) and set(parsed) == {"state"}
and isinstance(parsed["state"], str) and parsed["state"] in {"active", "terminal", "unknown"}):
return parsed["state"]
except (httpx.HTTPError, asyncio.TimeoutError, ValueError, TypeError):
pass
return None
async def _settle_edge_chat(edge_url: str, key: str, chat_id: str) -> str | None:
"""Ask the ingress, through the edge, to settle a chat it proves idle.
"settled" means no run of this chat can still be alive and any turn a
restart cut off is recorded as interrupted; "active" means work may still
run. Nothing is ever stopped. None means it could not be confirmed, for
example while Portal is still restarting or on an older edge or ingress.
"""
try:
timeout = httpx.Timeout(connect=2.0, read=10.0, write=2.0, pool=2.0)
async with httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False) as client:
async with client.stream("POST", f"{edge_url}/v1/chat/settle",
json={"user": chat_id},
headers=_edge_headers(key, accept="application/json")) as response:
if response.status_code != 200 or not response.headers.get("content-type", "").lower().startswith("application/json"):
return None
raw = await _bounded_response_bytes(response, 1024)
parsed = json.loads(raw)
if (isinstance(parsed, dict) and set(parsed) == {"state"}
and isinstance(parsed["state"], str) and parsed["state"] in {"settled", "active"}):
return parsed["state"]
except (httpx.HTTPError, asyncio.TimeoutError, ValueError, TypeError):
pass
return None
@router.post("/chat/activity")
async def pixel_chat_activity(body: ChatCancelRequest, owner: str = Depends(verify_api_key)) -> dict[str, str]:
"""One authenticated chat lookup; global activity never supplies its state.
A turn this process still streams is active. Otherwise, when no stream of
this chat passes through the edge, the host ingress is asked to settle the
chat: under its history lock it proves the native session idle before it
records a turn that a restart cut off as interrupted, and it never stops a
run. Only that proof turns the chat terminal here, and it also releases
receipts no producer owns any more, so the chat can take its next message.
"""
config = _pixel_config()
if config is None:
return {"state": "unknown"}
edge_url, key = config
conversation = (owner_namespace(owner), body.chat_id) if isinstance(owner, str) else None
if conversation is not None and _owns_live_work(conversation):
return {"state": "active"}
state = await _edge_chat_activity(edge_url, key, body.chat_id)
if state is None:
return {"state": "unknown"}
if state == "active" or conversation is None:
return {"state": state}
# A Stop, a turn or another check may have started here during that read.
# It owns the chat now; settling beside it could race its outcome.
if _owns_live_work(conversation) or conversation in _result_settles:
return {"state": "active"}
# Fence this process's own next attempt so it cannot race the history
# lock. A Stop keeps its own fence; only this check removes this one.
_result_settles.add(conversation)
try:
settled = await _settle_edge_chat(edge_url, key, body.chat_id)
if settled == "settled" and _owns_live_work(conversation):
# A Stop that started meanwhile settles its own receipt.
settled = "active"
if settled == "settled":
store = _chat_results()
for identity in store.pending_attempts(conversation):
row = _result_state(store, identity)
if row is not None and row["state"] == "unresolved":
# No producer owns this receipt and the ingress proved the
# chat idle. Keep every saved chunk; never call it complete.
store.finish(identity, "interrupted")
finally:
_result_settles.discard(conversation)
if settled == "settled":
return {"state": "terminal"}
if settled == "active":
return {"state": "active"}
# An older edge or ingress cannot settle. Its own memory that the chat
# ended does not free a chat that a receipt still holds: the next message
# would only be refused.
if state == "terminal" and _chat_results().pending_attempts(conversation):
return {"state": "unknown"}
return {"state": state}
_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_OPEN_SECONDS = 42.0
class ExampleProjectOpenRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=64)
@field_validator("name")
@classmethod
def _example_name(cls, value: str) -> str:
if not _EXAMPLE_PROJECT_NAME.fullmatch(value):
raise ValueError("invalid example project name")
return value
def _example_projects(value) -> dict[str, object]:
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[str, object]:
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)}}
@router.get("/example-projects", dependencies=[Depends(verify_api_key)])
async def pixel_example_projects() -> dict[str, object]:
"""The shipped example projects (Elf of Doom) whose folder is in the owner's workspace.
Portal's sidebar lists them with the other Playground projects. A deleted
or renamed folder is simply absent. Without Portal there are none.
"""
config = _pixel_config()
if config is None:
return {"schemaVersion": 1, "projects": []}
edge_url, key = config
try:
timeout = httpx.Timeout(connect=2.0, read=6.0, write=2.0, pool=2.0)
async with httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False) as client:
async with client.stream("GET", f"{edge_url}/v1/example-projects",
headers=_edge_headers(key, accept="application/json")) as response:
if response.status_code != 200 or not response.headers.get("content-type", "").lower().startswith("application/json"):
raise ValueError("example projects unavailable")
raw = await _bounded_response_bytes(response, 4096)
return _example_projects(json.loads(raw))
except (httpx.HTTPError, asyncio.TimeoutError, ValueError, TypeError, RecursionError) as exc:
raise HTTPException(status_code=503, detail="Portal could not list its example projects.") from exc
@router.post("/example-projects/open", dependencies=[Depends(verify_api_key)])
async def pixel_example_project_open(body: ExampleProjectOpenRequest) -> dict[str, object]:
"""Open one shipped example project in Portal's Workspace preview, with no model run.
The host publishes the owner's existing Playground/<name> folder through
the same create-only preview service a model run uses and returns its
verified receipt. Nothing in the workspace is written.
"""
config = _pixel_config()
if config is None:
raise HTTPException(status_code=503, detail="Portal is not set up on this ODS install.")
edge_url, key = config
try:
timeout = httpx.Timeout(connect=2.0, read=_EXAMPLE_OPEN_SECONDS, write=2.0, pool=2.0)
async with httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False) as client:
async with client.stream("POST", f"{edge_url}/v1/example-projects", json={"name": body.name},
headers=_edge_headers(key, accept="application/json")) as response:
if response.status_code == 404:
raise HTTPException(status_code=404,
detail="This example project is no longer in your Portal workspace.")
if response.status_code == 422:
raise HTTPException(status_code=422,
detail="This example project's folder is still there, but it cannot open as the example.")
if response.status_code == 409:
raise HTTPException(status_code=409,
detail="Some files in this example project's folder cannot be previewed.")
if response.status_code != 200 or not response.headers.get("content-type", "").lower().startswith("application/json"):
raise ValueError("example preview unavailable")
raw = await _bounded_response_bytes(response, 8192)
return _example_preview(json.loads(raw), body.name)
except (httpx.HTTPError, asyncio.TimeoutError, ValueError, TypeError, RecursionError) as exc:
raise HTTPException(status_code=503, detail="Portal could not publish the example project's preview.") from exc
class _ClientDisconnected(Exception):
"""The dashboard consumer left while Pixel was still producing a turn."""
async def _retained_chat_stream(request, body, owner):
await conversation_storage("assert_available", owner, body.chat_id)
store = _chat_results()
identity = (owner_namespace(owner), body.chat_id, body.request_id)
fingerprint_input = [m.model_dump() for m in body.messages]
if body.history_snapshot is not None:
fingerprint_input = {"messages": fingerprint_input, "history_snapshot": body.history_snapshot.model_dump()}
if body.image_route is not None:
fingerprint_input = {"conversation": fingerprint_input, "image_route": body.image_route.model_dump()}
fingerprint = hashlib.sha256(json.dumps(fingerprint_input, sort_keys=True, ensure_ascii=True).encode()).hexdigest()
try:
if identity[:2] in _result_stops:
raise ResultConflict("Stop is still being confirmed")
if identity[:2] in _result_settles:
raise ResultConflict("The last turn of this chat is still being checked")
created = store.reserve(identity, fingerprint)
except ResultConflict as exc:
raise HTTPException(status_code=423, detail=str(exc)) from None
except ResultCapacity as exc:
raise HTTPException(status_code=507, detail=str(exc)) from None
if created:
_result_preflights.add(identity)
try:
try:
config = _pixel_config()
if config is None:
raise HTTPException(status_code=503, detail="Portal is not enabled")
issue = await _model_readiness_issue()
if issue is not None:
raise HTTPException(status_code=409, detail=issue[1])
messages = await _prepare_chat_messages(body, owner)
await conversation_storage("assert_available", owner, body.chat_id)
except Exception as exc:
# The attempt ID was committed, but no producer or agent turn
# was started. Retain an exact terminal receipt for reloads.
text = "Portal did not start this attempt. Restore its connection and send your message again."
frame = {"choices": [{"delta": {"content": text}}]}
data = f"data: {json.dumps(frame)}\n\n".encode() + _error_event(text) + b"data: [DONE]\n\n"
deleted = (isinstance(exc, HTTPException) and exc.status_code == 410
and isinstance(exc.detail, dict) and exc.detail.get("code") == "conversation_deleted")
store.reject_before_submission(identity, data, rejected=deleted)
raise
begin_pixel_stream()
task = asyncio.create_task(_produce_retained_result(store, identity, body, config, messages, owner=owner))
_result_tasks[identity] = task
def release(finished):
_result_tasks.pop(identity, None)
end_pixel_stream()
if not finished.cancelled() and finished.exception() is not None:
logger.error("Pixel result persistence failed (%s)", type(finished.exception()).__name__)
task.add_done_callback(release)
finally:
_result_preflights.discard(identity)
async def subscribe():
after = -1
last_sent = time.monotonic()
while True:
# Snapshot terminal state before yielding any bytes. Sending a chunk
# can suspend this subscriber while the producer commits its tail.
# If it was active, take another snapshot before deciding to close.
row = _result_state(store, identity)
for chunk in store.chunks(identity, after):
after = chunk["sequence"]
yield chunk["data"]
last_sent = time.monotonic()
if row is None or row["state"] != "active":
return
if await request.is_disconnected():
return
if time.monotonic() - last_sent >= _STREAM_KEEPALIVE_SECONDS:
# A CPU-backed local model can spend minutes in prompt prefill.
# Keep the subscriber alive without inventing an answer or
# persisting transport-only comments in the result receipt.
yield _STREAM_KEEPALIVE
last_sent = time.monotonic()
# Subscriber disposal never cancels the independent bounded producer.
await asyncio.sleep(_CLIENT_DISCONNECT_POLL_SECONDS)
return StreamingResponse(subscribe(), media_type="text/event-stream", headers={
"Cache-Control": "no-cache, no-store", "X-Accel-Buffering": "no",
})
async def _produce_retained_result(store, identity, body, config, messages, *, owner=None):
edge_url, key = config
done_seen = False
answer_seen = False
empty_done_seen = False
terminal_error_seen = False
cancelled = False
failed = False
stopped = False
rejected = False
admission_rejected = False
admission_code = "transition_in_progress"
gateway_refusal_confirmed = False
gateway_refusal_line = None
upstream_event_seen = False
routing_rollback_failed = False
extension_preparation: dict = {}
oversized_image = False
try:
extension_context = None
if owner is not None and body.messages and body.messages[-1].role == 'user':
from routers.extensions import chat_extension_request_context
extension_context = await chat_extension_request_context(
owner, body.chat_id, body.request_id, body.messages[-1].content, include_evidence=True,
preparation=extension_preparation)
timeout = httpx.Timeout(connect=5.0, read=_CHAT_STREAM_TIMEOUT_SECONDS, write=30.0, pool=5.0)
async with async_timeout(_CHAT_STREAM_TIMEOUT_SECONDS):
async with httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False) as client:
async with client.stream("POST", f"{edge_url}/v1/chat/completions",
**_edge_request_arguments(_edge_chat_body(body, messages, extension_context=extension_context),
image_turn=bool(body.messages[-1].images)),
headers=_edge_headers(key, accept="text/event-stream", image_turn=bool(body.messages[-1].images))) as upstream:
rejected = 400 <= upstream.status_code < 500
if upstream.status_code == 409:
# Only Edge's exact admission refusal proves this turn
# never reached the agent. Never echo an upstream body
# or classify an arbitrary conflict as safe to retry.
try:
raw = await _bounded_response_bytes(upstream, 1024)
admission_rejected = json.loads(raw) == {"error": "pixel_transition_in_progress"}
except (ValueError, UnicodeDecodeError):
pass
elif upstream.status_code == 429:
# Edge has one image slot. It refuses another image turn
# with this exact body before admitting it, so nothing
# ran: tell the owner Portal was busy, not that it failed.
try:
raw = await _bounded_response_bytes(upstream, 1024)
if json.loads(raw) == {"error": "image processing busy; retry shortly"}:
admission_rejected = True
admission_code = "image_turn_busy"
except (ValueError, UnicodeDecodeError):
pass
if upstream.status_code != 200 or not upstream.headers.get("content-type", "").lower().startswith("text/event-stream"):
raise ValueError("Invalid upstream stream")
buffered = bytearray()
async for chunk in upstream.aiter_bytes():
buffered.extend(chunk)
while b"\n" in buffered:
newline = buffered.index(b"\n")
line = bytes(buffered[:newline + 1])
del buffered[:newline + 1]
if len(line.rstrip(b"\r\n")) > _MAX_SSE_LINE_BYTES:
raise ResultCapacity("SSE line limit")
stripped = line.rstrip(b"\r\n")
if gateway_refusal_line is not None and stripped != b"data: [DONE]":
if not stripped or stripped.startswith(b":"):
continue
# Extra upstream data invalidates the exact no-run
# receipt. Keep the ordinary uncertain-error path.
store.append(identity, gateway_refusal_line)
gateway_refusal_line = None
terminal_error_seen = True
failed = True
if stripped.startswith(b"data: ") and stripped != b"data: [DONE]":
try:
event = json.loads(stripped[6:])
except (json.JSONDecodeError, UnicodeDecodeError):
event = None
if not upstream_event_seen and event == {"error": {
"type": "pixel_ingress_error", "code": "gateway_connect_refused"}}:
# This exact trusted ingress receipt is usable
# only with its terminator and no prior run
# evidence. Withhold it until owned extension
# preparation is rolled back in finally.
gateway_refusal_line = line
upstream_event_seen = True
continue
upstream_event_seen = True
if isinstance(event, dict):
if "error" in event:
# The admission receipt namespace is
# owned here, never by an upstream SSE
# producer that may already have run.
if isinstance(event["error"], dict) and event["error"].get("type") == "pixel_dashboard_error":
line = _error_event("Portal could not complete the response.").rstrip(b"\n") + b"\n"
# A syntactically terminal SSE stream can still be
# a failed attempt. Keep its sanitized error bytes
# for replay, but never publish it as complete.
terminal_error_seen = True
failed = True
choices = event.get("choices")
for choice in choices if isinstance(choices, list) else []:
if not isinstance(choice, dict):
continue
for field in ("delta", "message"):
payload = choice.get(field)
if isinstance(payload, dict) and (
(isinstance(payload.get("content"), str) and payload["content"])
or bool(payload.get("tool_calls"))
or bool(payload.get("function_call"))
):
answer_seen = True
if stripped == b"data: [DONE]":
if gateway_refusal_line is not None:
admission_rejected = True
admission_code = "gateway_connect_refused"
gateway_refusal_confirmed = True
terminal_error_seen = True
failed = True
done_seen = True
break
if not answer_seen and not terminal_error_seen:
# Live Pixel Edge cancellations can end with only
# [DONE]. The host session reports zero output and
# aborted, so a syntactic DONE is not a user answer.
# Do not persist it as a successful receipt.
terminal_error_seen = True
empty_done_seen = True
failed = True
store.append(identity, _error_event("Portal returned no answer. Try again.")
+ b"data: [DONE]\n\n", terminal=True)
else:
# The upstream blank separator remains in the
# buffer when this terminal line ends the loop.
# Persist one complete SSE event for live clients
# and replay, including an upstream error frame.
store.append(identity, b"data: [DONE]\n\n")
done_seen = True
break
store.append(identity, line)
if done_seen:
break
if len(buffered) > _MAX_SSE_LINE_BYTES:
raise ResultCapacity("SSE line limit")
if not done_seen:
failed = True
except HTTPException as exc:
oversized_image = exc.status_code == 413 and bool(body.messages[-1].images)
rejected = oversized_image
failed = True
except asyncio.CancelledError:
cancelled = identity in _result_abort_ack
failed = not cancelled
except Exception as exc:
failed = True
logger.warning("Pixel retained stream failed (%s)", type(exc).__name__)
finally:
if admission_rejected and extension_preparation:
try:
from routers.extensions import rollback_chat_extension_request
await rollback_chat_extension_request(owner, body.chat_id, body.request_id, extension_preparation)
except (Exception, asyncio.CancelledError) as exc:
# A safe-to-resend receipt also promises that this turn left no
# new actionable routing. Reserve the attempt if that cannot
# be persisted; never fabricate a successful rollback.
admission_rejected = False
routing_rollback_failed = True
logger.warning("Pixel admission routing rollback failed (%s)", type(exc).__name__)
# Keep this conversation reserved until cancellation has finished. A late
# native cancellation must never target the next attempt in this chat.
if not done_seen and not cancelled and not rejected:
try:
stopped = await asyncio.wait_for(_cancel_edge_run(edge_url, key, body.chat_id), _CLIENT_CANCEL_TIMEOUT_SECONDS)
except (asyncio.TimeoutError, asyncio.CancelledError):
pass
try:
if not done_seen or gateway_refusal_confirmed:
text = ("Portal was stopped." if cancelled else
"This image turn exceeds the 16 MiB encoded limit. Reduce attachments or conversation text." if oversized_image else
"Portal did not accept this turn. Check the conversation's context status before continuing." if rejected else
"Portal could not complete the response. Check saved work before continuing.")
if admission_rejected:
event = {"error": {"type": "pixel_dashboard_error", "code": admission_code}}
data = f"data: {json.dumps(event)}\n\ndata: [DONE]\n\n".encode()
else:
data = _error_event(text) + b"data: [DONE]\n\n"
store.append(identity, data, terminal=True)
finally:
state = (
"unresolved" if routing_rollback_failed
else "complete" if done_seen and not terminal_error_seen
else "cancelled" if cancelled
# A DONE-only frame can overtake the Edge Stop acknowledgment.
# Keep the attempt reserved until Stop resolves; an acknowledged
# abort then commits cancelled, while an unacknowledged native
# run must remain unresolved instead of admitting a successor.
else "unresolved" if empty_done_seen and identity[:2] in _result_stops
else "rejected" if admission_rejected
else "interrupted" if rejected or terminal_error_seen or failed and stopped
else "unresolved" if failed
else "complete"
)
store.finish(identity, state)
async def _prepare_chat_messages(body, owner):
if body.image_route is not None:
state = await _chat_context_request(ChatCancelRequest(chat_id=body.chat_id))
model = state.get("model") or {}
if (model.get("imageRouteFingerprint") or model.get("routeFingerprint")) != body.image_route.routeFingerprint:
raise HTTPException(409, "The model route changed. Review the selected model before sending images.")
capability = model.get("imageInput")
if capability == "unsupported":
raise HTTPException(409, "The selected model is declared text-only. Choose an image-capable model.")
if capability not in {"supported", "unknown"}:
raise HTTPException(409, "Image support for the selected runtime has not been verified.")
if capability == "unknown" and not body.image_route.unknownConsent:
raise HTTPException(409, "Image support is unknown. Confirm an image test on this model route first.")
messages = await messages_with_identity(body.messages)
latest = body.messages[-1]
if latest.images is not None:
parts = await resolve_message_images(owner, body.chat_id, latest.content,
[image.model_dump() for image in latest.images])
# Identity injection inserts a system message; the final owner turn
# remains last. Preserve references for Edge/ingress integrity checks.
messages[-1] = {**messages[-1], "content": parts}
_image_json_size(_edge_chat_body(body, messages))
return messages
def _image_json_size(payload):
total = 0
for token in json.JSONEncoder(ensure_ascii=True).iterencode(payload):
total += len(token)
if total > 16 * 1024 * 1024:
raise HTTPException(413, "Image turn exceeds the 16 MiB encoded limit. Reduce attachments or conversation text.")
return total
def _edge_request_arguments(payload, *, image_turn):
if not image_turn:
return {"json": payload}
_image_json_size(payload)
async def encoded():
for token in json.JSONEncoder(ensure_ascii=True).iterencode(payload):
for offset in range(0, len(token), 32768):
yield token[offset:offset + 32768].encode("ascii")
await asyncio.sleep(0)
return {"content": encoded()}
def _edge_chat_body(body, messages, *, extension_context=None):
from extension_requests import model_request_context
latest = body.messages[-1] if body.messages else None
context = extension_context or (model_request_context(latest.content, body.chat_id, body.request_id) if latest and latest.role == 'user' else None)
if context:
position = next((index for index, item in enumerate(messages) if item['role'] != 'system'), len(messages))
messages = [*messages[:position], context, *messages[position:]]
result = {"model": _MODEL, "stream": True, "user": body.chat_id, "messages": messages}
if body.history_snapshot is not None:
result["history_snapshot"] = body.history_snapshot.model_dump()
result["request_id"] = body.request_id
if body.image_route is not None:
result["image_route"] = body.image_route.model_dump()
return result
async def _iter_upstream_chunks(
upstream: httpx.Response,
request: Request,
can_emit_keepalive: Callable[[], bool],
) -> AsyncIterator[bytes]:
"""Yield upstream bytes while promptly observing a silent client exit."""
iterator = upstream.aiter_bytes().__aiter__()
pending: asyncio.Task[bytes] | None = None
last_sent = time.monotonic()
try:
while True:
pending = asyncio.create_task(anext(iterator))
while not pending.done():
done, _ = await asyncio.wait(
{pending},
timeout=_CLIENT_DISCONNECT_POLL_SECONDS,
)
if done:
break
if await request.is_disconnected():
raise _ClientDisconnected
# A comment is safe only between complete SSE lines. The
# caller may be holding an upstream fragment without a newline;
# injecting a comment there would corrupt that data line.
if can_emit_keepalive() and time.monotonic() - last_sent >= _STREAM_KEEPALIVE_SECONDS:
yield _STREAM_KEEPALIVE
last_sent = time.monotonic()
try:
chunk = pending.result()
except StopAsyncIteration:
return
pending = None
yield chunk
last_sent = time.monotonic()
finally:
if pending is not None and not pending.done():
pending.cancel()
await asyncio.gather(pending, return_exceptions=True)
close = getattr(iterator, "aclose", None)
if callable(close):
await close()
@router.post("/chat/stream")
async def pixel_chat_stream(request: Request, body: ChatStreamRequest, owner: str = Depends(verify_api_key)) -> StreamingResponse:
"""Forward one bounded chat over authenticated, unbuffered SSE."""
if isinstance(owner, str):
await conversation_storage("assert_available", owner, body.chat_id)
if body.request_id is not None:
return await _retained_chat_stream(request, body, owner)
if isinstance(owner, str) and _result_store is not None and _result_store.has_pending((owner_namespace(owner), body.chat_id)):
raise HTTPException(status_code=423, detail="Recover or stop the retained attempt before starting another turn")
config = _pixel_config()
if config is None:
raise HTTPException(status_code=503, detail="Portal is not enabled")
readiness_issue = await _model_readiness_issue()
if readiness_issue is not None:
_state, detail = readiness_issue
raise HTTPException(status_code=409, detail=detail)
edge_url, key = config
edge_body = _edge_chat_body(body, await messages_with_identity(body.messages))
# Pixel Edge is capped at 33 minutes; retain one bounded minute of outer
# headroom so this bridge never aborts a valid CPU-only first turn first.
timeout = httpx.Timeout(
connect=5.0,
read=_CHAT_STREAM_TIMEOUT_SECONDS,
write=30.0,
pool=5.0,
)
client = None
upstream_context = None
entered = False
released = False
done_seen = False
async def release_stream():
nonlocal released
if released:
return
released = True
try:
try:
if entered and not done_seen:
cancel_task = asyncio.create_task(_cancel_edge_run(edge_url, key, body.chat_id))
try:
await asyncio.wait_for(asyncio.shield(cancel_task), timeout=_CLIENT_CANCEL_TIMEOUT_SECONDS)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
finally:
try:
if entered:
await upstream_context.__aexit__(None, None, None)
finally:
if client is not None:
await client.aclose()
finally:
end_pixel_stream()
if not try_begin_pixel_stream():
raise HTTPException(status_code=429, detail="Portal stream capacity is busy; retry shortly")
try:
client = httpx.AsyncClient(timeout=timeout, trust_env=False, follow_redirects=False)
upstream_context = client.stream(
"POST",
f"{edge_url}/v1/chat/completions",
json=edge_body,
headers=_edge_headers(key, accept="text/event-stream"),
)
try:
upstream = await upstream_context.__aenter__()
entered = True
except (httpx.HTTPError, asyncio.TimeoutError) as exc:
logger.warning("Pixel edge stream connection failed (%s)", type(exc).__name__)
raise HTTPException(status_code=503, detail="Portal stream is unavailable") from exc
if upstream.status_code == 409:
# Pixel Edge uses 409 while its managed runtime is transitioning.
# Preserve the actionable retry class without reflecting any
# upstream response body into the owner-facing dashboard.
raise HTTPException(status_code=409, detail=_MODEL_SWITCH_DETAIL)
if upstream.status_code != 200:
raise HTTPException(status_code=502, detail="Portal request was rejected")
if not upstream.headers.get("content-type", "").lower().startswith("text/event-stream"):
raise HTTPException(status_code=502, detail="Portal returned an invalid stream")
except BaseException:
await release_stream()
raise
async def stream() -> AsyncIterator[bytes]:
nonlocal done_seen
try:
async with async_timeout(_CHAT_STREAM_TIMEOUT_SECONDS):
buffered = bytearray()
async for chunk in _iter_upstream_chunks(upstream, request, lambda: not buffered):
buffered.extend(chunk)
while True:
newline = buffered.find(b"\n")
if newline < 0:
break
line = bytes(buffered[: newline + 1])
del buffered[: newline + 1]
if len(line.rstrip(b"\r\n")) > _MAX_SSE_LINE_BYTES:
yield _error_event("Portal stream exceeded its safety limit")
if not done_seen:
yield b"data: [DONE]\n\n"
return
yield line
if line.rstrip(b"\r\n") == b"data: [DONE]":
done_seen = True
if len(buffered) > _MAX_SSE_LINE_BYTES:
yield _error_event("Portal stream exceeded its safety limit")
if not done_seen:
yield b"data: [DONE]\n\n"
return
if buffered:
# The final upstream line may lack a newline. Forward it
# terminated so it cannot fuse with the appended [DONE],
# and recognize a bare trailing marker as a real [DONE].
if buffered.rstrip(b"\r\n") == b"data: [DONE]":
done_seen = True
yield bytes(buffered) + b"\n"
except _ClientDisconnected:
return
except (GeneratorExit, asyncio.CancelledError):
raise
except (httpx.HTTPError, asyncio.TimeoutError):
yield _error_event("Portal stream is unavailable")
except Exception:
yield _error_event("Portal stream failed")
finally:
await release_stream()
if not done_seen:
yield b"data: [DONE]\n\n"
class OwnedStreamResponse(StreamingResponse):
async def __call__(self, scope, receive, send):
try:
await super().__call__(scope, receive, send)
finally:
# Sending headers can fail before the iterator ever starts.
await release_stream()
return OwnedStreamResponse(
stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache, no-store",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)