sharedComputers.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import Router from '@koa/router'
  2. import {randomUUID} from 'node:crypto'
  3. import {z} from 'zod'
  4. import type {WorkspaceAgent} from '../shared/workspace.js'
  5. import type {WorkspaceStore} from './workspaceStore.js'
  6. import {parse} from './workspaceStore.js'
  7. import {HttpError} from './errors.js'
  8. import type {WorkspaceNodes} from './workspaceGateway.js'
  9. import type {RunnerHub} from './runnerHub.js'
  10. import type {LocalAuthStore} from './localAuth.js'
  11. export interface SharedComputer {managedCompose?:boolean;managedLocalVm?:boolean;id:string;name:string;memberIds:string[];nodeId:string;profile:string;runnerId:string;archived:boolean;createdAt:number}
  12. export function requireSharedComputer(store:WorkspaceStore,owner:string,agent:{id?:string;nodeId:string;profile:string;computerEnvironmentId?:string}){
  13. if(!agent.computerEnvironmentId)return
  14. const shared=store.require<SharedComputer>(owner,'shared-computer',agent.computerEnvironmentId)
  15. if(shared.archived||!agent.id||!shared.memberIds.includes(agent.id)||shared.nodeId!==agent.nodeId||(!shared.managedCompose&&!shared.managedLocalVm&&shared.profile!=='*'&&shared.profile!==agent.profile))throw new HttpError(403,'当前成员没有这台共享电脑的授权','shared_computer_forbidden')
  16. }
  17. export class SharedComputers {
  18. constructor(readonly store:WorkspaceStore,readonly auth:LocalAuthStore,readonly nodes:WorkspaceNodes,readonly hub:RunnerHub){}
  19. private idle(owner:string,ids:string[],environmentId?:string){
  20. const busy=new Set(this.store.list<{agentId:string;status:string}>(owner,'turn').filter(work=>ids.includes(work.agentId)&&['queued','running','waiting','uncertain','cancelling'].includes(work.status)).map(work=>work.agentId))
  21. if(busy.size){
  22. const names=[...busy].slice(0,5).map(id=>`「${this.store.get<WorkspaceAgent>(owner,'agent',id)?.name??'未知成员'}」`).join('、')
  23. throw new HttpError(409,`请先停止${names}${busy.size>5?'等成员':''}的当前任务,再修改电脑共享`,'shared_computer_busy')
  24. }
  25. const environments=new Set(ids.map(id=>this.store.get<WorkspaceAgent>(owner,'agent',id)?.computerEnvironmentId??id))
  26. if(environmentId)environments.add(environmentId)
  27. if(this.store.list<{owner:string;agentId:string;environmentId?:string;expiresAt:number}>('_system','computer-control').some(grant=>grant.owner===owner&&grant.expiresAt>Date.now()&&(ids.includes(grant.agentId)||(grant.environmentId&&environments.has(grant.environmentId)))))throw new HttpError(409,'请先交还电脑控制权,再修改共享','shared_computer_busy')
  28. }
  29. private localVmAgents(owner:string){return this.store.list<WorkspaceAgent>(owner,'agent').filter(a=>a.nodeId==='local'&&!a.archived&&!a.remoteAgentId&&!a.temporaryGoalId&&(a.execution==='computer'||!!a.computerEnvironmentId))}
  30. assertLocalVmIdle(owner:string,ids?:string[]){this.idle(owner,ids??this.localVmAgents(owner).map(a=>a.id))}
  31. bindCompose(owner:string,agent:WorkspaceAgent,desktop:{id:string;name:string},runnerId:string,persist=true){
  32. this.idle(owner,[agent.id])
  33. const claim=this.store.get<{owner:string;runnerId:string}>('_system','compose-desktop-owner',desktop.id)
  34. if(claim&&(claim.owner!==owner||claim.runnerId!==runnerId))throw new HttpError(403,'这台共享桌面已分配给其他账号或执行节点','compose_desktop_forbidden')
  35. if(agent.computerEnvironmentId&&agent.computerEnvironmentId!==desktop.id)this.detachLocalVm(owner,agent)
  36. const group=this.store.get<SharedComputer>(owner,'shared-computer',desktop.id)??{id:desktop.id,name:desktop.name,nodeId:'local',profile:'*',runnerId,memberIds:[],archived:false,createdAt:Date.now(),managedCompose:true}
  37. group.archived=false;if(!group.memberIds.includes(agent.id))group.memberIds.push(agent.id)
  38. this.store.put('_system','compose-desktop-owner',desktop.id,{owner,runnerId})
  39. this.store.put(owner,'shared-computer',group.id,group)
  40. agent.execution='computer';agent.computer='vm';agent.computerEnvironmentId=desktop.id;agent.computerEnvironmentName=desktop.name
  41. if(persist){agent.revision++;agent.updatedAt=Date.now();this.store.put(owner,'agent',agent.id,agent);this.store.event(owner,'agent.changed',agent)}
  42. }
  43. attachLocalVm(owner:string,agent:WorkspaceAgent,runnerId:string){
  44. if(agent.nodeId!=='local'||agent.execution!=='computer'||agent.temporaryGoalId||agent.remoteAgentId||agent.computerEnvironmentId)return
  45. this.nodes.requireSource(owner,agent)
  46. const group=this.store.list<SharedComputer>(owner,'shared-computer').find(g=>!g.archived&&g.managedLocalVm&&g.runnerId===runnerId)
  47. ??{id:randomUUID(),name:'共享本地虚拟机',memberIds:[],nodeId:'local',profile:'*',runnerId,archived:false,createdAt:Date.now(),managedLocalVm:true}
  48. if(!group.memberIds.includes(agent.id))group.memberIds.push(agent.id)
  49. this.store.put(owner,'shared-computer',group.id,group)
  50. agent.computerEnvironmentId=group.id;agent.computerEnvironmentName=group.name
  51. }
  52. detachLocalVm(owner:string,agent:WorkspaceAgent){
  53. if(!agent.computerEnvironmentId)return
  54. const group=this.store.require<SharedComputer>(owner,'shared-computer',agent.computerEnvironmentId)
  55. group.memberIds=group.memberIds.filter(id=>id!==agent.id);group.archived=group.memberIds.length===0
  56. this.store.put(owner,'shared-computer',group.id,group)
  57. delete agent.computerEnvironmentId;delete agent.computerEnvironmentName
  58. this.store.put(owner,'agent',agent.id,agent)
  59. }
  60. setLocalVmMode(owner:string,mode:'shared'|'per-bot',runnerId:string){
  61. this.assertLocalVmIdle(owner)
  62. this.store.atomic(()=>{
  63. const agents=this.localVmAgents(owner)
  64. const previous=new Map(agents.map(a=>[a.id,{id:a.computerEnvironmentId,name:a.computerEnvironmentName}]))
  65. const groups=this.store.list<SharedComputer>(owner,'shared-computer').filter(g=>g.nodeId==='local'&&g.runnerId===runnerId)
  66. for(const group of groups){group.archived=true;this.store.put(owner,'shared-computer',group.id,group)}
  67. for(const agent of agents){
  68. if(agent.computerEnvironmentId&&groups.some(g=>g.id===agent.computerEnvironmentId)){delete agent.computerEnvironmentId;delete agent.computerEnvironmentName}
  69. }
  70. if(mode==='shared'){
  71. const members=agents.filter(a=>a.execution==='computer'&&!a.computerEnvironmentId)
  72. if(members.length){
  73. const group=groups.find(g=>g.managedLocalVm)??{id:randomUUID(),name:'共享本地虚拟机',memberIds:[],nodeId:'local',profile:'*',runnerId,archived:false,createdAt:Date.now(),managedLocalVm:true}
  74. group.profile='*';group.archived=false;group.managedLocalVm=true;group.memberIds=members.map(a=>a.id);this.store.put(owner,'shared-computer',group.id,group)
  75. for(const agent of members){agent.computerEnvironmentId=group.id;agent.computerEnvironmentName=group.name}
  76. }
  77. }
  78. for(const agent of agents){
  79. const before=previous.get(agent.id)!
  80. if(before.id===agent.computerEnvironmentId&&before.name===agent.computerEnvironmentName)continue
  81. agent.revision++;agent.updatedAt=Date.now();this.store.put(owner,'agent',agent.id,agent);this.store.event(owner,'agent.changed',agent)
  82. }
  83. })
  84. }
  85. create(owner:string,input:unknown){
  86. const body=parse(z.object({requestId:z.string().uuid(),name:z.string().trim().min(1).max(100),memberIds:z.array(z.string().uuid()).min(2).max(8),trusted:z.literal(true)}).strict(),input)
  87. return this.store.command(owner,body.requestId,{operation:'computer.share',...body},()=>this.store.atomic(()=>{
  88. if(new Set(body.memberIds).size!==body.memberIds.length)throw new HttpError(400,'成员不能重复','shared_computer_members')
  89. if(this.store.list<SharedComputer>(owner,'shared-computer').filter(value=>!value.archived).length>=16)throw new HttpError(409,'共享电脑数量已达上限','shared_computer_limit')
  90. const agents=body.memberIds.map(id=>this.store.require<WorkspaceAgent>(owner,'agent',id)),first=agents[0]!
  91. for(const agent of agents){
  92. this.nodes.requireSource(owner,agent)
  93. if(agent.archived||agent.temporaryGoalId||agent.remoteAgentId||agent.execution!=='computer'||agent.computerEnvironmentId||agent.nodeId!==first.nodeId)throw new HttpError(400,'请选择同一来源的持久隔离成员,且成员尚未加入其他共享电脑','shared_computer_members')
  94. }
  95. this.idle(owner,body.memberIds)
  96. const runnerId=this.hub.sharedComputerRunner(owner,first).id
  97. const shared:SharedComputer={id:randomUUID(),name:body.name,memberIds:body.memberIds,nodeId:first.nodeId,profile:'*',runnerId,archived:false,createdAt:Date.now()}
  98. this.store.put(owner,'shared-computer',shared.id,shared)
  99. for(const agent of agents){agent.computerEnvironmentId=shared.id;agent.computerEnvironmentName=shared.name;agent.revision++;agent.updatedAt=Date.now();this.store.put(owner,'agent',agent.id,agent);this.store.event(owner,'agent.changed',agent)}
  100. return shared
  101. }))
  102. }
  103. remove(owner:string,id:string){
  104. return this.store.atomic(()=>{
  105. const shared=this.store.require<SharedComputer>(owner,'shared-computer',id)
  106. if(shared.archived)return
  107. this.idle(owner,shared.memberIds,id)
  108. for(const agent of this.store.list<WorkspaceAgent>(owner,'agent').filter(agent=>agent.computerEnvironmentId===id)){
  109. delete agent.computerEnvironmentId;delete agent.computerEnvironmentName;agent.revision++;agent.updatedAt=Date.now();this.store.put(owner,'agent',agent.id,agent);this.store.event(owner,'agent.changed',agent)
  110. }
  111. shared.archived=true;this.store.put(owner,'shared-computer',id,shared)
  112. })
  113. }
  114. router(){
  115. const router=new Router()
  116. router.get('/api/app/computers/shared',ctx=>{const owner=this.auth.require(ctx).id;ctx.body={computers:this.store.list<SharedComputer>(owner,'shared-computer').filter(value=>!value.archived)}})
  117. router.post('/api/app/computers/shared',ctx=>{ctx.body={computer:this.create(this.auth.require(ctx).id,(ctx.request as any).body)};ctx.status=201})
  118. router.delete('/api/app/computers/shared/:id',ctx=>{this.remove(this.auth.require(ctx).id,ctx.params.id);ctx.body={ok:true}})
  119. return router
  120. }
  121. }