File size: 13,499 Bytes
ee61dae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | """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())
|