"""Small offline transaction boundary for reviewed, candidate-specific tools. This is not a sandbox for hostile Python. The trusted controller runs this worker in a fresh interpreter for every call and keeps its state output private. """ from __future__ import annotations import argparse from contextlib import redirect_stderr, redirect_stdout from copy import deepcopy import importlib.util import json import math from pathlib import Path import re import sys from unittest.mock import patch from jsonschema import Draft202012Validator, FormatChecker, validators sys.dont_write_bytecode = True MAX_REQUEST_BYTES = 32768 MAX_INTERNAL_BYTES = 16 * 1024 * 1024 DEFAULT_OBSERVATION_BYTES = 32768 def require(condition, message): if not condition: raise ValueError(message) def canonical(value): # Reject Python-only coercions such as integer object keys or tuples. def check(item): if item is None or type(item) in (str, bool, int): return if type(item) is float: require(math.isfinite(item), 'Nonfinite JSON number') return if type(item) is list: for child in item: check(child) return if type(item) is dict: require(all(type(key) is str for key in item), 'JSON keys must be strings') for child in item.values(): check(child) return raise ValueError('Value is not JSON') check(value) return json.dumps(value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(',', ':')).encode('utf-8') def strict(raw): if type(raw) is bytes: raw = raw.decode('utf-8', errors='strict') require(type(raw) is str, 'Expected JSON bytes or text') def pairs(items): result = {} for key, value in items: require(key not in result, 'Duplicate JSON key') result[key] = value return result value = json.loads(raw, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON'))) canonical(value) return value def read(path): path = Path(path) require(path.is_file() and not path.is_symlink(), 'Expected a regular file') return strict(path.read_bytes()) _TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({ 'integer': lambda checker, value: type(value) is int, 'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)), }) StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER) # Load the pinned optional format checker by bundle-relative path. It requires # no network, installed extras, sys.path changes, or historical checkout. _date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py' _date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path) _date_module = importlib.util.module_from_spec(_date_spec) _date_spec.loader.exec_module(_date_module) def validator(schema): require(type(schema) in (dict, bool), 'Schema must be a JSON Schema') canonical(schema) formats = FormatChecker() @formats.checks('date-time') def date_time(value): return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper()) visited = set() def inspect(value): if type(value) is dict: if id(value) in visited: return visited.add(id(value)) require(value != {'truncated': True}, 'Truncated schemas are unsupported') require('$id' not in value and '$dynamicRef' not in value, 'Schema resource rebasing and dynamic references are unsupported') if 'format' in value: require(type(value['format']) is str and value['format'] in formats.checkers, 'Unsupported schema format') if '$ref' in value: ref = value['$ref'] require(type(ref) is str and (ref == '#' or ref.startswith('#/')), 'Only local JSON Pointer schema references are allowed') current = schema if ref != '#': for part in ref[2:].split('/'): part = part.replace('~1', '/').replace('~0', '~') if type(current) is list: require(part.isdigit(), 'Invalid local schema reference') current = current[int(part)] else: require(type(current) is dict and part in current, 'Missing local schema reference') current = current[part] require(type(current) in (dict, bool), 'Schema reference is not a schema') # A local reference may target a schema stored outside the # standard schema keywords; inspect that target as well. inspect(current) # Walk schema locations, not property names or literal const/enum # data (a business field named "format" is not a schema keyword). for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'): if keyword in value: require(type(value[keyword]) is dict, 'Invalid schema map') for child in value[keyword].values(): inspect(child) for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'): if keyword in value: require(type(value[keyword]) is list, 'Invalid schema sequence') for child in value[keyword]: inspect(child) for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames', 'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'): if keyword in value: inspect(value[keyword]) inspect(schema) Draft202012Validator.check_schema(schema) return StrictValidator(schema, format_checker=formats) class _BoundedSink: def __init__(self): self.size = 0 def write(self, value): self.size += len(value.encode('utf-8')) require(self.size <= 16384, 'Domain diagnostic output exceeded limit') return len(value) def flush(self): pass def load_domain(environment): environment = Path(environment) require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory') path = environment / 'domain_tools.py' require(path.is_file() and not path.is_symlink(), 'Invalid domain module') spec = importlib.util.spec_from_file_location('_curated_domain_tools', path) domain = importlib.util.module_from_spec(spec) # No sys.path injection and no reuse of an earlier module's global state. sys.modules[spec.name] = domain with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()): spec.loader.exec_module(domain) require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing') descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None)) require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list') names = set() for item in descriptors: require(type(item) is dict and set(item) <= { 'name', 'description', 'input_schema', 'output_schema', 'read_only' } and {'name', 'description', 'input_schema', 'read_only'} <= set(item), 'Invalid tool descriptor fields') name = item['name'] require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name) and name not in names, 'Invalid or duplicate tool name') names.add(name) require(type(item['description']) is str and bool(item['description'].strip()), 'Tool description is required') require(type(item['read_only']) is bool, 'read_only must be boolean') schema = item['input_schema'] require(type(schema) is dict and schema.get('type') == 'object' and schema.get('additionalProperties') is False, 'Tool input must explicitly prohibit extra arguments') validator(schema) if 'output_schema' in item: validator(item['output_schema']) return domain, descriptors def state_validator(environment): path = Path(environment) / 'state_schema.json' return validator(read(path)) if path.exists() else validator({'type': 'object'}) def error(code, message): return {'ok': False, 'error': {'code': code, 'message': message}} def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES): """Return private {state, observation, dispatched}; never mutate inputs.""" canonical(state) canonical(arguments) require(type(state) is dict, 'State must be an object') state_check = state_validator(environment) state_check.validate(state) domain, descriptors = load_domain(environment) by_name = {item['name']: item for item in descriptors} before, working = deepcopy(state), deepcopy(state) def result(observation, dispatched, next_state=None): return {'state': deepcopy(before if next_state is None else next_state), 'observation': deepcopy(observation), 'dispatched': dispatched} if type(name) is not str or name not in by_name: return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False) descriptor = by_name[name] try: require(type(arguments) is dict, 'Arguments must be an object') validator(descriptor['input_schema']).validate(arguments) except Exception: return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False) try: with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()): observation = domain.call_tool(working, name, deepcopy(arguments)) except Exception: return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True) try: require(type(observation) is dict and type(observation.get('ok')) is bool, 'Invalid domain envelope') if observation['ok']: require(set(observation) == {'ok', 'result'}, 'Invalid success envelope') else: require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict, 'Invalid error envelope') require(type(observation['error'].get('code')) is str and bool(observation['error']['code']) and type(observation['error'].get('message')) is str, 'Invalid domain error') encoded = canonical(observation) require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576, 'Invalid observation limit') if len(encoded) > max_observation_bytes: return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True) if descriptor['read_only'] and canonical(working) != canonical(before): return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True) if not observation['ok']: return result(observation, True) if 'output_schema' in descriptor: validator(descriptor['output_schema']).validate(observation['result']) state_check.validate(working) canonical(working) except Exception: return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True) return result(observation, True, working) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--environment', type=Path, required=True) parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES) args = parser.parse_args(argv) try: raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1) require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit') request = strict(raw) with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')), patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))): if request == {'action': 'describe'}: _, descriptors = load_domain(args.environment) state_validator(args.environment).validate(read(args.environment / 'state.json')) value = {'tools': descriptors} else: require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'} and request['action'] == 'transition', 'Invalid internal request') value = transition(args.environment, request['state'], request['tool'], request['arguments'], max_observation_bytes=args.max_observation_bytes) sys.stdout.buffer.write(canonical(value) + b'\n') return 0 except Exception: sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n') return 1 if __name__ == '__main__': raise SystemExit(main())