aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / science / allen_science.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Loopback-only stateless compute service. No HTTP client, credentials or project store.""" |
| 3 | import argparse |
| 4 | import json |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import re |
| 8 | import secrets |
| 9 | import socket |
| 10 | import socketserver |
| 11 | import threading |
| 12 | from http.server import BaseHTTPRequestHandler, HTTPServer |
| 13 | |
| 14 | # Isolated interpreter (-I) intentionally excludes cwd; only the root-owned install dir is imported. |
| 15 | import sys |
| 16 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 17 | from science_protocol import MAX_BYTES, TOOLS, event, packed, validate |
| 18 | from science_protocol import content as validate_content |
| 19 | from science_sandbox import AIEN_MATH_PIN, run_math, run_omega, selftest |
| 20 | ENGINE = 'aien-math' |
| 21 | SOURCE = '' # Source publication and distribution license await the copyright holder. |
| 22 | MANIFEST = Path(__file__).with_name('engine.json') |
| 23 | |
| 24 | |
| 25 | def load_manifest(): |
| 26 | manifest = json.loads(MANIFEST.read_text()) |
| 27 | if type(manifest) is not dict or not re.fullmatch(r'[0-9a-f]{40}', manifest.get('commit','')): |
| 28 | raise ValueError('Missing engine source identity') |
| 29 | if manifest.get('binary_sha256') != AIEN_MATH_PIN: |
| 30 | raise ValueError('Engine provenance does not match enforced binary pin') |
| 31 | return manifest |
| 32 | |
| 33 | |
| 34 | def evidence(status, expression='', result=''): |
| 35 | # No default guessed source pin or corpus score. |
| 36 | manifest = load_manifest() |
| 37 | label = 'math engine: Drake’s own, source not yet published' |
| 38 | corpus, alpha, guard = manifest.get('corpus'), manifest.get('alpha'), manifest.get('guard') |
| 39 | if corpus and alpha and guard: |
| 40 | label += (f". aien-math {manifest['commit']}: full corpus {corpus['pass']}/{corpus['total']} pass, " |
| 41 | f"{corpus['intentional_differences']} intentional differences, {corpus['failures']} failures, exit {corpus['exit']}; " |
| 42 | f"Alpha {alpha['pass']}/{alpha['total']}, exit {alpha['exit']}; " |
| 43 | f"guard tests {guard['tests']} {guard['result']}, exit {guard['exit']}. Experimental, not independent verification.") |
| 44 | return {'status': status, 'engine': label if expression else '', 'expression': expression, |
| 45 | 'result': result, 'source': SOURCE if expression else '', 'commit': manifest['commit'] if expression else ''} |
| 46 | |
| 47 | |
| 48 | def perform(name, arguments): |
| 49 | args = validate(name, arguments) |
| 50 | pane_id = 'p_' + secrets.token_hex(12) |
| 51 | kind = {'math_compute':'math','omega_compile':'omega','web_app':'app','paper':'doc','research':'research','plot':'plot'}[name] |
| 52 | provenance = {'status':'unverified','engine':'','expression':'','result':'','source':'','commit':''} |
| 53 | result = 'Created a draft pane. Its claims are unverified; do not describe them as computed.' |
| 54 | if name == 'math_compute': |
| 55 | outcome = run_math(args['expression']) |
| 56 | raw = outcome.get('output', '') |
| 57 | # A zero exit can still be an unsupported symbolic call. Require a nonempty |
| 58 | answer = raw.strip() |
| 59 | ok = outcome.get('ok') is True and bool(answer) |
| 60 | provenance = evidence('computed' if ok else 'unsupported', args['expression'], raw) |
| 61 | content = {'text': answer if ok else 'Not supported yet. aien-math did not produce a supported result for this expression.'} |
| 62 | result = ('aien-math exact output (not a proof of correctness): ' + answer) if ok else 'NOT SUPPORTED. Do not invent an answer or substitute model arithmetic.' |
| 63 | if len(result) > 8000: |
| 64 | result = 'The complete aien-math output is in the pane. It exceeds the model context limit; do not infer omitted values or claim to have read the full result.' |
| 65 | elif name == 'omega_compile': |
| 66 | outcome = run_omega(args['source']) |
| 67 | content = {'source':args['source'],'language':'omega'} |
| 68 | if outcome.get('ok') is True: |
| 69 | content.update({k:outcome[k] for k in ('wasm','functions') if k in outcome}) |
| 70 | result = 'Omega compiled to browser WASM. It has not been run. The visitor chooses whether to run it.' |
| 71 | provenance['result'] = packed({'omc_sha256':outcome['omc_sha256'], |
| 72 | 'irwasm_sha256':outcome['irwasm_sha256'], |
| 73 | 'stage':'compiled','executed':False}) |
| 74 | else: |
| 75 | result = 'Omega compilation refused: ' + str(outcome.get('error', outcome.get('message','unsupported source')))[:2000] |
| 76 | provenance['status'] = 'unsupported' |
| 77 | provenance['engine'] = 'seeded-omc' |
| 78 | provenance['expression'] = args['source'] |
| 79 | provenance['source'] = 'https://github.com/aien-dev/omega-mv' |
| 80 | elif name == 'web_app': |
| 81 | content = {'html':args['html']} |
| 82 | result = 'App draft created. It has not run; only a visitor click may run it in an allow-scripts-only iframe with no network.' |
| 83 | elif name == 'paper': content = {'markdown':args['markdown'],'citations':args['citations']} |
| 84 | elif name == 'research': |
| 85 | content = {key:args[key] for key in ('notes','hypotheses','derivations','sources')} |
| 86 | result = 'Research draft created from supplied notes. No live web search was performed; sources and model claims are unverified.' |
| 87 | else: |
| 88 | content = {key:args[key] for key in ('series','x_label','y_label')} |
| 89 | provenance['status'] = 'input-data' |
| 90 | provenance['expression'] = packed(args['series']) |
| 91 | result = 'Plot created from supplied data, not from a new calculation. Data provenance is input-data, not verified science.' |
| 92 | validate_content(kind, content) |
| 93 | events = [{'event':'pane.open','data':{'v':1,'id':pane_id,'kind':kind,'title':args['title']}}, |
| 94 | {'event':'pane.update','data':{'v':1,'id':pane_id,'revision':1,'content':content,'provenance':provenance}}] |
| 95 | for item in events: |
| 96 | event(item['event'], item['data']) |
| 97 | if len(packed(item['data']).encode()) > MAX_BYTES: |
| 98 | raise ValueError('Pane result exceeds output limit') |
| 99 | return {'events':events,'result':result} |
| 100 | |
| 101 | |
| 102 | class Handler(BaseHTTPRequestHandler): |
| 103 | server_version = 'AllenScience/1' |
| 104 | protocol_version = 'HTTP/1.0' |
| 105 | def log_message(self, *args): |
| 106 | pass # Never persist expressions, drafts, IPs or visitor information. |
| 107 | def setup(self): |
| 108 | super().setup() |
| 109 | self.connection.settimeout(20) |
| 110 | def reply(self, status, body): |
| 111 | data = packed(body).encode() |
| 112 | self.send_response(status) |
| 113 | self.send_header('Content-Type','application/json') |
| 114 | self.send_header('Content-Length',str(len(data))) |
| 115 | self.send_header('Cache-Control','no-store') |
| 116 | self.end_headers() |
| 117 | self.wfile.write(data) |
| 118 | def do_POST(self): |
| 119 | if self.path != '/compute' or self.client_address[0] != '127.0.0.1': |
| 120 | self.reply(404, {'error':'not_found'}); return |
| 121 | if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Type','').split(';')[0] != 'application/json': |
| 122 | self.reply(400, {'error':'invalid_framing'}); return |
| 123 | try: |
| 124 | lengths = self.headers.get_all('Content-Length', []) |
| 125 | if len(lengths) != 1: raise ValueError('Invalid content length') |
| 126 | size = int(lengths[0]) |
| 127 | if not 0 < size <= MAX_BYTES: raise ValueError('Body too large') |
| 128 | raw = self.rfile.read(size) |
| 129 | if len(raw) != size: raise ValueError('Truncated request') |
| 130 | from science_protocol import parse_call |
| 131 | name, args = parse_call(raw.decode('utf-8')) |
| 132 | if name not in self.server.tools: |
| 133 | self.reply(403, {'error':'tool_not_allowed'}); return |
| 134 | output = perform(name,args) |
| 135 | except (ValueError, UnicodeError, json.JSONDecodeError): |
| 136 | self.reply(422, {'error':'invalid_compute_request'}); return |
| 137 | except Exception: |
| 138 | self.reply(503, {'error':'compute_unavailable','message':'Not supported yet. Please try a smaller expression.'}); return |
| 139 | self.reply(200, output) |
| 140 | |
| 141 | |
| 142 | class Server(socketserver.ThreadingMixIn, HTTPServer): |
| 143 | daemon_threads = True |
| 144 | allow_reuse_address = True |
| 145 | slots = threading.BoundedSemaphore(2) |
| 146 | tools = frozenset(TOOLS) |
| 147 | def process_request(self, request, client_address): |
| 148 | if not self.slots.acquire(False): |
| 149 | request.sendall(b'HTTP/1.0 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n') |
| 150 | self.shutdown_request(request) |
| 151 | return |
| 152 | try: super().process_request(request,client_address) |
| 153 | except BaseException: |
| 154 | self.slots.release(); raise |
| 155 | def process_request_thread(self, request, client_address): |
| 156 | try: super().process_request_thread(request,client_address) |
| 157 | finally: self.slots.release() |
| 158 | |
| 159 | def allowed_tools(text): |
| 160 | """The --tools list: a non-empty, duplicate-free subset of TOOLS. A public gateway gets an |
| 161 | instance that serves only what it calls, so its reach is the tool, not the whole service.""" |
| 162 | names = text.split(',') |
| 163 | if not text or len(set(names)) != len(names) or not set(names) <= set(TOOLS): |
| 164 | raise argparse.ArgumentTypeError('--tools takes a comma list of ' + ','.join(TOOLS)) |
| 165 | return frozenset(names) |
| 166 | |
| 167 | if __name__ == '__main__': |
| 168 | parser = argparse.ArgumentParser() |
| 169 | parser.add_argument('--listen-fd', type=int) |
| 170 | parser.add_argument('--port', type=int, default=18113, choices=[18113, 18114]) |
| 171 | parser.add_argument('--tools', type=allowed_tools, default=frozenset(TOOLS)) |
| 172 | options = parser.parse_args() |
| 173 | load_manifest() |
| 174 | problems = selftest() |
| 175 | if problems: |
| 176 | raise SystemExit('Science sandbox self-test refused startup: ' + '; '.join(problems)) |
| 177 | if options.listen_fd is None: |
| 178 | raise SystemExit('Science service requires the isolated inherited-socket launcher') |
| 179 | server = Server(('127.0.0.1',options.port),Handler,bind_and_activate=False) |
| 180 | server.tools = options.tools |
| 181 | server.socket.close() |
| 182 | server.socket = socket.socket(fileno=options.listen_fd) |
| 183 | server.server_address = server.socket.getsockname() |
| 184 | if server.server_address != ('127.0.0.1',options.port): |
| 185 | raise SystemExit('Unexpected inherited listener') |
| 186 | server.serve_forever() |