Spaces:
Sleeping
Sleeping
File size: 6,498 Bytes
115b94d | 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 | """Server-owned, task/version-bound budget proposals. Never account balances."""
from src.modules.skill.domain.models import digest
TITLES={'design':'技术设计','code':'生成源码','repair':'根据编译或测试诊断修复','diagnose':'定位失败原因'}
APPROVABLE={'STAGE_CONTEXT_BUDGET_EXCEEDED','TASK_TOKEN_BUDGET_EXCEEDED'}
TOKEN_INCREMENT=12000
def context_binding(run,check):
return digest({'snapshot':run['snapshot']['snapshot_digest'],'request':run['request'],
'cursor':run['cursor'],'repairs':run['repairs'],'repair_pending':run.get('repair_pending'),
'repair_failure_code':run.get('repair_failure_code'),
'outputs':run['outputs'],'check':check})
def ledger_binding(calls):
return digest([{k:c.get(k) for k in ('id','state','charged','reservation')} for c in calls])
def propose(run,check,calls,now,provider=None):
if run.get('cancel_requested') or (check.get('rejection') or [None])[0] not in APPROVABLE:
return None,'BUDGET_NOT_ADJUSTABLE'
if any(c['state'] in {'unknown','reserved'} for c in calls):return None,'MODEL_RESULT_UNKNOWN'
if len(calls)>=run['budget']['max_model_calls']:return None,'MODEL_CALL_BUDGET_EXCEEDED'
input_bound=check['input_bound'];output=check['output_target']
model_limit=getattr(provider,'context_window',None) if provider is not None else check.get('model_context_limit')
if type(model_limit) is not int or model_limit<=0:model_limit=None
if model_limit is not None:
if input_bound+check['minimum_output']>model_limit:return None,'MODEL_CONTEXT_LIMIT_EXCEEDED'
output=min(output,model_limit-input_bound)
settled=sum(c['charged'] or 0 for c in calls)
reserved=sum(c['reservation'] for c in calls if c['charged'] is None)
current_task=run['budget']['max_tokens'];current_stage=max(check['stage_limit'],run.get('approved_stage_limits',{}).get(check['stage'],0))
# One explicit approval buys exactly one increment, never an inferred total.
# If it still cannot fit, the next preflight pauses for another approval.
stage_limit=current_stage+TOKEN_INCREMENT if input_bound+check['minimum_output']>current_stage else current_stage
task_limit=current_task+TOKEN_INCREMENT
output=max(0,min(output,stage_limit-input_bound,task_limit-settled-reserved-input_bound))
if task_limit>1000000 or stage_limit>128000:return None,'BUDGET_POLICY_LIMIT_EXCEEDED'
stage_delta=stage_limit-current_stage;task_delta=task_limit-current_task
if not stage_delta and not task_delta:return None,'BUDGET_RECHECK_REQUIRED'
model=getattr(provider,'model',None) or check.get('model')
if not model:return None,'MODEL_ROUTE_UNAVAILABLE'
proposal={'stage':check['stage'],'stage_title':TITLES.get(check['stage'],check['stage']),
'resume_step':TITLES.get(check['stage'],check['stage']),'model':model,
'reason':check['rejection'][0],'adjustment':'stage_and_task' if stage_delta and task_delta else 'task' if task_delta else 'stage',
'token_increment':TOKEN_INCREMENT,
'input_bound':input_bound,'input_estimator':check['estimator'],'safety_tokens':check['safety_tokens'],
'output_reservation':output,'output_target':check['output_target'],
'planned_call_reservation':input_bound+output,
'current_task_limit':current_task,'task_limit':task_limit,'task_delta':task_delta,
'current_stage_limit':current_stage,'stage_limit':stage_limit,'stage_delta':stage_delta,
'settled_tokens':settled,'reserved_tokens':reserved,'task_remaining':current_task-settled-reserved,
'model_context_limit':model_limit,'model_context_limit_verified':model_limit is not None,
'model_call_limit':run['budget']['max_model_calls'],'remaining_calls':run['budget']['max_model_calls']-len(calls),
'currency_estimate':None,'price_basis':None,'provider_balance':'not_verified',
'scope':'current_task_current_adjustment','created_at':now,'expires_at':now+900,
'context_binding':context_binding(run,check),'ledger_binding':ledger_binding(calls)}
return proposal,None
def seal(run,proposal,revision):
value={**proposal,'task_revision':revision}
value.pop('digest',None)
value['digest']=digest({'run':run['id'],**value})
return value
def limit_proposal(run,calls,now):
"""Adjust only a known call/time/repair ceiling; never an environment fault."""
if any(c['state'] in {'unknown','reserved'} for c in calls):return None
error=run.get('error');before=run['budget'];after=dict(before)
if error=='RUN_TIME_BUDGET_EXCEEDED':after['max_seconds']=min(3600,max(before['max_seconds']+300,int(run['active_seconds'])+310))
elif error=='MODEL_CALL_BUDGET_EXCEEDED':after['max_model_calls']=min(6,before['max_model_calls']+1)
elif error in {'JAVA_BUILD_FAILED','JAVA_TEST_FAILED'} and run['repairs']>=before['max_repairs']:
after['max_repairs']=min(2,before['max_repairs']+1)
if len(calls)>=before['max_model_calls']:after['max_model_calls']=min(6,before['max_model_calls']+1)
else:return None
if before==after:return None
node_id=run['release']['execution_order'][min(run['cursor'],len(run['release']['execution_order'])-1)]
node=next(n for n in run['release']['draft']['graph']['nodes'] if n['id']==node_id)
operation=(node.get('operation_ref') or '').split('@')[0]
stage='repair' if error in {'JAVA_BUILD_FAILED','JAVA_TEST_FAILED'} or run.get('repair_pending') else {'AO04':'design','AO05':'code','AO08':'build','AO09':'test'}.get(operation,node_id)
model=next((c['metadata'].get('model') for c in reversed(calls) if c['metadata'].get('stage')==stage),None)
if not model and stage in TITLES:model=next((c.get('model') for c in reversed(run.get('budget_checks',[])) if c['stage']==stage),None)
return {'limit_kind':error,'before':before,'after':after,'reason':error,
'stage':stage,'resume_step':TITLES.get(stage,stage),'model':model or ('待服务端路由核对,不允许切换更贵模型' if stage in TITLES else '本步骤不调用模型'),
'settled_tokens':sum(c['charged'] or 0 for c in calls),
'reserved_tokens':sum(c['reservation'] for c in calls if c['charged'] is None),
'calls':len(calls),'active_seconds':run['active_seconds'],'repairs':run['repairs'],
'ledger_binding':ledger_binding(calls),'context_binding':context_binding(run,{}),
'created_at':now,'expires_at':now+900,'scope':'current_task_current_adjustment'}
|