aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / science / science_protocol.py
| 1 | """Allen pane v1 / compute-call validation. Host JSON adapter; see DEPENDENCIES.""" |
| 2 | import json |
| 3 | import math |
| 4 | import re |
| 5 | from urllib.parse import urlsplit |
| 6 | |
| 7 | VERSION = 1 |
| 8 | MAX_BYTES = 65536 |
| 9 | MAX_TEXT = 32768 |
| 10 | KINDS = ('math', 'plot', 'doc', 'code', 'app', 'research', 'data', 'omega') |
| 11 | TOOLS = ('math_compute', 'omega_compile', 'web_app', 'paper', 'research', 'plot') |
| 12 | # Positive admission: no contexts, assignments, slots, patterns, shell escapes, |
| 13 | # comments or dynamically assembled symbols. Strings are unit names only. |
| 14 | MATH_HEADS = frozenset('Abs ArcCos ArcSin ArcTan Cos Sin Tan Cosh Sinh Tanh Exp Log Sqrt Power Rational Complex N D Integrate NIntegrate Limit Series Normal Sum Product Solve Reduce Simplify FullSimplify Expand Factor Together Apart Cancel Numerator Denominator Coefficient CoefficientList Collect Det Inverse Transpose Eigenvalues Eigenvectors MatrixRank RowReduce LinearSolve Dot IdentityMatrix DiagonalMatrix Tr EigenSystem Eigensystem DSolve DSolveValue NDSolve Mean Median Variance StandardDeviation Covariance Correlation PDF CDF Quantile NormalDistribution BinomialDistribution PoissonDistribution Gamma Beta Erf Erfc Factorial Binomial GCD LCM Mod Min Max Floor Ceiling Round Sign Re Im Conjugate Chop Length Total Range Table List Plus Times Equal Less Greater LessEqual GreaterEqual And Or Not True False Pi E I Infinity DirectedInfinity'.split()) |
| 15 | MATH_HEADS |= frozenset('Assumptions GenerateConditions ConditionalExpression SingularValueList MatrixExp First HermiteH C Quantity QuantityMagnitude QuantityUnit UnitConvert UnitSimplify Probability Expectation Zeta SeriesData'.split()) |
| 16 | UNITS = frozenset('Kilograms SpeedOfLight Joules GravitationalConstant SolarMass Kilometers Parsecs LightYears ReducedPlanckConstant Meters Seconds Kelvins Celsius Fahrenheit Radians Degrees Moles Amperes Candelas Newtons Pascals Watts Hertz MetersPerSecond SIBase'.split()) |
| 17 | VARIABLES = frozenset('x y z t a b c d f g h k m n p q r s u v w'.split()) |
| 18 | TOKEN = re.compile(r'\s+|"[A-Za-z]{1,64}"|\\\[Distributed\]|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z]+|[\[\]{}(),.+*/^<>=!\x27\-]') |
| 19 | WORD = re.compile(r'[A-Za-z]+') |
| 20 | |
| 21 | |
| 22 | def packed(value): |
| 23 | return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(',', ':')) |
| 24 | |
| 25 | |
| 26 | def obj(value, required, optional=()): |
| 27 | if type(value) is not dict or set(value) - set(required) - set(optional) or not set(required) <= set(value): |
| 28 | raise ValueError('Unexpected or missing fields') |
| 29 | return value |
| 30 | |
| 31 | |
| 32 | def text(value, limit=MAX_TEXT, empty=True): |
| 33 | if not isinstance(value, str) or len(value.encode('utf-8')) > limit or (not empty and not value.strip()) or '\x00' in value: |
| 34 | raise ValueError('Invalid text or text too long') |
| 35 | return value |
| 36 | |
| 37 | |
| 38 | def strings(value): |
| 39 | if type(value) is not list or len(value) > 64: |
| 40 | raise ValueError('Invalid list') |
| 41 | return [text(v) for v in value] |
| 42 | |
| 43 | |
| 44 | def citations(value): |
| 45 | if type(value) is not list or len(value) > 64: |
| 46 | raise ValueError('Invalid citations') |
| 47 | for row in value: |
| 48 | obj(row, ('title', 'url')) |
| 49 | text(row['title'], 200, False) |
| 50 | url = text(row['url'], 2048) |
| 51 | parsed = urlsplit(url) |
| 52 | if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or any(ord(c) < 33 for c in url): |
| 53 | raise ValueError('Citation must be a plain HTTPS URL; never fetched by tools') |
| 54 | return value |
| 55 | |
| 56 | |
| 57 | def expression(value): |
| 58 | value = text(value, 4096, False) |
| 59 | at = 0 |
| 60 | nesting = [] |
| 61 | for match in TOKEN.finditer(value): |
| 62 | if match.start() != at: |
| 63 | raise ValueError('Expression contains disallowed syntax') |
| 64 | token = match.group() |
| 65 | at = match.end() |
| 66 | if token.startswith('"') and token[1:-1] not in UNITS: |
| 67 | raise ValueError('Only approved unit strings are accepted') |
| 68 | if token == ',' and not nesting: |
| 69 | raise ValueError('Exactly one expression is required') |
| 70 | if token[0].isalpha() and token not in MATH_HEADS and token not in VARIABLES: |
| 71 | raise ValueError('Unsupported mathematical symbol: ' + token) |
| 72 | if token in ('[', '{', '('): |
| 73 | nesting.append(token) |
| 74 | if len(nesting) > 32: |
| 75 | raise ValueError('Expression nesting limit') |
| 76 | elif token in (']', '}', ')'): |
| 77 | if not nesting or nesting.pop() != {']':'[', '}':'{', ')':'('}[token]: |
| 78 | raise ValueError('Unbalanced expression') |
| 79 | if at != len(value) or nesting or any(s in value for s in ('==>', '!=', '<>', '!!', '//', '/*', '*/', '(*', '*)')): |
| 80 | raise ValueError('Expression contains disallowed syntax') |
| 81 | if re.search(r'(?<![=<>])=(?!=)', value): |
| 82 | raise ValueError('Assignments are not mathematical requests') |
| 83 | if '++' in value or '--' in value: |
| 84 | raise ValueError('Mutation operators are not mathematical requests') |
| 85 | # Dependent variables may occur as heads in differential equations. |
| 86 | # Maximal letter runs plus a forward whitespace scan avoid regex backtracking. |
| 87 | for word in WORD.finditer(value): |
| 88 | after = word.end() |
| 89 | while after < len(value) and value[after].isspace(): |
| 90 | after += 1 |
| 91 | head = word.group() |
| 92 | if after < len(value) and value[after] == '[' and head not in MATH_HEADS and head not in VARIABLES and head != 'Distributed': |
| 93 | raise ValueError('Unapproved function head') |
| 94 | return value |
| 95 | |
| 96 | |
| 97 | def validate(name, args): |
| 98 | if name not in TOOLS: |
| 99 | raise ValueError('Unknown compute tool') |
| 100 | if len(packed(args).encode('utf-8')) > MAX_BYTES: |
| 101 | raise ValueError('Tool arguments too large') |
| 102 | fields = {'math_compute':('title','expression'), 'omega_compile':('title','source'), |
| 103 | 'web_app':('title','html'), 'paper':('title','markdown','citations'), |
| 104 | 'research':('title','notes','hypotheses','derivations','sources'), |
| 105 | 'plot':('title','series','x_label','y_label')}[name] |
| 106 | obj(args, fields) |
| 107 | text(args['title'], 200, False) |
| 108 | if name == 'math_compute': expression(args['expression']) |
| 109 | elif name == 'omega_compile': text(args['source'], 16384, False) |
| 110 | elif name == 'web_app': text(args['html'], MAX_TEXT, False) |
| 111 | elif name == 'paper': |
| 112 | text(args['markdown']); citations(args['citations']) |
| 113 | elif name == 'research': |
| 114 | text(args['notes']); strings(args['hypotheses']); strings(args['derivations']); citations(args['sources']) |
| 115 | else: |
| 116 | text(args['x_label'], 200); text(args['y_label'], 200) |
| 117 | if type(args['series']) is not list or not 1 <= len(args['series']) <= 8: |
| 118 | raise ValueError('Invalid series') |
| 119 | for series in args['series']: |
| 120 | obj(series, ('label', 'points')); text(series['label'], 200) |
| 121 | if type(series['points']) is not list or not 1 <= len(series['points']) <= 512: |
| 122 | raise ValueError('Invalid points') |
| 123 | for point in series['points']: |
| 124 | if type(point) is not list or len(point) != 2 or any(type(n) not in (int,float) or not math.isfinite(n) or abs(n) > 1e100 for n in point): |
| 125 | raise ValueError('Invalid point') |
| 126 | return json.loads(packed(args)) |
| 127 | |
| 128 | |
| 129 | def parse_call(value): |
| 130 | """The only accepted constrained fallback frame; surrounding prose is not executable.""" |
| 131 | if not isinstance(value, str) or len(value.encode('utf-8')) > MAX_BYTES: |
| 132 | raise ValueError('Invalid tool frame') |
| 133 | def unique(pairs): |
| 134 | result = {} |
| 135 | for key, val in pairs: |
| 136 | if key in result: raise ValueError('Duplicate JSON key') |
| 137 | result[key] = val |
| 138 | return result |
| 139 | frame = json.loads(value, object_pairs_hook=unique, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON'))) |
| 140 | obj(frame, ('tool', 'arguments')) |
| 141 | return frame['tool'], validate(frame['tool'], frame['arguments']) |
| 142 | |
| 143 | |
| 144 | def event(name, data): |
| 145 | if name not in ('pane.open', 'pane.update', 'pane.close'): raise ValueError('Unknown pane event') |
| 146 | fields = {'pane.open':('v','id','kind','title'), 'pane.update':('v','id','revision','content','provenance'), 'pane.close':('v','id')}[name] |
| 147 | obj(data, fields) |
| 148 | if type(data['v']) is not int or data['v'] != VERSION or not isinstance(data['id'], str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', data['id']): |
| 149 | raise ValueError('Invalid pane identity') |
| 150 | if name == 'pane.open': |
| 151 | if data['kind'] not in KINDS: raise ValueError('Invalid pane kind') |
| 152 | text(data['title'], 200) |
| 153 | if name == 'pane.update': |
| 154 | if type(data['revision']) is not int or not 1 <= data['revision'] <= 1000000: raise ValueError('Invalid revision') |
| 155 | if type(data['content']) is not dict or len(packed(data['content']).encode()) > MAX_BYTES: raise ValueError('Invalid content') |
| 156 | p = obj(data['provenance'], ('status','engine','expression','result','source','commit')) |
| 157 | if p['status'] not in ('computed','unsupported','unverified','input-data'): raise ValueError('Invalid evidence status') |
| 158 | for key in ('engine','expression','result','source','commit'): text(p[key]) |
| 159 | return data |
| 160 | |
| 161 | |
| 162 | def content(kind, value): |
| 163 | """Validate the kind-specific replacement before any SSE event is emitted.""" |
| 164 | if kind == 'math': |
| 165 | obj(value, ('text',), ('tex',)) |
| 166 | for item in value.values(): text(item) |
| 167 | elif kind in ('doc', 'research', 'plot', 'app'): |
| 168 | tool = {'doc':'paper','research':'research','plot':'plot','app':'web_app'}[kind] |
| 169 | validate(tool, {'title':'Pane', **value}) |
| 170 | if 'title' in value: raise ValueError('Unexpected content title') |
| 171 | elif kind in ('code', 'omega'): |
| 172 | obj(value, ('source','language'), ('wasm','functions')) |
| 173 | text(value['source'], 16384); text(value['language'], 64) |
| 174 | if 'wasm' in value: |
| 175 | import base64 |
| 176 | base64.b64decode(text(value['wasm']), validate=True) |
| 177 | if 'functions' in value: |
| 178 | if type(value['functions']) is not list or len(value['functions']) > 64: raise ValueError('Invalid function list') |
| 179 | for function in value['functions']: |
| 180 | obj(function, ('name','params','ret')) |
| 181 | text(function['name'],64); text(function['ret'],64) |
| 182 | if type(function['params']) is not list or len(function['params']) > 6: raise ValueError('Invalid parameters') |
| 183 | for parameter in function['params']: |
| 184 | obj(parameter, ('name','type')) |
| 185 | text(parameter['name'],64); text(parameter['type'],64) |
| 186 | elif kind == 'data': |
| 187 | obj(value, ('columns','rows')) |
| 188 | strings(value['columns']) |
| 189 | if type(value['rows']) is not list or len(value['rows']) > 64: raise ValueError('Invalid rows') |
| 190 | for row in value['rows']: |
| 191 | strings(row) |
| 192 | if len(row) != len(value['columns']): raise ValueError('Invalid row width') |
| 193 | else: |
| 194 | raise ValueError('Unknown content kind') |
| 195 | if len(packed(value).encode()) > MAX_BYTES: raise ValueError('Content too large') |
| 196 | return value |