suayptalha's picture
Initial release
e70aa91
Raw History Blame Contribute Delete
7 kB
"""Typed public contracts. No benchmark IDs, answers or evaluator access."""
import json
import math
def field(kind,description=''):
return dict(type=kind,**({'description':description} if description else {}))
CONTRACTS={
'schema':({'schema':field('object'),'value':field('object')},['schema','value']),
'workflow':({'nodes':field('integer'),'dependencies':field('array','Pairs [prerequisite,task].'),
'completed':field('array')},['nodes','dependencies','completed']),
'index':({'documents':field('array','Records with id,key,version,text; optional for RAM files.'),
'query':field('string')},['query']),
'syntax_scope':({'text':field('string','Source text for lexical delimiter checking.'),
'events':field('array','Explicit scope IR: [opcode,symbol_id]. 0 enter,1 leave,2 declare,3 use.')},[]),
'polynomial':({'operation':field('string'),'left':field('array'),'right':field('array')},['operation','left']),
'constraints':({'text':field('string'),'words':field('integer'),'paragraphs':field('integer'),
'forbidden':field('string')},['text']),
'units':({'operation':field('string'),'left':field('string'),'right':field('string')},['left','right']),
'sat':({'variables':field('integer'),'clauses':field('array')},['variables','clauses']),
'closure':({'nodes':field('integer'),'edges':field('array'),'query':field('array')},['nodes']),
'binary':({'operation':field('string'),'left':field('array','Unsigned 32-bit left operands. For a scalar pair use left:[A], right:[B].'),'right':field('array','Required for xor/and/or; same length as left. Never put both operands in left.'),
'bytes':field('array','Byte values 0..255 for base64_encode/hex_encode.'),
'text':field('string','For base64_decode.'),'rotation':field('integer','0..31 for rol/ror.')},['operation']),
}
def parameters(feature):
properties,required=CONTRACTS[feature]
return dict(type='object',properties=properties,required=required,additionalProperties=False)
def normalize(feature,args):
"""XML values arrive as strings; convert only fields declared non-string."""
props,_=CONTRACTS[feature]
# One explicit backward-compatible spelling; never reinterpret arbitrary fields.
if feature=='binary' and args.get('operation') in ('base64_encode','hex_encode') and 'input' in args and 'bytes' not in args:
args={**args};args['bytes']=args.pop('input')
result={}
for key,value in args.items():
if key in props and props[key]['type']!='string' and isinstance(value,str):
value=strict_json(value)
result[key]=value
return result
def implicit_call(value):
"""Recover an unambiguous unfinished tool envelope, never a normal answer."""
if not isinstance(value,dict) or set(value)!={'payload'} or not isinstance(value['payload'],dict):return None
payload=value['payload'];keys=set(payload)
signatures={'index':{'documents','query'},'closure':{'nodes','edges','query'},
'workflow':{'nodes','dependencies','completed'},'sat':{'variables','clauses'}}
names=[name for name,signature in signatures.items() if signature==keys]
return {'name':'analytic_'+names[0],'arguments':payload} if len(names)==1 else None
def answer_contract(prompt):
"""A narrow public output instruction, not a hidden evaluator contract."""
if 'single field "answer"' not in prompt:return None
lower=prompt.lower();kind=None
if 'return a boolean' in lower or 'answer must be a boolean' in lower:kind='boolean'
elif 'coefficient list' in lower or 'return the integer list' in lower or 'task ids, sorted' in lower:kind='array'
elif 'return the encoded string' in lower:kind='string'
elif 'return its document id or null' in lower:kind=['integer','null']
prop={'type':kind} if kind is not None else {}
return {'type':'object','properties':{'answer':prop},'required':['answer'],'additionalProperties':False}
def validate_payload(feature, payload):
"""Validate bounded JSON inputs before invoking a numerical circuit."""
if feature not in CONTRACTS or not isinstance(payload, dict):
raise ValueError('Expected a known feature and JSON object payload')
props, required = CONTRACTS[feature]
unknown = set(payload) - set(props)
if unknown: raise ValueError('Unknown arguments: ' + ', '.join(sorted(unknown)))
missing = set(required) - set(payload)
if missing: raise ValueError('Missing required arguments: ' + ', '.join(sorted(missing)))
def check_json(v, depth=0):
if depth > 32: raise ValueError('JSON nesting exceeds 32')
if v is None or type(v) in (str, bool, int): return
if type(v) is float:
if not math.isfinite(v): raise ValueError('Non-finite JSON number')
return
if type(v) is list:
for item in v: check_json(item, depth+1)
return
if type(v) is dict:
if any(type(k) is not str for k in v): raise TypeError('JSON object keys must be strings')
for item in v.values(): check_json(item, depth+1)
return
raise TypeError('Non-JSON input value')
check_json(payload)
for key, value in payload.items():
kind = props[key]['type']
valid = {'string':type(value) is str, 'array':type(value) is list,
'object':type(value) is dict, 'integer':type(value) is int,
'boolean':type(value) is bool}.get(kind, False)
if not valid: raise TypeError('Invalid argument type for ' + key + ': expected ' + kind)
if feature == 'binary':
op=payload['operation']
if op not in ('xor','and','or','not','rol','ror','hex_encode','base64_encode','base64_decode'):
raise ValueError('Unknown bit operation')
needed = ['text'] if op=='base64_decode' else ['bytes'] if op in ('hex_encode','base64_encode') else ['left']
if op in ('xor','and','or'): needed.append('right')
if op in ('rol','ror'): needed.append('rotation')
for key in needed:
if key not in payload: raise ValueError('Operation '+op+' requires '+key)
if feature == 'polynomial':
if payload['operation'] not in ('add','multiply','derivative'): raise ValueError('Unsupported polynomial operation')
if payload['operation'] in ('add','multiply') and 'right' not in payload:
raise ValueError('Binary polynomial operation requires right')
if feature == 'syntax_scope' and not ('text' in payload or 'events' in payload):
raise ValueError('Provide text or scope events')
return payload
def strict_json(text):
def unique(pairs):
result={}
for key,value in pairs:
if key in result:raise ValueError('Duplicate JSON key')
result[key]=value
return result
def invalid(value):raise ValueError('Non-finite JSON number')
return json.loads(text,object_pairs_hook=unique,parse_constant=invalid)