VibeCoding / src /apps /workbench /agent_sandboxes.py
dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
12.5 kB
"""Owner- and artifact-bound Agent execution units; never a shared active preview."""
import json
import threading
import time
import uuid
from pathlib import Path
from src.adapters.sandbox.preview import PreviewSession
from src.modules.skill.domain.models import SkillError,digest
class VerifiedPageSession:
"""A page-only preview bound to existing real VM evidence and an opaque browser frame."""
execution_mode='verified-static-page'
def __init__(self, source, evidence):
self.source=source;self.id=uuid.uuid4().hex;self.expires=time.time()+900
self._status='ready';self.error=None;self.started_at=time.time()
candidate=evidence['manifest']['candidate'];tested=evidence['manifest']['test']
self.receipt={'source_digest':source['source_digest'],'image':candidate['image'],
'config_digest':candidate['config_digest'],'classes_digest':candidate['classes_digest'],
'tests':tested['passed_cases'],'verification':'existing-vm-evidence',
'network':'none','host_mounts':[]}
@property
def status(self):
if self._status=='ready' and time.time()>=self.expires:self._status='closed'
return self._status
def progress(self):
return {'started_at':self.started_at,'server_time':time.time(),'elapsed_seconds':max(0,time.time()-self.started_at),
'events':[{'at':self.started_at,'phase':'ready','detail':'已使用当前源码的隔离验证证据。'}],
'process_alive':False}
def request(self,*args,**kwargs):
raise SkillError('PREVIEW_API_UNAVAILABLE','此网页应用没有服务端业务接口。',403)
def close(self):self._status='closed'
class AgentSandboxPool:
# Grace protects reload/navigation; timeout also covers a crashed browser.
BROWSER_GRACE=8
BROWSER_TIMEOUT=120
def __init__(self, engine, capacity=3, factory=PreviewSession, *, clock=time.monotonic):
if type(capacity) is not int or not 1<=capacity<=8:raise ValueError('Sandbox capacity must be 1..8')
self.engine,self.capacity,self.factory=engine,capacity,factory
self.lock=threading.RLock();self.units={};self.selected={};self.threads=[]
self.clock=clock;self.stopping=threading.Event()
self.reaper=threading.Thread(target=self._reap_loop,daemon=True,name='preview-browser-reaper')
self.reaper.start()
def _reap_loop(self):
while not self.stopping.wait(2):
with self.lock:self._reap_locked()
def _reap_locked(self):
now=self.clock()
for unit in self.units.values():
if unit['session'].status not in {'starting','ready'} or unit.get('prewarm'):continue
clients=unit['clients']
for key,seen in list(clients.items()):
if now-seen>=self.BROWSER_TIMEOUT:clients.pop(key)
if clients:continue
if unit['browser_seen'] and unit['close_after'] is None:unit['close_after']=now+self.BROWSER_GRACE
deadline=unit['close_after'] if unit['browser_seen'] else unit['claim_deadline']
if deadline is not None and now>=deadline:
unit['session'].close();unit['close_reason']='browser-disconnected';self._persist(unit)
def browser_client(self, actor, preview_id, client_id, event):
with self.lock:
unit=self._authorized(actor,preview_id)
self._reap_locked()
session=unit['session'];clients=unit['clients']
if session.status not in {'starting','ready'}:
if event=='release':return {'status':session.status}
raise SkillError('PREVIEW_NOT_READY','本次预览已结束,请从工作台重新打开。',409)
if event=='attach':
if client_id not in clients and len(clients)>=32:raise SkillError('PREVIEW_CLIENT_LIMIT','此应用打开的窗口过多。',429)
clients[client_id]=self.clock();unit['browser_seen']=True;unit['close_after']=None
elif event=='heartbeat':
# A late in-flight heartbeat must never resurrect a closed document.
if client_id not in clients:raise SkillError('PREVIEW_CLIENT_GONE','请重新打开此应用。',409)
clients[client_id]=self.clock()
elif event=='release':
if client_id in clients:
clients.pop(client_id)
if not clients:unit['close_after']=self.clock()+self.BROWSER_GRACE
else:raise SkillError('INVALID_INPUT','窗口状态不符合契约。',422)
return {'status':session.status}
def _authorized(self, actor, preview_id=None):
key=preview_id or self.selected.get(actor.user_id)
unit=self.units.get(key)
if not unit or unit['owner']!=actor.user_id:
raise SkillError('PREVIEW_NOT_FOUND','该应用预览不存在或已结束。',404)
self.engine.spec(actor,unit['scenario'])
return unit
def _state(self, unit):
session=unit['session']
return dict(id=session.id,agent_id='agent-'+session.id,scenario=unit['scenario'],kind=unit['kind'],reference=unit['reference'],
status=session.status,error=session.error,expires_at=session.expires,receipt=session.receipt,
diagnostics=getattr(session,'diagnostics',None),
backend=getattr(session,'execution_mode','qemu'),progress=session.progress(),
url=getattr(self.engine,'preview_origin','')+'/preview-site/?lease='+session.id if session.status=='ready' else None)
def state(self, actor, preview_id=None):
with self.lock:
self._reap_locked()
return self._state(self._authorized(actor,preview_id))
def find(self, actor, kind, reference):
with self.lock:
self._reap_locked()
for unit in reversed(list(self.units.values())):
if unit['owner']==actor.user_id and unit['kind']==kind and unit['reference']==reference and unit['session'].status in {'starting','ready'}:
if unit.get('prewarm'):
unit['prewarm']=False;unit['claim_deadline']=self.clock()+self.BROWSER_TIMEOUT
unit['session'].expires=time.time()+900;self.selected[actor.user_id]=unit['session'].id
return self._state(self._authorized(actor,unit['session'].id))
raise SkillError('PREVIEW_NOT_FOUND','该应用尚未打开,请从对应工程启动。',404)
def start(self, actor, kind, reference, *, prewarm=False):
scenario,_,evidence=self.engine.evidence(actor,kind,reference)
runtime=self.engine.runtimes[scenario];source=evidence['manifest']['source']
runtime.harness.files({'files':source['files']},evidence['manifest']['snapshot']['framework'])
candidate=evidence['manifest'].get('candidate',{})
fast_page=(scenario=='webapp' and candidate.get('execution_mode') in {'qemu','docker'}
and candidate.get('source_digest')==source['source_digest']
and candidate.get('config_digest')==digest(runtime.sandbox.config)
and candidate.get('image')==runtime.sandbox.config.image
and evidence['manifest']['test'].get('suite_digest')==runtime.sandbox.suite_digest)
if fast_page:
runtime.harness.evidence(evidence['manifest']['test'],candidate,'test')
runtime.harness.evidence(evidence['manifest']['preview'],candidate,'preview')
with self.lock:
self._reap_locked()
for unit in self.units.values():
session=unit['session']
if (unit['owner']==actor.user_id and unit['kind']==kind and unit['reference']==reference
and session.source['source_digest']==source['source_digest'] and session.status in {'starting','ready'}):
if not prewarm:
if unit['prewarm']:unit['claim_deadline']=self.clock()+self.BROWSER_TIMEOUT
unit['prewarm']=False;session.expires=time.time()+900
self.selected[actor.user_id]=session.id
return self._state(unit)
if sum(u['session'].status in {'starting','ready'} for u in self.units.values())>=self.capacity:
idle=next((u for u in self.units.values() if u.get('prewarm') and u['session'].status in {'starting','ready'}),None)
if prewarm:return None
if idle:
idle['session'].close();idle['prewarm']=False;self._persist(idle)
else:
if any(u['session'].status in {'starting','ready'} and u.get('close_after') is not None for u in self.units.values()):
raise SkillError('SANDBOX_RELEASING','正在释放已关闭的应用,请稍候。',409)
raise SkillError('SANDBOX_CAPACITY_EXCEEDED','并行应用已达到本机容量,请关闭一个不再使用的预览后重试。',409)
session=VerifiedPageSession(source,evidence) if fast_page else self.factory(runtime.sandbox,source)
# Reuse only evidence bound to the exact current source, image, configuration and suite.
if not fast_page and isinstance(session,PreviewSession):
test=evidence['manifest'].get('test',{})
if (candidate.get('source_digest')==source['source_digest']
and candidate.get('config_digest')==digest(runtime.sandbox.config)
and candidate.get('image')==runtime.sandbox.config.image
and candidate.get('suite_digest')==runtime.sandbox.suite_digest
and test.get('suite_digest')==runtime.sandbox.suite_digest):
runtime.harness.evidence(test,candidate,'test')
session.tested_candidate=candidate;session.tested_evidence=test
if prewarm:session.expires=min(session.expires,time.time()+180)
unit={'owner':actor.user_id,'scenario':scenario,'kind':kind,'reference':reference,'session':session,'prewarm':prewarm,
'clients':{},'browser_seen':False,'close_after':None,'claim_deadline':self.clock()+self.BROWSER_TIMEOUT}
self.units[session.id]=unit
if not prewarm:self.selected[actor.user_id]=session.id
if fast_page:
self._persist(unit)
return self._state(unit)
def execute():
try:session.start()
finally:self._persist(unit)
self._persist(unit)
thread=threading.Thread(target=execute,daemon=True,name='agent-'+session.id);self.threads.append(thread);thread.start()
return self._state(unit)
def _persist(self, unit):
with self.lock:
folder=Path(self.engine.root)/'agent-sandboxes';folder.mkdir(exist_ok=True)
state=self._state(unit);target=folder/(state['id']+'.json');temporary=target.with_suffix('.tmp')
temporary.write_text(json.dumps({**state,'owner':unit['owner']},ensure_ascii=False,indent=2),encoding='utf-8');temporary.replace(target)
def request(self, actor, preview_id, method, path, token, body=None):
with self.lock:unit=self._authorized(actor,preview_id)
return unit['session'].request(method,path,token,**({'body':body} if body is not None else {}))
def close(self, actor, preview_id=None):
with self.lock:unit=self._authorized(actor,preview_id)
unit['session'].close();self._persist(unit)
def list(self, actor):
result=[]
with self.lock:
self._reap_locked()
for key,unit in self.units.items():
if unit['owner']!=actor.user_id or unit.get('prewarm'):continue
try:result.append(self._state(self._authorized(actor,key)))
except SkillError:continue
return {'capacity':self.capacity,'active_total':sum(u['session'].status in {'starting','ready'} for u in self.units.values()),'items':result}
def shutdown(self):
self.stopping.set()
if self.reaper is not threading.current_thread():self.reaper.join(timeout=3)
with self.lock:units=list(self.units.values())
for unit in units:
unit['session'].close();self._persist(unit)
for thread in self.threads:
if thread is not threading.current_thread():thread.join(timeout=2)