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.

19.8 KB
Raw Blame
"""Fixed owner-worker pipe frames, not public settings or privilege authority."""
import json
import math
from pathlib import PurePosixPath
import re
import uuid
from pixel_model_contract import target as model_target, ModelError

MAX_REQUEST = 16384
MAX_REPLY = 8192
BASE = {"operation", "openclaw", "config_sha256", "confirmed"}
KEYS = {"status": BASE, "full-access": BASE, "sandboxed": BASE, "settings-status": BASE,
        "settings-apply": BASE | {"transaction_id", "settings_revision", "preferences", "capabilities"},
        "settings-recover": BASE | {"transaction_id"}, "provider-status": BASE,
        "provider-worker-status": BASE | {"provider_probe"},
        "provider-change": BASE | {"transaction_id", "binding"},
        "provider-recover": BASE | {"transaction_id"}}
HOOKS = {"status": (), "full-access": ("busy", "restart"), "sandboxed": ("busy", "restart"),
         "settings-status": (), "settings-apply": ("busy", "settings-activate"),
         "settings-recover": ("busy", "settings-activate"), "provider-status": (), "provider-worker-status": (),
         "provider-change": ("busy", "provider-activate"), "provider-recover": ("busy", "provider-activate")}
HEX = re.compile(r"[a-f0-9]{64}\Z")
KEYS.update({"model-status": BASE, "model-begin": BASE | {"transaction_id"},
             "model-apply": BASE | {"transaction_id", "model_target"},
             "model-rollback": BASE | {"transaction_id"}, "model-finish": BASE | {"transaction_id", "model_outcome"}})
HOOKS.update({name: (() if name == "model-status" else ("busy",)) for name in KEYS if name.startswith("model-")})
KEYS['access-relocate'] = BASE | {'relocation'}
HOOKS['access-relocate'] = ('busy',)
KEYS.update({
    'release-baseline': BASE | {'transaction_id'},
    'release-abort': BASE | {'transaction_id', 'receipt_sha256'},
    'release-prepare': BASE | {'transaction_id', 'candidate_path', 'candidate_sha256', 'receipt_sha256'},
    'release-recover': BASE | {'transaction_id', 'release_outcome'},
    'release-finish': BASE | {'transaction_id', 'release_outcome'},
})
HOOKS.update({'release-prepare': ('busy',), 'release-recover': ('busy',),
              'release-finish': ('busy', 'release-verify'), 'release-baseline': ('busy',),
              'release-abort': ('busy', 'release-verify')})


class ProtocolError(ValueError):
    pass


def _pairs(items):
    result = {}
    for key, value in items:
        if key in result:
            raise ProtocolError("owner-protocol-failed")
        result[key] = value
    return result


def _finite(value):
    if not math.isfinite(float(value)):
        raise ProtocolError("owner-protocol-failed")
    return float(value)


def decode_frame(raw, maximum):
    try:
        if type(raw) is not str or not raw.endswith("\n") or len(raw.encode("utf-8")) > maximum:
            raise ProtocolError("owner-protocol-failed")
        return json.loads(raw, object_pairs_hook=_pairs, parse_constant=_finite, parse_float=_finite)
    except (ValueError, UnicodeError, RecursionError, OverflowError):
        raise ProtocolError("owner-protocol-failed") from None


def read_frame(stream, maximum):
    return decode_frame(stream.readline(maximum + 1), maximum)


def control_request(value):
    """Fixed local socket operations; installer candidates are validated paths.

    Candidate paths identify input only, never caller-supplied authority.
    The root adapter separately binds them to the held installer transaction.
    """
    if type(value) is not dict or type(value.get("operation")) is not str:
        raise ProtocolError("invalid-request")
    operation = value["operation"]
    keys = {"status": {"operation"}, "model-status": {"operation"},
            "change": {"operation", "request"},
            "model-begin": {"operation"}, "model-finish": {"operation", "request"},
            "installer-model-verify": {"operation", "request"},
            "installer-source-begin": {"operation", "request"},
            "installer-release-prepare": {"operation", "request"},
            "installer-release-publish": {"operation", "request"},
            "installer-release-finish": {"operation", "request"},
            "installer-release-abort": {"operation", "request"},
            # Browser model switching and installer promotion are distinct
            # transactions even though their public operation names overlap.
            "model-route-status": {"operation"},
            "model-route-begin": {"operation", "request"},
            "model-route-apply": {"operation", "request"},
            "model-route-finish": {"operation", "request"},
            "settings-status": {"operation", "data_dir_id"},
            "settings-change": {"operation", "data_dir_id", "request"},
            "provider-status": {"operation", "data_dir_id"},
            "provider-change": {"operation", "data_dir_id", "request"}}
    if operation not in keys or set(value) != keys[operation]:
        raise ProtocolError("invalid-request")
    if operation.startswith(("settings-", "provider-")) and (type(value["data_dir_id"]) is not str or not HEX.fullmatch(value["data_dir_id"])):
        raise ProtocolError("invalid-request")
    if "request" in value and type(value["request"]) is not dict:
        raise ProtocolError("invalid-request")
    if operation == 'installer-source-begin' and value['request'] != {}:
        raise ProtocolError('invalid-request')
    if operation.startswith('installer-release-'):
        payload = value['request']
        action = operation.removeprefix('installer-release-')
        expected = {'transaction_id'} | ({'candidate_path', 'candidate_sha256'} if action == 'prepare'
                   else {'outcome', 'config_sha256'} if action == 'finish'
                   else set() if action == 'abort' else {'outcome'})
        if (set(payload) != expected or type(payload.get('transaction_id')) is not str
                or not HEX.fullmatch(payload['transaction_id'])):
            raise ProtocolError('invalid-request')
        if action == 'prepare':
            try:
                request(dict(operation='release-prepare', openclaw='/validated-later',
                    confirmed=False, config_sha256='0' * 64, receipt_sha256='0' * 64, **payload))
            except ProtocolError:
                raise ProtocolError('invalid-request') from None
        elif action != 'abort' and payload['outcome'] not in ('apply', 'rollback'):
            raise ProtocolError('invalid-request')
        if action == 'finish' and (type(payload['config_sha256']) is not str
                                   or not HEX.fullmatch(payload['config_sha256'])):
            raise ProtocolError('invalid-request')
    if operation == "installer-model-verify":
        request_value = value["request"]
        if (set(request_value) != {"transaction_id"}
                or type(request_value["transaction_id"]) is not str
                or not HEX.fullmatch(request_value["transaction_id"])):
            raise ProtocolError("invalid-request")
    if operation == "model-finish":
        request_value = value["request"]
        if (set(request_value) != {"transaction_id", "outcome"}
                or type(request_value["transaction_id"]) is not str
                or not HEX.fullmatch(request_value["transaction_id"])
                or request_value["outcome"] not in ("applied", "rolled-back")):
            raise ProtocolError("invalid-request")
    if operation.startswith("model-route-") and operation != "model-route-status":
        request_value = value["request"]
        expected = {
            "model-route-begin": {"transactionId", "revision"},
            "model-route-apply": {"transactionId", "target"},
            "model-route-finish": {"transactionId", "outcome"},
        }[operation]
        if (set(request_value) != expected
                or type(request_value.get("transactionId")) is not str
                or not HEX.fullmatch(request_value["transactionId"])):
            raise ProtocolError("invalid-request")
        if (operation == "model-route-begin"
                and (type(request_value["revision"]) is not str
                     or not HEX.fullmatch(request_value["revision"]))):
            raise ProtocolError("invalid-request")
        if operation == "model-route-apply" and type(request_value["target"]) is not dict:
            raise ProtocolError("invalid-request")
        if operation == "model-route-finish" and request_value["outcome"] not in ("commit", "rollback"):
            raise ProtocolError("invalid-request")
    return value


def request(value):
    if type(value) is not dict or type(value.get("operation")) is not str:
        raise ProtocolError("owner-protocol-failed")
    operation = value["operation"]
    allowed = KEYS.get(operation)
    if allowed is None or set(value) not in (allowed, allowed | {'expected_projection'} if operation == 'provider-change' else allowed):
        raise ProtocolError("owner-protocol-failed")
    if (type(value["openclaw"]) is not str or not PurePosixPath(value["openclaw"]).is_absolute()
            or "\x00" in value["openclaw"] or type(value["confirmed"]) is not bool):
        raise ProtocolError("owner-protocol-failed")
    if operation.endswith("status"):
        if value["config_sha256"] is not None:
            raise ProtocolError("owner-protocol-failed")
    elif type(value["config_sha256"]) is not str or not HEX.fullmatch(value["config_sha256"]):
        raise ProtocolError("owner-protocol-failed")
    if operation.startswith('release-'):
        if (value['confirmed'] is not False or type(value['transaction_id']) is not str
                or not HEX.fullmatch(value['transaction_id'])):
            raise ProtocolError('owner-protocol-failed')
        if operation in ('release-prepare', 'release-abort') and (
                type(value['receipt_sha256']) is not str or not HEX.fullmatch(value['receipt_sha256'])):
            raise ProtocolError('owner-protocol-failed')
        if operation == 'release-prepare':
            candidate = value['candidate_path']
            if (type(candidate) is not str or not candidate.startswith('/')
                    or any(c in candidate for c in '\x00\n\r\t')
                    or any(p in ('', '.', '..') for p in candidate.split('/')[1:])
                    or type(value['candidate_sha256']) is not str
                    or not HEX.fullmatch(value['candidate_sha256'])):
                raise ProtocolError('owner-protocol-failed')
        elif operation in ('release-recover', 'release-finish') and value['release_outcome'] not in ('apply', 'rollback'):
            raise ProtocolError('owner-protocol-failed')
    if operation == 'access-relocate':
        relocation = value['relocation']
        if (type(relocation) is not dict or set(relocation) != {'source_config', 'source_sha256'}
                or type(relocation['source_config']) is not str
                or not relocation['source_config'].startswith('/')
                or any(c in relocation['source_config'] for c in '\x00\n\r\t')
                or any(p in ('', '.', '..') for p in relocation['source_config'].split('/')[1:])
                or type(relocation['source_sha256']) is not str
                or not HEX.fullmatch(relocation['source_sha256'])
                or value['confirmed'] is not False):
            raise ProtocolError('owner-protocol-failed')
    if operation == 'provider-worker-status':
        probe = value['provider_probe']
        if (type(probe) is not dict or set(probe) != {'python', 'launcher', 'providerDirectory', 'receipt'}
                or type(probe['receipt']) is not dict
                or any(type(probe[key]) is not str or '\x00' in probe[key]
                       or not PurePosixPath(probe[key]).is_absolute()
                       for key in ('python', 'launcher', 'providerDirectory'))
                or PurePosixPath(probe['launcher']).name != 'ods-pixel-route-lease'):
            raise ProtocolError('owner-protocol-failed')
    if operation in ("settings-apply", "settings-recover", "provider-change", "provider-recover"):
        if type(value["transaction_id"]) is not str or not HEX.fullmatch(value["transaction_id"]):
            raise ProtocolError("owner-protocol-failed")
    if operation.startswith("model-") and operation != "model-status":
        if type(value["transaction_id"]) is not str or not HEX.fullmatch(value["transaction_id"]):
            raise ProtocolError("owner-protocol-failed")
        if operation == "model-apply":
            try: model_target(value["model_target"])
            except ModelError: raise ProtocolError("owner-protocol-failed") from None
        if operation == "model-finish" and value["model_outcome"] not in ("commit", "rollback"):
            raise ProtocolError("owner-protocol-failed")
    if operation == "settings-apply" and (
            type(value["settings_revision"]) is not int or not 0 <= value["settings_revision"] <= 2**53 - 1
            or type(value["preferences"]) is not dict or type(value["capabilities"]) is not dict):
        raise ProtocolError("owner-protocol-failed")
    if operation == "provider-change":
        provider_binding(value["binding"])
        if 'expected_projection' in value:
            projection = value['expected_projection']
            if (type(projection) is not dict or set(projection) != {'afterSha', 'previousPlanSha'}
                    or type(projection['afterSha']) is not str or not HEX.fullmatch(projection['afterSha'])
                    or projection['previousPlanSha'] is not None and
                    (type(projection['previousPlanSha']) is not str or not HEX.fullmatch(projection['previousPlanSha']))):
                raise ProtocolError('owner-protocol-failed')
    return value


def provider_binding(value):
    if value is None:
        return
    if (type(value) is not dict or set(value) != {"schemaVersion", "activationId", "revision", "allowCloud"}
            or type(value["schemaVersion"]) is not int or value["schemaVersion"] != 1
            or type(value["revision"]) is not int or not 0 <= value["revision"] < 2**53
            or type(value["allowCloud"]) is not bool or type(value["activationId"]) is not str):
        raise ProtocolError("owner-protocol-failed")
    try:
        if str(uuid.UUID(value["activationId"])) != value["activationId"]:
            raise ValueError()
    except ValueError:
        raise ProtocolError("owner-protocol-failed") from None


def hook_reply(operation, name, value):
    if name not in HOOKS.get(operation, ()):
        raise ProtocolError("owner-protocol-failed")
    if name in ("settings-activate", "provider-activate", "release-verify"):
        valid = type(value) is str and value in ("verified", "rejected", "unavailable")
    else:
        valid = type(value) is bool
    if not valid:
        raise ProtocolError("host-hook-failed")
    return value


def result(operation, value):
    if type(value) is not dict:
        raise ProtocolError("owner-protocol-failed")
    if operation.startswith('release-'):
        keys = ({'beforeSha', 'afterSha'} if operation == 'release-prepare'
                else {'configSha256', 'receiptSha256'} if operation == 'release-baseline' else {'configSha256'})
        if set(value) != keys or any(type(value[k]) is not str or not HEX.fullmatch(value[k]) for k in keys):
            raise ProtocolError('owner-protocol-failed')
        return value
    if operation == 'access-relocate':
        if set(value) != {'relocated'} or type(value['relocated']) is not bool:
            raise ProtocolError('owner-protocol-failed')
        return value
    if operation.startswith("model-"):
        if type(value.get("configSha256")) is not str or not HEX.fullmatch(value["configSha256"]):
            raise ProtocolError("owner-protocol-failed")
        if operation != "model-status":
            if set(value) != {"configSha256"}: raise ProtocolError("owner-protocol-failed")
        else:
            if (set(value) != {"configSha256", "contract", "limits", "pending", "transactionId", "completion"}
                    or type(value["pending"]) is not bool or type(value["limits"]) is not dict
                    or value["transactionId"] is not None and (type(value["transactionId"]) is not str or not HEX.fullmatch(value["transactionId"]))):
                raise ProtocolError("owner-protocol-failed")
            try: model_target(value["contract"])
            except ModelError: raise ProtocolError("owner-protocol-failed") from None
            done = value["completion"]
            if done is not None and (type(done) is not dict or set(done) != {"transactionId", "outcome", "configSha256"}
                    or done["outcome"] not in ("commit", "rollback")
                    or any(type(done[key]) is not str or not HEX.fullmatch(done[key]) for key in ("transactionId", "configSha256"))):
                raise ProtocolError("owner-protocol-failed")
        return value
    if operation == 'provider-worker-status':
        if set(value) != {'ready'} or type(value['ready']) is not bool:
            raise ProtocolError('owner-protocol-failed')
        return value
    if operation.startswith("provider-"):
        return provider_result(operation, value)
    if not operation.startswith("settings-"):
        return value  # Existing access status contract is interpreted by inspect.
    def revision(item):
        return type(item) is int and 0 <= item <= 2**53 - 1
    def checksum(item):
        return type(item) is str and HEX.fullmatch(item) is not None
    valid = checksum(value.get("configSha256"))
    if operation == "settings-status":
        valid = valid and set(value) == {"configSha256", "managedRevision", "pending", "completion", "runtimeVerified"}
        if not valid:
            raise ProtocolError("owner-protocol-failed")
        valid = (value["runtimeVerified"] is False and type(value["pending"]) is bool
                 and (value["managedRevision"] is None or revision(value["managedRevision"])))
        completed = value["completion"]
        if completed is not None:
            valid = (valid and not value["pending"] and type(completed) is dict
                     and set(completed) == {"transactionId", "settingsRevision", "outcome", "configSha256"}
                     and checksum(completed["transactionId"]) and checksum(completed["configSha256"])
                     and revision(completed["settingsRevision"]) and completed["outcome"] in ("applied", "rolled-back"))
    elif value.get("status") == "rolled-back":
        valid = valid and set(value) == {"status", "configSha256"}
    else:
        valid = (valid and operation == "settings-apply" and value.get("status") == "runtime-verified"
                 and set(value) == {"status", "settingsRevision", "configSha256"} and revision(value["settingsRevision"]))
    if not valid:
        raise ProtocolError("owner-protocol-failed")
    return value


def provider_result(operation, value):
    def checksum(item):
        return type(item) is str and HEX.fullmatch(item) is not None
    provider_binding(value.get("binding"))
    valid = checksum(value.get("configSha256"))
    if operation == "provider-status":
        valid = (valid and set(value) == {"configSha256", "binding", "pending", "completion", "runtimeVerified"}
                 and type(value["pending"]) is bool and value["runtimeVerified"] is False)
        completed = value.get("completion")
        if completed is not None:
            valid = (valid and not value["pending"] and type(completed) is dict
                     and set(completed) == {"transactionId", "binding", "outcome", "configSha256"}
                     and checksum(completed["transactionId"]) and checksum(completed["configSha256"])
                     and completed["outcome"] in ("applied", "rolled-back"))
            if valid:
                provider_binding(completed["binding"])
    else:
        valid = (valid and set(value) == {"status", "binding", "configSha256"}
                 and (value.get("status") == "rolled-back" or
                      operation == "provider-change" and value.get("status") == "registration-verified"))
    if not valid:
        raise ProtocolError("owner-protocol-failed")
    return value