514 lines
29 KiB
Python
514 lines
29 KiB
Python
import asyncio
|
||
import contextlib
|
||
import json
|
||
import shlex
|
||
import time
|
||
import uuid
|
||
from contextlib import asynccontextmanager
|
||
from pathlib import Path
|
||
from fastapi import FastAPI, HTTPException
|
||
from fastapi.responses import FileResponse
|
||
from fastapi.responses import JSONResponse
|
||
from pydantic import BaseModel, Field
|
||
from .config import BLENDER_BIN, CODEX_IDLE_TIMEOUT, DEFAULT_PROVIDER, PROVIDERS, CODEX_HOME, runtime_for
|
||
from .storage import SOURCE, ROOT, TASKS, MODEL, EFFORT, task_dir, workspace, load, save, write, event, events, fingerprint, digest, inside
|
||
from .rpc import AppServer, api_key
|
||
from .eda import execute
|
||
from .delivery import deliver
|
||
from .eda import verify_native
|
||
from .exports import prepare_delivery
|
||
from .checks import VALIDATION_POLICY
|
||
from .native_policy import DESIGN_POLICY, POLICY_TEXT, WORKSPACE_RULES, refresh_workspace_rules
|
||
from .preflight import check_runtime
|
||
from .readiness import readiness
|
||
|
||
CACHE, JOBS, CLIENTS = {}, {}, {}
|
||
|
||
def object_schema(properties, required=None):
|
||
return {'type':'object','properties':properties,'required':list(properties) if required is None else required,'additionalProperties':False}
|
||
|
||
def tool(name, description, properties, required=None):
|
||
return {'type':'function','name':name,'description':description,'inputSchema':object_schema(properties,required)}
|
||
|
||
STR={'type':'string'}
|
||
TOOLS=[
|
||
tool('pcb_check','Run the exact delivery electrical gate early and after edits. Accepts schematic container OR page ID and PCB document ID. All schematic pages checked. Explicit warnings are reported and accepted; errors block.',{'schematic_id':STR,'pcb_id':STR}),
|
||
tool('pcb_prepare_delivery','After pcb_check accepts, export native project/drawings/STEP/OBJ, render OBJ with installed Blender, and return a file list for pcb_deliver. Built-in chunk transfer, schematic SVG/PDF conversion, model ZIP extraction. No STEP cosmetic rebuilding; warnings are retained. Inspect outputs once before delivery.',{'schematic_id':STR,'pcb_id':STR}),
|
||
tool('pcb_proposal','Publish or replace the proposal for website review; not production authorization.',{'title':STR,'markdown':STR}),
|
||
tool('pcb_read_reference','Read official EDA API documentation. Relative path under api-reference, e.g. references/_index.md. Also available via shell during production.',{'path':STR,'offset':{'type':'integer','minimum':0},'limit':{'type':'integer','minimum':100,'maximum':40000}},['path']),
|
||
tool('pcb_eda','Operate native EasyEDA schematic/PCB objects in this task session after approval. External routing exchange (DSN/SES/auto-route JSON) is disabled. Global eda and pcb_export(file,relative_name) are available. Use code OR code_file. Full outputs preserved; uncertain writes must be inspected.',{'label':STR,'code':STR,'code_file':STR},['label']),
|
||
tool('pcb_deliver','Submit real exported files for independent validation. Rejected submission returns evidence so you can repair in the SAME session.',{'schematic_id':STR,'pcb_id':STR,'notes':STR,'files':{'type':'array','items':object_schema({'path':STR,'kind':{'type':'string','enum':['project','schematic','layout','step','render','bom','report','other']},'label':STR}), 'minItems':5}}),
|
||
tool('pcb_blocked','Record a concrete unrecoverable blocker and preserve draft. Do not use for ordinary tool errors; investigate and repair first.',{'reason':STR,'evidence':STR}),
|
||
]
|
||
NATIVE_TOOL_ITEMS={'commandExecution','dynamicToolCall','mcpToolCall','webSearch','fileChange','imageGeneration'}
|
||
|
||
def get(tid):
|
||
try:
|
||
if tid not in CACHE:
|
||
CACHE[tid]=load(tid)
|
||
return CACHE[tid]
|
||
except (ValueError,FileNotFoundError):
|
||
raise HTTPException(404,'Task not found')
|
||
|
||
def public(t):
|
||
return {k:v for k,v in t.items() if k not in {'pending_prompt','internal'}}
|
||
|
||
def frozen(t):
|
||
if t.get('approval') and fingerprint(task_runtime(t))!=t['frozen_source']:
|
||
raise RuntimeError('Backend source or runtime settings changed after approval. This acceptance run is invalid; start a new task.')
|
||
|
||
|
||
def task_runtime(t):
|
||
provider_id = t.get('ai_provider')
|
||
if not provider_id:
|
||
# Existing tasks predate per-task selection and used OpenAI exclusively.
|
||
provider_id = 'openai' if t.get('provider') in {'openai','vibemake_openai'} else DEFAULT_PROVIDER
|
||
runtime = runtime_for(provider_id)
|
||
if (t.get('runtime') and t['runtime'] != runtime.snapshot()) or any(
|
||
t.get(key, value) != value for key, value in (
|
||
('model', runtime.model), ('effort', runtime.effort), ('provider', runtime.provider))
|
||
):
|
||
raise RuntimeError('Task model or provider settings changed; restore its original configuration or create a new design. Existing sessions cannot switch providers.')
|
||
return runtime
|
||
|
||
|
||
def provider_status(runtime):
|
||
try:
|
||
if runtime.auth_mode == 'chatgpt':
|
||
configured = (CODEX_HOME/'auth.json').is_file()
|
||
else:
|
||
api_key(runtime)
|
||
configured = True
|
||
return {'id':runtime.id,'label':runtime.label,'model':runtime.model,'effort':runtime.effort,'configured':configured}
|
||
except ValueError:
|
||
return {'id':runtime.id,'label':runtime.label,'model':runtime.model,'effort':runtime.effort,'configured':False}
|
||
|
||
|
||
def codex_error(error):
|
||
error = error or {}
|
||
return ': '.join(str(error[key]) for key in ('message', 'additionalDetails') if error.get(key)) or 'Unknown Codex error'
|
||
|
||
|
||
async def require_runtime_ready(force=False):
|
||
report = await readiness.verify(force=force)
|
||
if not report['ok']:
|
||
message = ';'.join(item['message'] for item in report['checks'] if not item['ok'])
|
||
raise HTTPException(503, '绘板环境未就绪,未启动生成:' + (message or '请等待环境检查完成'))
|
||
return report
|
||
|
||
async def handle(t, method, p):
|
||
if method != 'item/tool/call':
|
||
event(t,'request.unhandled',{'method':method})
|
||
if 'requestApproval' in method:
|
||
if 'permissions' in method:
|
||
return {'permissions':{},'scope':'turn'}
|
||
return {'decision':'decline'}
|
||
if 'requestUserInput' in method:
|
||
return {'answers':{}}
|
||
if 'elicitation' in method:
|
||
return {'action':'cancel','content':None}
|
||
raise RuntimeError('Unsupported Codex request: '+method)
|
||
name, a = p['tool'],p['arguments']
|
||
event(t,'tool.started',{'tool':name,'call_id':p['callId']})
|
||
try:
|
||
frozen(t)
|
||
if t['state'] == 'cancelled':
|
||
raise RuntimeError('Task cancelled')
|
||
if name=='pcb_check':
|
||
result=await verify_native(t,a['schematic_id'],a['pcb_id'],require_pass=False)
|
||
elif name=='pcb_prepare_delivery':
|
||
result=await prepare_delivery(t,a['schematic_id'],a['pcb_id'])
|
||
elif name=='pcb_proposal':
|
||
if t.get('approval'):
|
||
raise ValueError('Already approved; preserve accepted design and finish production')
|
||
markdown=a['markdown'].strip()
|
||
if len(markdown)<120:
|
||
raise ValueError('Proposal must describe circuit, board, assumptions and deliverables')
|
||
revision=t.get('proposal',{}).get('revision',0)+1
|
||
t['proposal']={'revision':revision,'title':a['title'],'markdown':markdown,'hash':digest(markdown.encode()),'at':time.time()}
|
||
event(t,'proposal.published',t['proposal'])
|
||
result={'published':True,'revision':revision,'instruction':'Now finish your reply and wait for the website approval. Do not operate EDA.'}
|
||
elif name=='pcb_read_reference':
|
||
path=inside(ROOT/'resources',a['path'])
|
||
if path.suffix not in {'.md','.txt','.json'}:
|
||
raise ValueError('Reference text files only')
|
||
text=path.read_text()
|
||
start=max(0,a.get('offset',0));limit=min(40000,a.get('limit',18000))
|
||
result={'path':str(path),'text':text[start:start+limit],'total_chars':len(text),'next_offset':start+limit if start+limit<len(text) else None}
|
||
elif name=='pcb_eda':
|
||
if bool(a.get('code'))==bool(a.get('code_file')):
|
||
raise ValueError('Specify exactly one of code or code_file')
|
||
code=a.get('code') or inside(workspace(t),a['code_file']).read_text()
|
||
# Backward-compatible access for resumed threads whose tool catalogue is fixed.
|
||
try: request=json.loads(code)
|
||
except ValueError: request=None
|
||
if isinstance(request,dict) and 'pcb_backend_tool' in request:
|
||
if set(request)!={'pcb_backend_tool','schematic_id','pcb_id'} or not all(isinstance(v,str) for v in request.values()):
|
||
raise ValueError('Invalid common-tool request')
|
||
operation=request['pcb_backend_tool']
|
||
if operation=='prepare_delivery':
|
||
result=await prepare_delivery(t,request['schematic_id'],request['pcb_id'])
|
||
elif operation=='check':
|
||
result=await verify_native(t,request['schematic_id'],request['pcb_id'],require_pass=False)
|
||
else:raise ValueError('Unknown common backend tool')
|
||
else:
|
||
result=await execute(t,code,a['label'])
|
||
raw=json.dumps(result,ensure_ascii=False)
|
||
if len(raw)>24000:
|
||
output=workspace(t)/'evidence'/('tool-result-'+uuid.uuid4().hex+'.json')
|
||
write(output,result)
|
||
result={'output_path':str(output),'preview':raw[:18000],'truncated':True,'instruction':'Read the complete file using shell; do not guess omitted fields'}
|
||
elif name=='pcb_deliver':
|
||
if not t.get('approval') or t['state']!='running':
|
||
raise ValueError('Production approval required')
|
||
t['delivery']=await deliver(t,a)
|
||
frozen(t)
|
||
t['state']='completed'
|
||
event(t,'delivery.completed',t['delivery'])
|
||
result={'accepted':True,'files':t['delivery']['files'],'instruction':'Delivery verified; give a concise user summary and finish.'}
|
||
elif name=='pcb_blocked':
|
||
if not t.get('approval'):
|
||
raise ValueError('Publish assumptions or questions in the proposal during review')
|
||
t['state']='blocked';t['error']=a['reason'];t['blocker_evidence']=a['evidence']
|
||
event(t,'production.blocked',a)
|
||
result={'recorded':True,'instruction':'Report the blocker honestly and stop.'}
|
||
else:
|
||
raise ValueError('Unknown tool '+name)
|
||
event(t,'tool.completed',{'tool':name,'call_id':p['callId']})
|
||
return {'success':True,'contentItems':[{'type':'inputText','text':json.dumps(result,ensure_ascii=False)}]}
|
||
except Exception as e:
|
||
event(t,'tool.error',{'tool':name,'message':str(e)})
|
||
return {'success':False,'contentItems':[{'type':'inputText','text':str(e)}]}
|
||
|
||
async def run_turn(t, prompt, production):
|
||
frozen(t)
|
||
runtime=task_runtime(t)
|
||
directory=workspace(t)
|
||
refresh_workspace_rules(directory)
|
||
prompt=POLICY_TEXT+'\n'+prompt
|
||
async with AppServer(directory, production, lambda m,p:handle(t,m,p), runtime=runtime) as client:
|
||
CLIENTS[t['id']]=client
|
||
instructions=(SOURCE/'instructions.md').read_text()
|
||
if runtime.id=='doubao':
|
||
instructions+='\nThis provider has no built-in web-search tool in this integration. In review, mark unverified library/device choices as assumptions. During approved production, retrieve manufacturer references using native Shell/network and inspect the downloaded evidence.\n'
|
||
common={'model':runtime.model,'modelProvider':runtime.provider,'cwd':str(directory),'approvalPolicy':'never','sandbox':'workspace-write' if production else 'read-only','developerInstructions':instructions,'serviceTier':'default'}
|
||
if t.get('thread_id'):
|
||
result=await client.call('thread/resume',dict(common,threadId=t['thread_id'],excludeTurns=True))
|
||
if result['thread']['id']!=t['thread_id']:
|
||
raise RuntimeError('Codex resumed a different thread')
|
||
event(t,'session.resumed',{'thread_id':t['thread_id']})
|
||
else:
|
||
result=await client.call('thread/start',dict(common,ephemeral=False,dynamicTools=TOOLS,serviceName='vibemake-persistent-pcb',allowProviderModelFallback=False))
|
||
t['thread_id']=result['thread']['id']
|
||
event(t,'session.created',{'thread_id':t['thread_id'],'model':result.get('model')})
|
||
if result.get('model') not in {None,runtime.model}:
|
||
raise RuntimeError('Unexpected model substitution')
|
||
policy={'type':'workspaceWrite','writableRoots':[str(directory)],'networkAccess':True,'excludeSlashTmp':True,'excludeTmpdirEnvVar':True} if production else {'type':'readOnly','networkAccess':False}
|
||
reply=await client.call('turn/start',{'threadId':t['thread_id'],'input':[{'type':'text','text':prompt}],'model':runtime.model,'effort':runtime.effort,'approvalPolicy':'never','sandboxPolicy':policy})
|
||
t['turn_id']=reply['turn']['id'];t['turn_started_at']=time.time()
|
||
event(t,'turn.started',{'turn_id':t['turn_id'],'production':production,'ai_provider':runtime.id,'model':runtime.model,'effort':runtime.effort,'source_hash':fingerprint(runtime)})
|
||
trace=directory/'evidence'/'codex-events.jsonl'
|
||
trace.parent.mkdir(exist_ok=True)
|
||
last_progress=time.monotonic()
|
||
last_error=None
|
||
active_tools=set()
|
||
tools_were_active=False
|
||
while True:
|
||
# A live transport/heartbeat is not evidence that the model is making
|
||
# progress. Native tool requests have their own execution timeouts.
|
||
tools_active=bool(client.requests or active_tools)
|
||
# Give a request that finished during the wait a fresh model idle
|
||
# window, rather than charging its execution time to the model.
|
||
if tools_active or tools_were_active:
|
||
last_progress=time.monotonic()
|
||
tools_were_active=tools_active
|
||
remaining=CODEX_IDLE_TIMEOUT-(time.monotonic()-last_progress)
|
||
if remaining<=0:
|
||
detail=' Last upstream error: '+last_error if last_error else ''
|
||
raise RuntimeError(f'Codex made no progress for {CODEX_IDLE_TIMEOUT} seconds. Check the model API address, authentication and network; the same session is retained for retry.'+detail)
|
||
try:
|
||
msg=await asyncio.wait_for(client.events.get(),min(30,remaining))
|
||
except asyncio.TimeoutError:
|
||
event(t,'heartbeat',{'turn_id':t['turn_id'],'elapsed':round(time.time()-t['turn_started_at'])})
|
||
continue
|
||
method,p=msg['method'],msg.get('params',{})
|
||
if method in {'transport/closed','transport/error'}:
|
||
raise ConnectionError(p.get('message','Codex disconnected'))
|
||
if p.get('threadId') not in {None,t['thread_id']}:
|
||
continue
|
||
if p.get('turnId') not in {None,t['turn_id']}:
|
||
continue
|
||
# Store complete native event evidence; no lossy context reconstruction.
|
||
with trace.open('a') as f:
|
||
f.write(json.dumps(msg,ensure_ascii=False)+'\n')
|
||
if method.startswith('item/') or method=='thread/tokenUsage/updated':
|
||
last_progress=time.monotonic()
|
||
if method=='error':
|
||
last_error=codex_error(p.get('error'))
|
||
if p.get('willRetry'):
|
||
event(t,'session.reconnecting',{'message':last_error,'native_retry':True})
|
||
else:
|
||
raise RuntimeError(last_error)
|
||
elif method=='item/completed':
|
||
item=p.get('item',{})
|
||
active_tools.discard(item.get('id'))
|
||
if item.get('type')=='agentMessage':
|
||
event(t,'message',{'role':'assistant','text':item.get('text',''),'phase':item.get('phase')})
|
||
elif item.get('type') not in {'userMessage','reasoning'}:
|
||
event(t,'activity',{'kind':item.get('type'),'status':item.get('status'),'command':item.get('command'),'tool':item.get('tool')})
|
||
elif method=='item/started':
|
||
item=p.get('item',{})
|
||
if item.get('type') in NATIVE_TOOL_ITEMS and item.get('id'):
|
||
active_tools.add(item['id'])
|
||
if item.get('type') not in {'userMessage','agentMessage','reasoning'}:
|
||
event(t,'activity',{'kind':item.get('type'),'status':'running','command':item.get('command'),'tool':item.get('tool')})
|
||
elif method=='thread/tokenUsage/updated':
|
||
t['usage']=p.get('tokenUsage');save(t)
|
||
elif method=='turn/completed' and p.get('turn',{}).get('id')==t['turn_id']:
|
||
turn=p['turn']
|
||
event(t,'turn.completed',{'turn_id':turn['id'],'status':turn['status'],'error':turn.get('error')})
|
||
if turn['status']!='completed':
|
||
raise RuntimeError('Codex turn '+turn['status']+': '+codex_error(turn.get('error')))
|
||
return
|
||
|
||
async def work(t, prompt, production):
|
||
t['pending_prompt']=prompt
|
||
save(t)
|
||
try:
|
||
if production:
|
||
frozen(t)
|
||
report = await check_runtime(workspace(t))
|
||
event(t, 'runtime.checked', report)
|
||
with contextlib.suppress(OSError):
|
||
write(workspace(t) / 'evidence/runtime-check.json', report)
|
||
if not report['ok']:
|
||
raise RuntimeError('生产环境预检未通过:' + ';'.join(
|
||
item['message'] for item in report['checks'] if not item['ok']))
|
||
else:
|
||
await require_runtime_ready()
|
||
failures=0;no_progress=0
|
||
while True:
|
||
before=t.get('eda_calls',0)
|
||
try:
|
||
await run_turn(t,prompt,production)
|
||
failures=0
|
||
except (ConnectionError,asyncio.TimeoutError) as e:
|
||
if t['state'] in {'cancelled','completed','blocked'}:
|
||
break
|
||
failures+=1
|
||
event(t,'session.reconnecting',{'attempt':failures,'message':str(e)})
|
||
if failures>=5:
|
||
raise
|
||
await asyncio.sleep(min(5*failures,30))
|
||
prompt='Connection recovery. Continue the existing approved task from the full conversation and actual files/EDA state. Inspect uncertain mutations before replaying anything.' if production else t['pending_prompt']
|
||
continue
|
||
if not production:
|
||
if t.get('proposal'):
|
||
t['state']='review'
|
||
else:
|
||
t['state']='needs_input'
|
||
t['error']='Codex has not published a proposal; add a comment to continue.'
|
||
save(t);break
|
||
if t['state'] in {'completed','blocked','cancelled'}:
|
||
break
|
||
no_progress=no_progress+1 if before==t.get('eda_calls',0) else 0
|
||
if no_progress>=3:
|
||
raise RuntimeError('Three completed turns made no EDA progress and produced no verified delivery. Draft and full session retained.')
|
||
prompt='The approved task is still incomplete: no accepted pcb_deliver result exists. Continue autonomously in this same session, inspect the actual workspace/EDA, resolve remaining problems and deliver. If a concrete external blocker makes further progress impossible, use pcb_blocked with evidence. Do not merely state intentions.'
|
||
event(t,'production.continued',{'reason':'No verified delivery yet','same_thread':t['thread_id']})
|
||
except asyncio.CancelledError:
|
||
if t['state'] not in {'completed','cancelled','blocked'}:
|
||
t['state']='interrupted'
|
||
event(t,'session.interrupted',{'resume_same_thread':t.get('thread_id')})
|
||
raise
|
||
except Exception as e:
|
||
if t['state'] not in {'completed','cancelled','blocked'}:
|
||
t['state']='failed';t['error']=str(e)
|
||
event(t,'session.failed',{'message':str(e)})
|
||
finally:
|
||
CLIENTS.pop(t['id'],None)
|
||
JOBS.pop(t['id'],None)
|
||
t['busy']=False;save(t)
|
||
|
||
def schedule(t,prompt,production):
|
||
if t['id'] in JOBS:
|
||
raise HTTPException(409,'Task already running')
|
||
t['busy']=True
|
||
t['state']='running' if production else 'planning'
|
||
t.pop('error',None)
|
||
save(t)
|
||
JOBS[t['id']]=asyncio.create_task(work(t,prompt,production))
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app):
|
||
TASKS.mkdir(parents=True,exist_ok=True)
|
||
readiness.start(force=True)
|
||
for p in TASKS.glob('*/state.json'):
|
||
t=json.loads(p.read_text());CACHE[t['id']]=t
|
||
if t['state'] not in {'completed','cancelled','blocked','failed'} and (t.get('busy') or t['state'] in {'running','planning','interrupted'}):
|
||
t['check_eda_session']=bool(t.get('eda_session'))
|
||
prompt=('Service restarted. Continue this approved task in the same session. Inspect live state and existing files before repeating uncertain actions.' if t.get('approval') else t.get('pending_prompt',t['request']))
|
||
schedule(t,prompt,bool(t.get('approval')))
|
||
yield
|
||
for job in list(JOBS.values()):
|
||
job.cancel()
|
||
await asyncio.gather(*list(JOBS.values()),return_exceptions=True)
|
||
await readiness.close()
|
||
|
||
app=FastAPI(lifespan=lifespan)
|
||
|
||
class Request(BaseModel):
|
||
text:str=Field(min_length=5,max_length=16000)
|
||
class DesignRequest(Request):
|
||
provider:str | None=None
|
||
class Approval(BaseModel):
|
||
revision:int
|
||
hash:str
|
||
|
||
@app.get('/api/health')
|
||
async def health():
|
||
runtime=runtime_for()
|
||
return {'ok':True,'runtime_ready':readiness.snapshot()['ok'],'engine':'persistent-codex','model':runtime.model,'effort':runtime.effort,'source_hash':fingerprint(),'legacy_pipeline':False,'auth_mode':runtime.auth_mode,'model_provider':runtime.provider,'model_api_base_url':runtime.api_base_url if runtime.auth_mode=='apikey' else None,'default_provider':DEFAULT_PROVIDER,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY,'delivery_toolkit':1}
|
||
|
||
@app.get('/api/readiness')
|
||
async def runtime_readiness():
|
||
readiness.start()
|
||
return JSONResponse(readiness.snapshot(), headers={'Cache-Control': 'no-store'})
|
||
|
||
@app.post('/api/readiness/check')
|
||
async def recheck_runtime():
|
||
# Coalesce concurrent visitors and throttle repeated manual retries.
|
||
recent = readiness.report and time.time() - readiness.report['checked_at'] < 5
|
||
readiness.start(force=not recent)
|
||
return JSONResponse(readiness.snapshot(), headers={'Cache-Control': 'no-store'})
|
||
|
||
@app.get('/api/ready')
|
||
async def deployment_ready():
|
||
report = readiness.snapshot()
|
||
return JSONResponse(report, status_code=200 if report['ok'] else 503,
|
||
headers={'Cache-Control': 'no-store'})
|
||
|
||
@app.get('/api/providers')
|
||
async def list_providers():
|
||
return {'default_provider':DEFAULT_PROVIDER,'providers':[provider_status(runtime_for(name)) for name in PROVIDERS]}
|
||
|
||
@app.get('/api/sessions')
|
||
async def list_sessions():
|
||
return sorted([public(t) for t in CACHE.values()],key=lambda t:t['created_at'],reverse=True)
|
||
|
||
@app.post('/api/sessions',status_code=201)
|
||
async def create(req:DesignRequest):
|
||
try:
|
||
runtime=runtime_for(req.provider)
|
||
except ValueError as e:
|
||
raise HTTPException(400,str(e)) from None
|
||
if not provider_status(runtime)['configured']:
|
||
raise HTTPException(503,runtime.label+' 未配置可用的服务端凭据,请先配置 '+runtime.key_name+' 或对应登录文件。')
|
||
await require_runtime_ready(force=True)
|
||
tid='pcb-'+uuid.uuid4().hex[:24]
|
||
t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':runtime.model,'effort':runtime.effort,'provider':runtime.provider,'ai_provider':runtime.id,'runtime':runtime.snapshot(),'busy':False,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY}
|
||
directory=workspace(t);directory.mkdir(parents=True)
|
||
for name in ('artifacts','evidence','scripts','tmp'):
|
||
(directory/name).mkdir()
|
||
(directory/'api-reference').symlink_to(ROOT/'resources',target_is_directory=True)
|
||
(directory/'AGENTS.md').write_text(WORKSPACE_RULES)
|
||
CACHE[tid]=t;save(t)
|
||
event(t,'message',{'role':'user','text':req.text})
|
||
schedule(t,'User requirement:\n'+req.text+'\n\nFirst prepare a reviewable proposal and publish it with pcb_proposal. Do not produce the board yet.',False)
|
||
return public(t)
|
||
|
||
@app.get('/api/sessions/{tid}')
|
||
async def detail(tid:str):
|
||
return public(get(tid))
|
||
|
||
@app.get('/api/sessions/{tid}/events')
|
||
async def history(tid:str,after:int=0):
|
||
get(tid)
|
||
return events(tid,after)
|
||
|
||
@app.post('/api/sessions/{tid}/comments')
|
||
async def comment(tid:str,req:Request):
|
||
t=get(tid)
|
||
if t.get('approval') or t['state'] not in {'review','needs_input','failed'} or t.get('busy'):
|
||
raise HTTPException(409,'Comments are allowed only while reviewing a proposal')
|
||
cursor=t['cursor']
|
||
await require_runtime_ready()
|
||
if t['cursor']!=cursor:
|
||
raise HTTPException(409,'Task changed during environment check; reload before retrying')
|
||
event(t,'message',{'role':'user','text':req.text})
|
||
schedule(t,'User review comment:\n'+req.text+'\nRevise the proposal in this same conversation and publish a replacement with pcb_proposal. This is not production authorization.',False)
|
||
return public(t)
|
||
|
||
@app.post('/api/sessions/{tid}/approve')
|
||
async def approve(tid:str,req:Approval):
|
||
t=get(tid)
|
||
p=t.get('proposal',{})
|
||
if t.get('approval'):
|
||
if t['approval']['hash']==req.hash:
|
||
return public(t)
|
||
raise HTTPException(409,'Different proposal already approved')
|
||
if t['state']!='review' or t.get('busy') or p.get('revision')!=req.revision or p.get('hash')!=req.hash:
|
||
raise HTTPException(409,'Approve the latest completed proposal revision')
|
||
cursor=t['cursor']
|
||
await require_runtime_ready(force=True)
|
||
if t['cursor']!=cursor:
|
||
raise HTTPException(409,'Task changed during environment check; reload before approving')
|
||
t['approval']={'revision':req.revision,'hash':req.hash,'at':time.time()}
|
||
t['frozen_source']=fingerprint(task_runtime(t))
|
||
t['design_policy']=DESIGN_POLICY
|
||
event(t,'proposal.approved',t['approval'])
|
||
prompt=f'''The user explicitly clicked APPROVE AND START for proposal revision {req.revision}, SHA256 {req.hash}.
|
||
This server-owned approval authorizes production of the accepted proposal in this same persistent session. Earlier requests to wait applied only to review.
|
||
Workspace: {workspace(t)}
|
||
Official API documentation: {workspace(t)}/api-reference/references/_index.md
|
||
{POLICY_TEXT}
|
||
Blender: {shlex.quote(BLENDER_BIN)} (render exported native 3D geometry only).
|
||
Now use native Codex tools and pcb_eda to implement, inspect, fix, route, verify and export the real board. You write the design scripts yourself. No fixed backend design pipeline exists. Keep working until pcb_deliver accepts native project, schematic, layout, assembled STEP and real 3D render. Do not edit backend code or use legacy PCB flows. Backend source is frozen for this run.
|
||
Accepted proposal:\n{p['markdown']}'''
|
||
schedule(t,prompt,True)
|
||
return public(t)
|
||
|
||
@app.post('/api/sessions/{tid}/cancel')
|
||
async def cancel(tid:str):
|
||
t=get(tid)
|
||
if t['state']=='completed':
|
||
raise HTTPException(409,'Already completed')
|
||
t['state']='cancelled';event(t,'task.cancelled',{})
|
||
client=CLIENTS.get(tid)
|
||
if client and t.get('turn_id'):
|
||
with contextlib.suppress(Exception):
|
||
await client.call('turn/interrupt',{'threadId':t['thread_id'],'turnId':t['turn_id']},timeout=10)
|
||
job=JOBS.get(tid)
|
||
if job:
|
||
job.cancel()
|
||
return public(t)
|
||
|
||
@app.post('/api/sessions/{tid}/resume')
|
||
async def resume(tid:str):
|
||
t=get(tid)
|
||
if t.get('busy') or t['state'] not in {'failed','blocked','interrupted','cancelled'}:
|
||
raise HTTPException(409,'Task is not resumable')
|
||
try:
|
||
frozen(t)
|
||
except RuntimeError as e:
|
||
raise HTTPException(409,str(e))
|
||
cursor=t['cursor']
|
||
await require_runtime_ready(force=True)
|
||
if t['cursor']!=cursor:
|
||
raise HTTPException(409,'Task changed during environment check; reload before resuming')
|
||
t['check_eda_session']=bool(t.get('eda_session'))
|
||
event(t,'task.resume_requested',{})
|
||
schedule(t,'The user requests continuing this same task. Preserve the accepted design and inspect actual saved files and EDA state. Continue to verified delivery.' if t.get('approval') else 'Continue the proposal review and publish a complete proposal.',bool(t.get('approval')))
|
||
return public(t)
|
||
|
||
@app.get('/api/sessions/{tid}/files/{name}')
|
||
async def download(tid:str,name:str):
|
||
t=get(tid)
|
||
item=next((f for f in t.get('delivery',{}).get('files',[]) if f['name']==name),None)
|
||
if not item or t['state']!='completed':
|
||
raise HTTPException(404,'Verified artifact not found')
|
||
path=inside(task_dir(tid)/'delivery',name)
|
||
if digest(path.read_bytes())!=item['sha256']:
|
||
raise HTTPException(409,'Artifact checksum mismatch')
|
||
return FileResponse(path,filename=name,headers={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'})
|