gateway.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import {randomUUID} from 'node:crypto'
  2. import {join,dirname,posix} from 'node:path'
  3. import {fileURLToPath} from 'node:url'
  4. import {mkdir,rm} from 'node:fs/promises'
  5. import {existsSync} from 'node:fs'
  6. import type {DatabaseSync} from 'node:sqlite'
  7. import {z} from 'zod'
  8. import {HttpError} from '../../server/errors.js'
  9. import type {GatewayFrame,GatewayTarget} from '../../server/workspaceGateway.js'
  10. import {ProfileComputerSession} from './profileSession.js'
  11. import {UNCONFIGURED_COMPUTER_IMAGE} from '../../shared/runner.js'
  12. import type {RunnerConfiguration} from '../../shared/runner.js'
  13. import {ContainerComputerProvider,COMPUTER_WORKSPACE,CUA_DRIVER,CUA_SOCKET,type ComputerSpecification} from '../computers/container.js'
  14. import {ComputerPool,type ComputerLease} from '../computers/pool.js'
  15. import {ComposeComputerProvider} from '../computers/compose.js'
  16. import {COMPOSE_DESKTOP_IMAGE,type DesktopRelay} from '../../shared/composeDesktops.js'
  17. import {ComputerControls} from './control.js'
  18. import {ComputerPublicProxy} from '../network/computerProxy.js'
  19. import {HermesWorkerProcess,type WorkerModel,type WorkerProxyEnvironment,type WorkerContextConfiguration,type WorkerTool,type WorkerFrame} from './process.js'
  20. import {HOST_TOOLS,hostTool,hostPath,readHostFile,writeHostFile} from './hostTools.js'
  21. import {homedir,platform} from 'node:os'
  22. export interface ComputerTarget {environmentId:string;ownerKey:string;agentId:string;hostAccess?:boolean;profileSession?:boolean}
  23. export interface WorkerSession {agentId?:string;id:string;profile:string;ownerKey:string;environmentId:string;cwd:string;configuredCwd:string;history:any[];outcome?:'complete'|'failed'|'uncertain';vmExecution?:'profile';profileSessionId?:string}
  24. interface Live {workMarker?:string;paused?:boolean;pauseJob?:Promise<ComputerLease>;segment?:number;toolCalls:Set<Promise<unknown>>;journal:Map<string,{name:string;result:unknown}>;proxy?:ComputerPublicProxy;session:WorkerSession;model:WorkerModel;contextConfig?:WorkerContextConfiguration;proxyEnv?:WorkerProxyEnvironment;lease:ComputerLease;controller:AbortController;worker?:HermesWorkerProcess;finishing?:Promise<void>;stopping?:Promise<void>;releasing?:Promise<void>;images:any[];running:boolean;received:boolean}
  25. const object=(properties:Record<string,unknown>,required:string[])=>({type:'object',properties,required,additionalProperties:false})
  26. const text={type:'string'}
  27. const TOOLS:WorkerTool[]=[
  28. {name:'computer_export',description:'将隔离电脑中的文件作为可下载附件回传当前会话,最大 25 MiB。',inputSchema:object({path:text,name:text},['path'])},
  29. {name:'computer_shell',description:'在当前隔离电脑和 Profile 工作目录执行 shell 命令。',inputSchema:object({command:text},['command'])},
  30. {name:'computer_read_file',description:'读取隔离电脑内的 UTF-8 文本文件。',inputSchema:object({path:text},['path'])},
  31. {name:'computer_write_file',description:'向隔离电脑写入 UTF-8 文本文件。',inputSchema:object({path:text,content:text},['path','content'])},
  32. {name:'computer_desktop_state',description:'查看隔离电脑当前桌面,返回真实截图。',inputSchema:object({},[])},
  33. {name:'computer_action',description:'在隔离电脑内调用 CUA 动作;先查看桌面并使用可用动作。',inputSchema:object({name:text,arguments:{type:'object'}},['name','arguments'])},
  34. ]
  35. const pathField=z.string().min(1).max(4096).refine(value=>!value.includes('\0'))
  36. const PROFILE_COMPUTER_RULES='当前使用本机协作模式:沿用基础 Profile 的本机工具、配置和上下文,本地虚拟机是独立的 Linux 电脑。computer_shell/read_file/write_file/desktop_state/action/export 只操作虚拟机;本机文件、终端和程序使用 Profile 已授权的原生工具。computer_copy_file 在两个环境间显式复制文件。调用前明确目标环境,文件路径和浏览器登录互不通用;需要回传虚拟机文件时使用 computer_export。人工接管期间停止操作,交还后先检查当前状态。'
  37. export class ComputerRuntime {
  38. retainDesktops=false
  39. readonly controls:ComputerControls
  40. readonly provider:ContainerComputerProvider
  41. readonly pool:ComputerPool
  42. readonly ready:Promise<void>
  43. readonly config:NonNullable<RunnerConfiguration['computers']>
  44. readonly gateways=new Map<string,ComputerGateway>()
  45. readonly workers=new Map<string,{environmentId:string;ownerKey:string;process:HermesWorkerProcess}>()
  46. readonly script:string
  47. readonly proxyScript:string
  48. constructor(readonly db:DatabaseSync,config:RunnerConfiguration,readonly home:string,script?:string,relay?:DesktopRelay){
  49. if(!config.computers)throw new HttpError(409,'执行节点尚未配置隔离电脑','computer_unavailable')
  50. this.config=config.computers
  51. this.script=script??join(dirname(fileURLToPath(import.meta.url)),'hermes_worker.py')
  52. this.proxyScript=existsSync(join(dirname(this.script),'guest_proxy.py'))?join(dirname(this.script),'guest_proxy.py'):join(dirname(this.script),'../network/guest_proxy.py')
  53. if(this.config.managedBy==='compose'){
  54. if(!relay)throw new HttpError(409,'缺少 Compose 桌面连接','compose_desktop_unavailable')
  55. this.config.imageId=COMPOSE_DESKTOP_IMAGE;this.config.network='none'
  56. this.provider=new ComposeComputerProvider(config.runnerId,home,relay)
  57. }else this.provider=new ContainerComputerProvider(this.config.runtime,config.runnerId,home)
  58. this.pool=new ComputerPool(db,this.provider,{concurrent:this.config.maxConcurrent??2,environments:32,ttlMs:30000})
  59. db.exec('CREATE TABLE IF NOT EXISTS retired_computers(id TEXT PRIMARY KEY,owner_key TEXT NOT NULL,spec TEXT)')
  60. db.exec('CREATE TABLE IF NOT EXISTS computer_sessions(id TEXT PRIMARY KEY,value TEXT NOT NULL)')
  61. db.exec('CREATE TABLE IF NOT EXISTS computer_image_bindings(id TEXT PRIMARY KEY,owner_key TEXT NOT NULL,image_id TEXT NOT NULL)')
  62. this.controls=new ComputerControls(this)
  63. this.ready=this.pool.recover();void this.ready.catch(()=>{})
  64. }
  65. assertTarget(meta:ComputerTarget){if(this.db.prepare('SELECT id FROM retired_computers WHERE id=?').get(meta.environmentId))throw new HttpError(410,'临时电脑已退役','computer_retired')}
  66. imageFor(meta:ComputerTarget):string {
  67. const spec=this.pool.definition(meta.ownerKey,meta.environmentId)
  68. const binding=this.db.prepare('SELECT owner_key,image_id FROM computer_image_bindings WHERE id=?').get(meta.environmentId) as {owner_key:string;image_id:string}|undefined
  69. if(binding&&binding.owner_key!==meta.ownerKey)throw new HttpError(403,'电脑归属不匹配','computer_owner_mismatch')
  70. return spec?.imageId??binding?.image_id??this.config.imageId
  71. }
  72. async retire(meta:ComputerTarget){
  73. const old=this.db.prepare('SELECT owner_key,spec FROM retired_computers WHERE id=?').get(meta.environmentId) as {owner_key:string;spec?:string}|undefined
  74. if(old&&old.owner_key!==meta.ownerKey)throw new HttpError(403,'电脑归属不匹配','computer_owner_mismatch')
  75. this.pool.definition(meta.ownerKey,meta.environmentId)
  76. this.db.prepare('INSERT OR IGNORE INTO retired_computers VALUES(?,?,NULL)').run(meta.environmentId,meta.ownerKey)
  77. await Promise.all([...this.workers.values()].filter(worker=>worker.environmentId===meta.environmentId&&worker.ownerKey===meta.ownerKey).map(worker=>worker.process.close()))
  78. const current=this.pool.status(meta.ownerKey).find(row=>row.environmentId===meta.environmentId)
  79. if(current?.holderId)await this.pool.stopHolder(meta.ownerKey,meta.environmentId,current.holderId)
  80. let spec=old?.spec?JSON.parse(old.spec):undefined
  81. spec??=this.pool.definition(meta.ownerKey,meta.environmentId)
  82. if(spec)this.db.prepare('UPDATE retired_computers SET spec=? WHERE id=?').run(JSON.stringify(spec),meta.environmentId)
  83. await this.pool.retire(meta.ownerKey,meta.environmentId)
  84. if(spec)await this.provider.deleteWorkspace(spec)
  85. const sessions=(this.db.prepare('SELECT id,value FROM computer_sessions').all() as {id:string;value:string}[]).filter(row=>{const session=JSON.parse(row.value);return session.environmentId===meta.environmentId&&session.ownerKey===meta.ownerKey})
  86. for(const row of sessions){if(!/^[0-9a-f-]{36}$/.test(row.id))throw new Error('电脑会话编号无效');await rm(join(this.home,'workers',row.id),{recursive:true,force:true});this.db.prepare('DELETE FROM computer_sessions WHERE id=?').run(row.id)}
  87. this.db.prepare('UPDATE retired_computers SET spec=NULL WHERE id=?').run(meta.environmentId)
  88. }
  89. save(session:WorkerSession){this.db.prepare('INSERT INTO computer_sessions VALUES(?,?) ON CONFLICT(id) DO UPDATE SET value=excluded.value').run(session.id,JSON.stringify(session))}
  90. session(id:string,meta:ComputerTarget,profile:string):WorkerSession {
  91. const row=this.db.prepare('SELECT value FROM computer_sessions WHERE id=?').get(id) as {value:string}|undefined
  92. const session:WorkerSession|undefined=row?JSON.parse(row.value):undefined
  93. if(!session||(session.agentId??session.environmentId)!==meta.agentId||session.ownerKey!==meta.ownerKey||session.environmentId!==meta.environmentId||session.profile!==profile)throw new HttpError(404,'电脑会话不存在或不属于当前任务','computer_session_missing')
  94. if((session.vmExecution==='profile')!==(meta.profileSession===true))throw new HttpError(409,'虚拟机执行方式已改变,请使用新会话','computer_session_mode_changed')
  95. return session
  96. }
  97. async resolve(profile:string,signal?:AbortSignal){
  98. return this.resolveProfile(profile,'resolve',signal)
  99. }
  100. async resolveWorkspace(profile:string,signal?:AbortSignal){
  101. return this.resolveProfile(profile,'resolve-workspace',signal)
  102. }
  103. private async resolveProfile(profile:string,mode:'resolve'|'resolve-workspace',signal?:AbortSignal){
  104. const resolver=new HermesWorkerProcess(this.config.python,this.script,{mode,profile,defaultCwd:COMPUTER_WORKSPACE,hermesSource:this.config.hermesSource,hermesHome:this.config.hermesHome})
  105. const abort=()=>{void resolver.close()};signal?.addEventListener('abort',abort,{once:true});if(signal?.aborted)abort()
  106. try{const result=await resolver.wait('resolved');return this.provider.fixedCapacity?{...result,cwd:COMPUTER_WORKSPACE}:result}finally{signal?.removeEventListener('abort',abort);await resolver.close()}
  107. }
  108. async desktop(meta:ComputerTarget,profile:string,action:'create'|'start'|'stop'|'recreate'|'remove',authorize:()=>void){
  109. if(this.provider.fixedCapacity)throw new HttpError(409,'桌面由 Compose 创建和管理,不能在界面增删或重建','compose_desktop_managed')
  110. this.assertTarget(meta);authorize()
  111. // Stopping/removing an existing desktop must remain possible even when
  112. // its Profile or model was removed or is temporarily misconfigured.
  113. if(action==='stop'||action==='remove'){
  114. const spec=this.pool.definition(meta.ownerKey,meta.environmentId)
  115. if(spec)await this.pool.desktop(spec,action,authorize)
  116. return
  117. }
  118. const resolved=await this.resolveWorkspace(profile);authorize()
  119. await this.pool.desktop({id:meta.environmentId,ownerKey:meta.ownerKey,imageId:this.imageFor(meta),cwd:meta.environmentId!==meta.agentId?(this.pool.definition(meta.ownerKey,meta.environmentId)?.cwd??COMPUTER_WORKSPACE):resolved.cwd,network:this.config.network??'none'},action,authorize)
  120. }
  121. }
  122. export class ComputerGateway {
  123. onEvent:(frame:GatewayFrame)=>void=()=>{}
  124. onDisconnect:()=>void=()=>{}
  125. private live?:Live
  126. private recoverySession?:WorkerSession
  127. private closed=false
  128. private controller=new AbortController()
  129. private timer?:ReturnType<typeof setInterval>
  130. private checking=false
  131. private hostCwd=homedir()
  132. private profileSession?:ProfileComputerSession
  133. private team?:{id:string;catalog:WorkerTool[];call(name:string,args:Record<string,unknown>,callId:string):Promise<unknown>}
  134. constructor(readonly runtime:ComputerRuntime,readonly meta:ComputerTarget,readonly workId:string,readonly check:()=>Promise<void>,readonly publish:(body:Record<string,unknown>)=>Promise<any>,readonly profileTarget?:GatewayTarget){ }
  135. async connect(){this.runtime.assertTarget(this.meta);await this.runtime.ready;await this.authorized()}
  136. private async authorized(){try{await this.check();this.guard()}catch(error){const stopping=this.interrupt().catch(()=>{});if(!this.profileSession)await stopping;if(!this.closed)this.onDisconnect();throw error}}
  137. private guard(){if(this.closed||this.live?.controller.signal.aborted)throw new HttpError(410,'电脑任务授权已结束','computer_cancelled')}
  138. private event(type:string,payload:Record<string,unknown>){if(!this.closed&&this.live)this.onEvent({type,session_id:this.live.session.id,payload})}
  139. private spec(session:WorkerSession):ComputerSpecification{return {id:this.meta.environmentId,ownerKey:this.meta.ownerKey,imageId:this.runtime.imageFor(this.meta),cwd:session.cwd,network:this.runtime.config.network??'none'}}
  140. async rpc(method:string,params:Record<string,any>):Promise<any>{
  141. if((method==='session.interrupt'||method==='session.close')&&params.session_id===this.live?.session.id){await this.interrupt();return {status:'interrupted'}}
  142. if((method==='session.interrupt'||method==='session.close')&&params.session_id===this.recoverySession?.id){await this.runtime.pool.stopHolder(this.meta.ownerKey,this.meta.environmentId,this.workId);return {status:'interrupted'}}
  143. this.guard()
  144. if(method==='session.create'||method==='session.resume'){
  145. if(this.live)throw new HttpError(409,'电脑通道已有会话','computer_session_busy')
  146. await this.authorized()
  147. if(method==='session.resume'&&params.recoverOnly===true){const session=this.runtime.session(String(params.session_id),this.meta,String(params.profile));this.recoverySession=session;if(this.meta.profileSession){await this.openProfile(session,params);await this.profileSession!.stop()}const resource=this.runtime.pool.status(this.meta.ownerKey).find(item=>item.environmentId===this.meta.environmentId);if(resource?.holderId===this.workId)await this.runtime.pool.stopHolder(this.meta.ownerKey,this.meta.environmentId,this.workId);return {session_id:session.id,stored_session_id:session.id,running:false,info:{profile_name:session.profile}}}
  148. if(this.runtime.imageFor(this.meta)===UNCONFIGURED_COMPUTER_IMAGE)throw new HttpError(409,'请先在应用设置的本地虚拟机页面完成准备','computer_image_required')
  149. const profile=String(params.profile),resolved=await (this.meta.profileSession?this.runtime.resolveWorkspace(profile,this.controller.signal):this.runtime.resolve(profile,this.controller.signal))
  150. if(this.meta.hostAccess){const configured=String(resolved.configuredCwd??'.');this.hostCwd=['.','auto','cwd'].includes(configured)?homedir():hostPath(homedir(),configured)}
  151. await this.authorized();this.guard()
  152. const session:WorkerSession=method==='session.resume'?this.runtime.session(String(params.session_id),this.meta,profile):{id:randomUUID(),agentId:this.meta.agentId,ownerKey:this.meta.ownerKey,environmentId:this.meta.environmentId,profile,cwd:resolved.cwd,configuredCwd:resolved.configuredCwd,history:[]}
  153. if(this.meta.profileSession)session.vmExecution='profile'
  154. session.cwd=this.meta.environmentId!==this.meta.agentId?(this.runtime.pool.definition(this.meta.ownerKey,this.meta.environmentId)?.cwd??COMPUTER_WORKSPACE):resolved.cwd;session.configuredCwd=resolved.configuredCwd
  155. await this.runtime.pool.configure(this.spec(session),()=>this.guard())
  156. await this.authorized()
  157. const controller=new AbortController(),lease=await this.runtime.pool.acquire(this.spec(session),this.workId,()=>{this.guard();if(controller.signal.aborted)throw new Error('cancelled')},controller.signal)
  158. if(this.closed){controller.abort();await this.runtime.pool.release(lease);throw new Error('电脑通道已关闭')}
  159. this.live={session,lease,controller,model:resolved.model as WorkerModel,contextConfig:resolved.contextConfig,proxyEnv:resolved.proxyEnv,images:[],running:false,received:false,toolCalls:new Set(),journal:new Map()}
  160. this.runtime.save(session);this.runtime.gateways.set(this.meta.environmentId,this)
  161. if(this.runtime.config.network==='public-proxy'){
  162. const live=this.live
  163. try{live.proxy=await ComputerPublicProxy.start(this.runtime.provider,this.spec(session),this.runtime.proxyScript,()=>this.runtime.pool.authorize(live.lease),()=>this.authorized(),()=>{void this.interrupt().finally(()=>{if(!this.closed)this.onDisconnect()}).catch(()=>{})})}
  164. catch(error){await this.interrupt();throw error}
  165. }
  166. this.timer=setInterval(()=>{if(this.checking)return;this.checking=true;void this.authorized().then(()=>this.runtime.pool.renew(this.live!.lease)).catch(async()=>{await this.interrupt().catch(()=>{});if(!this.closed)this.onDisconnect()}).finally(()=>{this.checking=false})},5000);this.timer.unref()
  167. if(this.meta.profileSession){
  168. try{const opened=await this.openProfile(session,params);return {...opened,session_id:session.id,stored_session_id:session.id}}
  169. catch(error){await this.interrupt();throw error}
  170. }
  171. return {session_id:session.id,stored_session_id:session.id,running:false,info:{profile_name:profile}}
  172. }
  173. const live=this.live
  174. if(!live||params.session_id!==live.session.id)throw new HttpError(403,'电脑会话不属于当前通道','computer_session_forbidden')
  175. if(method==='session.interrupt'||method==='session.close'){await this.interrupt();return {status:'interrupted'}}
  176. if(this.profileSession){
  177. if(method==='session.usage')return this.profileSession.rpc(method,params)
  178. if(live.paused)throw new HttpError(409,'电脑正在等待人工操作','computer_paused')
  179. await this.authorized()
  180. if(method==='prompt.submit'){
  181. if(live.running||live.received)throw new HttpError(409,'电脑会话已经提交过本轮','computer_session_busy')
  182. if(typeof params.workMarker==='string'&&/^\[yaoyao-run:[0-9a-f-]{36}:[0-9a-f-]{36}\]$/.test(params.workMarker))live.workMarker=params.workMarker
  183. await this.profileSession.bind();this.guard()
  184. live.running=true;live.session.outcome='uncertain';this.runtime.save(live.session)
  185. return this.profileSession.rpc(method,{...params,text:`${PROFILE_COMPUTER_RULES}\n${String(params.text??'')}`})
  186. }
  187. return this.profileSession.rpc(method,params)
  188. }
  189. if(method==='session.usage')return {}
  190. if(method==='session.cwd.set'){
  191. if(params.cwd!==live.session.cwd&&params.cwd!==live.session.configuredCwd)throw new HttpError(403,'工作目录必须采用基础 Profile 的配置','computer_cwd_forbidden')
  192. return {cwd:live.session.cwd}
  193. }
  194. if(method==='file.attach'||method==='image.attach_bytes'){
  195. if(live.running)throw new HttpError(409,'当前轮次已开始,不能追加附件','computer_session_busy')
  196. await this.authorized()
  197. const name=String(params.name??params.filename??'attachment').replace(/[\/\\\u0000-\u001f]/g,'_').slice(0,200)||'attachment'
  198. const encoded=method==='image.attach_bytes'?String(params.content_base64??''):String(params.data_url??'').split(',')[1]??''
  199. const bytes=Buffer.from(encoded,'base64');if(bytes.length>25*1024*1024)throw new HttpError(413,'附件超过 25 MiB','attachment_too_large')
  200. const relative=`.yaoyao-inputs/${randomUUID()}/${name}`
  201. await this.runtime.pool.use(live.lease,context=>this.runtime.provider.execute(this.spec(live.session),['python3','-c','import sys,pathlib; p=pathlib.Path(sys.argv[1]); p.parent.mkdir(parents=True,exist_ok=True); p.write_bytes(sys.stdin.buffer.read())',relative],{...context,input:bytes}))
  202. if(method==='image.attach_bytes'){
  203. const mime=String(params.mime_type??'image/png')
  204. if(!/^image\/(?:png|jpeg|webp|gif)$/.test(mime))throw new HttpError(400,'图片格式无效','invalid_image')
  205. if(JSON.stringify(live.images).length+encoded.length>64*1024*1024)throw new HttpError(413,'本轮图片总量超过限制','image_limit')
  206. live.images.push({type:'image_url',image_url:{url:`data:${mime};base64,${encoded}`}})
  207. }
  208. return {ref_text:`[附件 ${name}](${live.session.cwd}/${relative})`}
  209. }
  210. if(method==='prompt.submit'){
  211. if(live.running||live.received)throw new HttpError(409,'电脑会话已经提交过本轮','computer_session_busy')
  212. await this.authorized();this.guard()
  213. if(typeof params.workMarker==='string'&&/^\[yaoyao-run:[0-9a-f-]{36}:[0-9a-f-]{36}\]$/.test(params.workMarker))live.workMarker=params.workMarker
  214. await this.startModel(live,String(params.text??''),structuredClone(live.session.history))
  215. return {status:'streaming'}
  216. }
  217. throw new HttpError(409,'当前隔离 Worker 不支持此交互','computer_method_unavailable')
  218. }
  219. private async openProfile(session:WorkerSession,params:Record<string,unknown>){
  220. if(!this.profileTarget)throw new HttpError(409,'缺少本机 Profile 连接,请更新执行节点','computer_profile_unavailable')
  221. if(params.session_id&&!session.profileSessionId)throw new HttpError(409,'本机 Profile 会话尚未建立,请新建会话','computer_profile_session_invalid')
  222. const native=new ProfileComputerSession(this.profileTarget,session.profile,this.workId,()=>this.guard(),
  223. ()=>[...TOOLS,...HOST_TOOLS.filter(tool=>tool.name==='computer_copy_file'),...(this.team?.catalog??[])],
  224. async(name,args)=>{
  225. const live=this.live
  226. if(!live||!this.active||live.paused)throw new HttpError(410,'本轮电脑工具已结束或暂停','computer_cancelled')
  227. const call=this.tool(live,name,args,randomUUID())
  228. live.toolCalls.add(call);void call.finally(()=>live.toolCalls.delete(call)).catch(()=>{})
  229. return call
  230. })
  231. this.profileSession=native
  232. native.onStoredId=id=>{session.profileSessionId=id;this.runtime.save(session)}
  233. native.onDisconnect=()=>{void this.interrupt().finally(()=>{if(!this.closed)this.onDisconnect()}).catch(()=>{})}
  234. native.onEvent=frame=>{
  235. const live=this.live
  236. if(!live||this.closed||live.controller.signal.aborted||live.paused||live.received)return
  237. if(['message.complete','run.completed','run.failed','message.error','error'].includes(frame.type)){
  238. live.received=true
  239. live.finishing=this.finishProfile(live,frame)
  240. void live.finishing.catch(()=>this.lost(live))
  241. }else this.event(frame.type,frame.type==='session.info'?{...frame.payload,stored_session_id:session.id,session_key:session.id}:frame.payload??{})
  242. }
  243. return native.open(session.profileSessionId,params)
  244. }
  245. private async finishProfile(live:Live,frame:GatewayFrame){
  246. await Promise.allSettled([...live.toolCalls]);await this.authorized()
  247. const payload=frame.payload??{},success=['message.complete','run.completed'].includes(frame.type)&&!payload.error&&!['interrupted','failed','error'].includes(String(payload.status))
  248. live.session.outcome=success?'complete':'failed';this.runtime.save(live.session)
  249. await this.release(live,this.runtime.retainDesktops&&success);live.running=false
  250. if(this.closed||live.controller.signal.aborted)return
  251. this.event(frame.type,{...payload,...(payload.status==='error'?{status:'failed'}:{})})
  252. }
  253. private async startModel(live:Live,prompt:string,history:any[]){
  254. live.received=false;live.running=true;live.session.outcome='uncertain';live.session.history.push({role:'user',content:prompt});this.runtime.save(live.session)
  255. const directory=join(this.runtime.home,'workers',live.session.id,this.workId,String(live.segment=(live.segment??0)+1))
  256. await mkdir(directory,{recursive:true,mode:0o700})
  257. const worker=new HermesWorkerProcess(this.runtime.config.python,this.runtime.script,{mode:'run',home:directory,hermesSource:this.runtime.config.hermesSource,model:live.model,contextConfig:live.contextConfig,proxyEnv:live.proxyEnv,sessionId:live.session.id,taskId:this.workId,cwd:live.session.cwd,...(this.meta.hostAccess?{host:{cwd:this.hostCwd,platform:platform()}}:{}),network:this.runtime.config.network??'none',tools:[...TOOLS,...(this.meta.hostAccess?HOST_TOOLS:[]),...(this.team?.catalog??[])],prompt:live.images.length?[{type:'text',text:prompt},...live.images]:prompt,history})
  258. live.worker=worker
  259. this.runtime.workers.set(this.workId,{environmentId:this.meta.environmentId,ownerKey:this.meta.ownerKey,process:worker});void worker.exited.then(()=>{if(this.runtime.workers.get(this.workId)?.process===worker)this.runtime.workers.delete(this.workId)})
  260. worker.onTool=(name,args,id,callId)=>{
  261. if(live.worker!==worker||live.received)throw new HttpError(410,'本轮 Worker 已结束','computer_worker_finished')
  262. const task=this.tool(live,name,args,id).then(result=>{if(callId)live.journal.set(callId,{name,result});return result},error=>{if(callId)live.journal.set(callId,{name,result:{error:'操作未完成或已中断'}});throw error})
  263. live.toolCalls.add(task);void task.finally(()=>live.toolCalls.delete(task)).catch(()=>{});return task
  264. }
  265. worker.onEvent=frame=>{
  266. if(this.closed||live.worker!==worker||live.received||live.controller.signal.aborted)return
  267. if(frame.type==='checkpoint'&&Array.isArray(frame.messages)){live.session.history=frame.messages;this.runtime.save(live.session);return}
  268. if(live.paused)return
  269. if(frame.type==='delta')this.event('message.delta',{text:frame.text})
  270. if(frame.type==='reasoning')this.event('reasoning.delta',{text:frame.text})
  271. if(frame.type==='complete'){live.received=true;live.finishing=this.finish(live,frame);void live.finishing.catch(()=>this.lost(live))}
  272. if(frame.type==='failed')void this.lost(live)
  273. }
  274. void worker.exited.then(()=>{if(!live.paused&&!live.received&&live.running&&!this.closed)void this.lost(live)})
  275. }
  276. installTeamLease(id:string,catalog:WorkerTool[],call:(name:string,args:Record<string,unknown>,callId:string)=>Promise<unknown>){this.team={id,catalog,call}}
  277. removeTeamLease(id:string){if(this.team?.id===id)this.team=undefined}
  278. private async tool(live:Live,name:string,args:unknown,id:string):Promise<unknown>{
  279. if(live.paused)throw new HttpError(409,'电脑正在等待人工操作','computer_paused')
  280. await this.authorized();this.guard()
  281. if(live.paused)throw new HttpError(409,'电脑正在等待人工操作','computer_paused')
  282. this.event('tool.started',{tool_id:id,name})
  283. try{
  284. const team=this.team?.catalog.find(tool=>tool.name===name)
  285. if(team)return await this.team!.call(team.id??name,z.record(z.string(),z.unknown()).parse(args),id)
  286. return await this.runtime.pool.use(live.lease,async context=>{
  287. const execute=(argv:string[],input?:Buffer)=>this.runtime.provider.execute(this.spec(live.session),argv,{...context,input})
  288. if(this.meta.hostAccess&&name.startsWith('host_'))return hostTool(name,args,{...context,cwd:this.hostCwd})
  289. if(this.meta.hostAccess&&name==='computer_copy_file'){
  290. const body=z.object({from:z.enum(['host','vm']),source:pathField,destination:pathField}).strict().parse(args),host={...context,cwd:this.hostCwd}
  291. if(body.from==='host'){
  292. const bytes=await readHostFile(hostPath(this.hostCwd,body.source),25*1024*1024,host)
  293. await execute(['python3','-c','import pathlib,sys; p=pathlib.Path(sys.argv[1]); p.parent.mkdir(parents=True,exist_ok=True); p.write_bytes(sys.stdin.buffer.read())',body.destination],bytes)
  294. }else{
  295. const snapshot=`/tmp/yaoyao-copy-${randomUUID()}`,chunks:Buffer[]=[]
  296. try{
  297. const size=Number((await execute(['python3','-c','import pathlib,sys,shutil; p=pathlib.Path(sys.argv[1]); assert p.is_file() and p.stat().st_size<=25*1024*1024; shutil.copyfile(p,sys.argv[2]); n=pathlib.Path(sys.argv[2]).stat().st_size; assert n<=25*1024*1024; print(n)',body.source,snapshot])).stdout.trim())
  298. if(!Number.isSafeInteger(size)||size<0||size>25*1024*1024)throw new Error('文件大小无效')
  299. for(let offset=0;offset<size;offset+=524288){
  300. const data=(await execute(['python3','-c','import sys,base64; f=open(sys.argv[1],"rb"); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(524288)).decode())',snapshot,String(offset)])).stdout.trim()
  301. chunks.push(Buffer.from(data,'base64'))
  302. }
  303. const bytes=Buffer.concat(chunks);if(bytes.length!==size)throw new Error('文件复制不完整')
  304. await writeHostFile(hostPath(this.hostCwd,body.destination),bytes,host)
  305. }finally{await execute(['rm','-f','--',snapshot]).catch(()=>{})}
  306. }
  307. return {ok:true}
  308. }
  309. if(name==='computer_export'){
  310. const body=z.object({path:pathField,name:z.string().min(1).max(240).optional()}).strict().parse(args)
  311. const snapshot=`/tmp/yaoyao-export-${randomUUID()}`
  312. try{
  313. const metadata=JSON.parse((await execute(['python3','-c','import pathlib,sys,shutil,json,hashlib; p=pathlib.Path(sys.argv[1]); assert p.is_file(),"not a file"; assert p.stat().st_size<=25*1024*1024,"file too large"; shutil.copyfile(p,sys.argv[2]); b=pathlib.Path(sys.argv[2]).read_bytes(); assert len(b)<=25*1024*1024,"file too large"; print(json.dumps({"size":len(b),"digest":hashlib.sha256(b).hexdigest()}))',body.path,snapshot])).stdout)
  314. await this.publish({phase:'begin',id,name:body.name??posix.basename(body.path),size:metadata.size,digest:metadata.digest})
  315. for(let offset=0,index=0;offset<metadata.size;offset+=524288,index++){
  316. context.authorize();await this.authorized()
  317. const data=(await execute(['python3','-c','import sys,base64; f=open(sys.argv[1],"rb"); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(524288)).decode())',snapshot,String(offset)])).stdout.trim()
  318. await this.publish({phase:'append',id,index,data})
  319. }
  320. context.authorize();await this.authorized()
  321. return (await this.publish({phase:'finish',id})).result
  322. }finally{await execute(['rm','-f','--',snapshot]).catch(()=>{})}
  323. }
  324. if(name==='computer_shell'){
  325. const body=z.object({command:z.string().min(1).max(65536)}).strict().parse(args)
  326. try{return {exitCode:0,...await execute(['/bin/bash','-lc',body.command])}}catch(error){if(typeof(error as any).code==='number')return {exitCode:(error as any).code,stdout:String((error as any).stdout??''),stderr:String((error as any).stderr??'')};throw error}
  327. }
  328. if(name==='computer_read_file'){
  329. const body=z.object({path:pathField}).strict().parse(args)
  330. return execute(['python3','-c','import sys; f=open(sys.argv[1],encoding="utf-8"); s=f.read(1000001); assert len(s)<=1000000,"file too large"; print(s,end="")',body.path])
  331. }
  332. if(name==='computer_write_file'){
  333. const body=z.object({path:pathField,content:z.string().max(1000000)}).strict().parse(args)
  334. await execute(['python3','-c','import pathlib,sys; p=pathlib.Path(sys.argv[1]); p.parent.mkdir(parents=True,exist_ok=True); p.write_bytes(sys.stdin.buffer.read())',body.path],Buffer.from(body.content));return {ok:true}
  335. }
  336. if(name==='computer_action'){
  337. const body=z.object({name:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,99}$/),arguments:z.record(z.string(),z.unknown())}).strict().parse(args)
  338. return execute([CUA_DRIVER,'call',body.name,JSON.stringify(body.arguments),'--socket',CUA_SOCKET])
  339. }
  340. if(name==='computer_desktop_state'){
  341. z.object({}).strict().parse(args)
  342. const path=`/tmp/yaoyao-frame-${randomUUID()}.png`
  343. const state=await execute([CUA_DRIVER,'call','get_desktop_state','{}','--socket',CUA_SOCKET,'--screenshot-out-file',path])
  344. const data=(await execute(['base64','-w0',path])).stdout.trim()
  345. return {_multimodal:true,text_summary:state.stdout,content:[{type:'image_url',image_url:{url:`data:image/png;base64,${data}`}}]}
  346. }
  347. throw new HttpError(403,'本轮未授权该工具','computer_tool_forbidden')
  348. })
  349. }finally{this.event('tool.completed',{tool_id:id,name})}
  350. }
  351. private async finish(live:Live,frame:WorkerFrame){
  352. if(this.closed||live.paused||live.controller.signal.aborted)return
  353. await this.authorized()
  354. this.runtime.pool.renew(live.lease)
  355. const contextErrors:Record<string,string>={
  356. context_compaction_disabled:'模型上下文已超限,基础 Profile 关闭了自动压缩。请开启压缩、缩短输入或新建对话后继续。',
  357. context_compaction_failed:'模型上下文压缩未能完成,本轮已结束。请缩短输入、检查模型配置或新建对话后继续。',
  358. }
  359. const contextError=frame.completed===false&&!frame.interrupted&&Object.hasOwn(contextErrors,String(frame.failureCode))
  360. ?contextErrors[String(frame.failureCode)]:undefined
  361. const success=frame.completed!==false&&!frame.interrupted
  362. // Failed model turns can carry a newly compacted, authoritative history too.
  363. // A missing history leaves the last durable checkpoint intact.
  364. if(Array.isArray(frame.messages))live.session.history=frame.messages
  365. live.session.outcome=success?'complete':'failed'
  366. this.runtime.save(live.session)
  367. const keepRunning=this.runtime.retainDesktops&&(success||!!contextError)&&!live.toolCalls.size
  368. await live.worker?.close()
  369. await this.release(live,keepRunning)
  370. live.running=false
  371. if(this.closed||live.controller.signal.aborted)return
  372. const error=contextError?contextError+(keepRunning?' 虚拟机已进入空闲,后续按空闲停止设置处理。':''):'隔离 Worker 未完成本轮'
  373. this.event('message.complete',{text:contextError?error:String(frame.text??''),status:success?'complete':'failed',...(!success?{error,...(contextError?{code:frame.failureCode}:{})}:{})})
  374. }
  375. private release(live:Live,keepRunning=false){
  376. clearInterval(this.timer)
  377. live.releasing??=(async()=>{
  378. try{await live.proxy?.close();await this.runtime.pool.release(live.lease,keepRunning)}
  379. catch(error){await this.runtime.pool.release(live.lease).catch(()=>{});throw error}
  380. })()
  381. return live.releasing
  382. }
  383. private async lost(live:Live){
  384. if(!live.running||live.paused||this.closed||live.controller.signal.aborted)return
  385. live.running=false;await this.interrupt().catch(()=>{});if(!this.closed)this.onDisconnect()
  386. }
  387. get active(){return !!this.live?.running&&!this.live.received&&!this.closed}
  388. get paused(){return this.live?.paused===true}
  389. get lease(){return this.live?.lease}
  390. get specification(){return this.live?this.spec(this.live.session):undefined}
  391. async takeControl(controlId:string,authorize:()=>void):Promise<ComputerLease>{
  392. const live=this.live
  393. if(!live||!this.active)throw new HttpError(409,'机器人已不在执行,请重新打开电脑','computer_not_active')
  394. if(live.pauseJob)return live.pauseJob
  395. live.paused=true;this.event('computer.paused',{stage:'pausing'})
  396. live.pauseJob=(async()=>{
  397. await this.profileSession?.stop()
  398. await live.worker?.close()
  399. await Promise.allSettled([...live.toolCalls])
  400. authorize();this.guard()
  401. const history=structuredClone(live.session.history),done=new Set(history.filter(message=>message.role==='tool').map(message=>message.tool_call_id))
  402. for(const message of [...history])for(const tool of message.tool_calls??[])if(!done.has(tool.id)){
  403. const entry=live.journal.get(tool.id),value=entry?.result??{error:'用户接管时此操作未完成,继续前请检查电脑状态,不要盲目重复'}
  404. const content=typeof value==='string'?value:JSON.stringify(value)
  405. history.push({role:'tool',name:tool.function?.name??entry?.name,tool_call_id:tool.id,content});done.add(tool.id)
  406. }
  407. live.session.history=history;this.runtime.save(live.session)
  408. live.lease=await this.runtime.pool.transfer(live.lease,`human:${controlId}`,authorize)
  409. this.event('computer.paused',{stage:'human',generation:live.lease.generation})
  410. return live.lease
  411. })()
  412. return live.pauseJob
  413. }
  414. async giveBack(notes:string):Promise<void>{
  415. const live=this.live
  416. if(!live?.paused)throw new HttpError(409,'机器人没有处于接管状态','computer_not_paused')
  417. await live.pauseJob;await this.authorized()
  418. live.lease=await this.runtime.pool.transfer(live.lease,this.workId,()=>this.guard())
  419. live.paused=false;live.pauseJob=undefined;live.journal.clear()
  420. this.event('computer.resumed',{generation:live.lease.generation,notes})
  421. if(this.profileSession){
  422. await this.profileSession.bind();this.guard()
  423. await this.profileSession.rpc('prompt.submit',{text:`${PROFILE_COMPUTER_RULES}\n用户已交还电脑控制权。请先检查当前状态,避免重复已完成的操作。交还说明:${notes||'无额外说明'}\n${live.workMarker??''}`})
  424. return
  425. }
  426. await this.startModel(live,`用户已完成电脑接管并明确交还控制。请先检查当前电脑状态,再继续原任务;不要重复已完成的副作用。用户说明:${notes||'无额外说明'}\n${live.workMarker??''}`,structuredClone(live.session.history))
  427. }
  428. async interrupt(){
  429. const live=this.live;if(!live)return
  430. if(live.stopping)return live.stopping
  431. live.stopping=(async()=>{
  432. live.controller.abort();clearInterval(this.timer)
  433. try{await this.profileSession?.stop()}
  434. finally{
  435. await this.profileSession?.close();await live.worker?.close()
  436. try{await this.release(live)}catch(error){if((error as any).code!=='computer_lease_stale')throw error}
  437. live.running=false
  438. }
  439. })()
  440. return live.stopping
  441. }
  442. async stopControl(){await this.interrupt();this.event('message.complete',{text:'电脑控制已结束,本轮已停止',status:'interrupted'})}
  443. async close(){if(this.runtime.gateways.get(this.meta.environmentId)===this)this.runtime.gateways.delete(this.meta.environmentId);this.closed=true;this.controller.abort();this.team=undefined;clearInterval(this.timer);try{if(this.live?.running||this.live&&!this.live.releasing)await this.interrupt()}finally{await this.profileSession?.close()}}
  444. }