"""Small server-owned limits layered over the existing ledger and interpreter.""" import os import time from contextlib import contextmanager from src.modules.skill.domain.models import SkillError DEFAULTS={'version':'intranet-light-v1','max_features':3,'max_acceptance':5, 'max_model_calls':4,'max_tokens':120000,'max_repairs':1,'max_seconds':900,'scope_budget_percent':50, 'queue_seconds':900,'design_context':20000,'code_context':32000,'repair_context':32000, 'design_output':2048,'code_output':8192,'repair_output':12288} def configured(overrides=None): values={**DEFAULTS,**(overrides or {})} if set(values)!=set(DEFAULTS) or values['version']!=DEFAULTS['version'] or any(type(v) is not int or v<=0 for k,v in values.items() if k!='version'): raise ValueError('RESOURCE_LIMITS_REQUIRED') if values['scope_budget_percent']>50 or values['max_seconds']>3600 or values['max_model_calls']>6 or values['max_tokens']>1000000 or values['max_repairs']>2: raise ValueError('RESOURCE_LIMITS_POLICY_EXCEEDED') return values def time_remaining(run,now=None): now=time.time() if now is None else now used=run['active_seconds']+max(0,now-run.get('claim_started_at',now)) if run['status']=='running' else run['active_seconds'] return run['budget']['max_seconds']-used def require_time(run,expected,now=None): if run['request'].get('resource_limits') and time_remaining(run,now)=timeout:raise SkillError('RESOURCE_QUEUE_TIMEOUT','资源排队达到上限,未启动新工作。',409) time.sleep(.05) yield time.monotonic()-start finally: if locked: handle.seek(0) if os.name=='nt': import msvcrt msvcrt.locking(handle.fileno(),msvcrt.LK_UNLCK,1) else: import fcntl fcntl.flock(handle.fileno(),fcntl.LOCK_UN) def timing_guidance(store): """Observed successful stage timings only; never silently extend a timeout.""" samples={} with store.connect() as db: rows=db.execute("SELECT id FROM web_jobs WHERE state='verified' ORDER BY rowid DESC LIMIT 20").fetchall() for row in rows: starts={} for event in store.stages(row['id']): stage=event['stage'] if event['status']=='started':starts[stage]=event['timestamp'] if event['status']=='completed' and stage in starts: samples.setdefault(stage,[]).append(max(0,event['timestamp']-starts.pop(stage))) return {stage:{'samples':len(values),'max_observed_seconds':max(values), 'suggested_seconds':int(max(values)*2+15),'applied':False} for stage,values in samples.items()}