runnerHub.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
  2. import Router from '@koa/router'
  3. import type Koa from 'koa'
  4. import { z } from 'zod'
  5. import { HttpError } from './errors.js'
  6. import { parse, type WorkspaceStore } from './workspaceStore.js'
  7. import type { LocalAuthStore } from './localAuth.js'
  8. import type { GatewayFrame, GatewayTarget } from './workspaceGateway.js'
  9. import type { UpstreamRequestOptions, UpstreamResponse } from './upstream.js'
  10. import type { LeaseInput, WorkspaceToolLease } from './workspaceToolLease.js'
  11. import { RUNNER_PROTOCOL, type RunnerCommand, type RunnerRecord } from '../shared/runner.js'
  12. const hash = (value: string) => createHash('sha256').update(value).digest('hex')
  13. const input = z.object({ name:z.string().trim().min(1).max(100),sourceNodeId:z.string().min(1).max(100).default('local'),
  14. allowedProfiles:z.array(z.string().min(1).max(100)).min(1).max(256) }).strict()
  15. interface Pending { command:RunnerCommand; resolve(value:any):void; reject(error:Error):void; timer:ReturnType<typeof setTimeout>; nextDelivery:number; valid():boolean }
  16. interface GatewayConnection { runnerId:string;cleanupOnly?:boolean;publishArtifact?:(name:string,bytes:Buffer)=>Promise<unknown>; valid():boolean; onEvent(frame:GatewayFrame):void; onDisconnect():void }
  17. interface Lease { runnerId:string; input:LeaseInput; calls:Map<string,{fingerprint:string;result:Promise<unknown>}> }
  18. /** Outbound-only machine transport. Browser auth and machine auth remain separate. */
  19. export class RunnerHub {
  20. readonly epoch=randomUUID()
  21. private online = new Map<string,{instance:string;seen:number;epoch:string;features:string[];wake?:()=>void}>()
  22. private retired = new Map<string,Set<string>>()
  23. private pending = new Map<string,Map<string,Pending>>()
  24. private connections = new Map<string,GatewayConnection>()
  25. private artifacts=new Map<string,{runnerId:string;connectionId:string;name:string;size:number;digest:string;chunks:Buffer[];bytes:number;next:number;result?:unknown}>()
  26. private leases = new Map<string,Lease>()
  27. private watchdog: ReturnType<typeof setInterval>
  28. constructor(readonly store:WorkspaceStore,readonly auth:LocalAuthStore,readonly local:GatewayTarget) {
  29. this.watchdog=setInterval(()=>{
  30. for(const [id,state] of this.online) if(Date.now()-state.seen>35_000)this.disconnect(id)
  31. for(const [id,upload] of this.artifacts)if(!this.connections.has(upload.connectionId))this.artifacts.delete(id)
  32. },5000);this.watchdog.unref()
  33. }
  34. records():RunnerRecord[] {return this.store.list('_system','runner')}
  35. enroll(owner:string,value:unknown) {
  36. const body=parse(input,value)
  37. body.allowedProfiles=this.auth.validateAssignedProfiles(body.allowedProfiles)
  38. if(body.sourceNodeId!=='local'&&this.store.require<import('./workspaceGateway.js').WorkspaceNode>(owner,'node',body.sourceNodeId).transport==='paired-web')throw new HttpError(409,'配对 Web 节点应在它自己的服务中注册 Runner','runner_source_invalid')
  39. const sourceOwner=body.sourceNodeId==='local'?'_system':owner
  40. if(this.records().some(r=>r.enabled&&r.sourceOwner===sourceOwner&&r.sourceNodeId===body.sourceNodeId))
  41. throw new HttpError(409,'该来源已有执行节点,请先停用原节点','runner_source_in_use')
  42. const token=randomBytes(32).toString('base64url')
  43. const record:RunnerRecord={...body,id:randomUUID(),sourceOwner,tokenHash:hash(token),enabled:true,createdAt:Date.now()}
  44. this.store.put('_system','runner',record.id,record)
  45. return {runner:this.summary(record),token}
  46. }
  47. summary(record:RunnerRecord) {
  48. const {tokenHash:_secret,sourceOwner:_owner,...publicRecord}=record
  49. return {...publicRecord,features:this.online.get(record.id)?.features??[],online:!!this.online.get(record.id)&&Date.now()-this.online.get(record.id)!.seen<35_000}
  50. }
  51. remove(id:string) {
  52. const record=this.store.require<RunnerRecord>('_system','runner',id)
  53. record.enabled=false;this.store.put('_system','runner',id,record);this.disconnect(id)
  54. }
  55. private disconnect(id:string) {
  56. this.online.get(id)?.wake?.();this.online.delete(id)
  57. for(const [key,connection] of this.connections) if(connection.runnerId===id){this.connections.delete(key);connection.onDisconnect()}
  58. for(const [key,lease] of this.leases) if(lease.runnerId===id)this.leases.delete(key)
  59. for(const pending of this.pending.get(id)?.values()??[]){clearTimeout(pending.timer);pending.reject(new HttpError(503,'执行节点已断开,需核对原执行','runner_offline'))}
  60. this.pending.delete(id)
  61. }
  62. private request(id:string,kind:RunnerCommand['kind'],payload:Record<string,unknown>,valid:()=>boolean=()=>true):Promise<any> {
  63. if(!this.online.has(id))return Promise.reject(new HttpError(503,'执行节点未连接','runner_offline'))
  64. const queue=this.pending.get(id)??new Map<string,Pending>();this.pending.set(id,queue)
  65. if(queue.size>=64)return Promise.reject(new HttpError(429,'执行节点请求过多','runner_busy'))
  66. const command:RunnerCommand={id:randomUUID(),kind,payload,expiresAt:Date.now()+30000}
  67. const bytes=Buffer.byteLength(JSON.stringify(command))
  68. if(bytes>36*1024*1024)return Promise.reject(new HttpError(413,'执行命令超过传输限制','runner_payload_limit'))
  69. if([...queue.values()].reduce((size,p)=>size+Buffer.byteLength(JSON.stringify(p.command)),bytes)>64*1024*1024)return Promise.reject(new HttpError(429,'执行节点待传输数据过多','runner_busy'))
  70. return new Promise((resolve,reject)=>{
  71. const timer=setTimeout(()=>{queue.delete(command.id);reject(new HttpError(504,'执行节点回应超时,请核对执行状态','runner_command_uncertain'))},30000)
  72. queue.set(command.id,{command,resolve,reject,timer,nextDelivery:0,valid});this.online.get(id)?.wake?.()
  73. })
  74. }
  75. target(owner:string,sourceNodeId:string,computer?:import('../runner/worker/gateway.js').ComputerTarget):GatewayTarget|undefined {
  76. const record=this.records().find(r=>r.enabled&&r.sourceNodeId===sourceNodeId&&(r.sourceOwner==='_system'||r.sourceOwner===owner))
  77. if(!record)return undefined
  78. const requireProfile=(profile:string)=>{
  79. if(!this.auth.canUseSource(owner,sourceNodeId,profile)||!record.allowedProfiles.includes(profile))throw new HttpError(403,'执行节点未授权这个基础 Profile','runner_profile_forbidden')
  80. }
  81. const requireComputer=()=>{if(computer&&!this.online.get(record.id)?.features.includes('computer-worker-v1'))throw new HttpError(409,'执行节点未提供隔离 Worker 能力,请检查配置或更新 Runner','computer_unavailable')}
  82. const requestHTTP=async(path:string,options:UpstreamRequestOptions={}):Promise<UpstreamResponse>=>{
  83. requireComputer()
  84. const profile=options.search?.get('profile')??'default'
  85. if(path!=='/api/profiles'&&path!=='/api/status')requireProfile(profile)
  86. const version=this.auth.pushAuthorizationVersion(owner)
  87. const valid=()=>this.auth.isUserActive(owner)&&this.auth.pushAuthorizationVersion(owner)===version&&this.store.get<RunnerRecord>('_system','runner',record.id)?.enabled===true
  88. const result=await this.request(record.id,'http',{path,method:options.method??'GET',search:options.search?.toString(),body:options.body,computer},valid)
  89. if(!valid())throw new HttpError(403,'读取权限已失效','runner_authorization_revoked')
  90. if(path==='/api/profiles') {
  91. const parsed=JSON.parse(Buffer.from(result.body,'base64').toString())
  92. parsed.profiles=(parsed.profiles??[]).filter((p:any)=>{const name=typeof p==='string'?p:p.name;return record.allowedProfiles.includes(name)&&this.auth.canUseSource(owner,sourceNodeId,name)})
  93. result.body=Buffer.from(JSON.stringify(parsed)).toString('base64')
  94. }
  95. return {status:result.status,headers:new Headers(result.headers),body:Buffer.from(result.body,'base64')}
  96. }
  97. return {url:this.local.url,client:this.local.client,session:{request:requestHTTP,webSocketCredential:async()=>{throw new Error('Runner uses its own authenticated gateway')}},
  98. runner:{id:record.id,computer:!!computer,helperRetirement:this.online.get(record.id)?.features.includes('helper-retirement-v1')===true,
  99. open:async(onEvent,onDisconnect,scope)=>{
  100. requireComputer()
  101. if(computer&&!scope)throw new HttpError(403,'隔离执行缺少任务授权','computer_scope_required')
  102. const version=this.auth.pushAuthorizationVersion(owner)
  103. const valid=()=>{try{scope?.authorize();return (scope?.cleanupOnly||(this.auth.isUserActive(owner)&&this.auth.pushAuthorizationVersion(owner)===version))&&this.store.get<RunnerRecord>('_system','runner',record.id)?.enabled===true}catch{return false}}
  104. const id=randomUUID();this.connections.set(id,{runnerId:record.id,valid,onEvent,onDisconnect,publishArtifact:scope?.publishArtifact,cleanupOnly:scope?.cleanupOnly})
  105. try {await this.request(record.id,'gateway.open',{connectionId:id,computer,workId:scope?.workId,cleanupOnly:scope?.cleanupOnly})} catch(error){this.connections.delete(id);void this.request(record.id,'gateway.close',{connectionId:id}).catch(()=>{});throw error}
  106. let closed=false
  107. return {rpc:async(method,params)=>{
  108. if(closed)throw new Error('Runner gateway closed')
  109. const cleanup=['session.interrupt','session.close'].includes(method)
  110. if(scope?.cleanupOnly&&(!['session.resume','session.interrupt','session.close'].includes(method)||(method==='session.resume'&&params.session_id!==scope.sessionId)))throw new HttpError(403,'清理通道只能操作原绑定会话','runner_cleanup_forbidden')
  111. if(!cleanup&&!valid())throw new HttpError(403,'本轮执行授权已失效','runner_command_not_admitted')
  112. if(!scope?.cleanupOnly&&(method==='session.create'||method==='session.resume'))requireProfile(String(params.profile??'default'))
  113. return this.request(record.id,'gateway.rpc',{connectionId:id,method,params})
  114. },close:()=>{
  115. closed=true;this.connections.delete(id)
  116. for(const [key,pending] of this.pending.get(record.id)??[])if(pending.command.payload.connectionId===id){clearTimeout(pending.timer);pending.reject(new HttpError(409,'执行通道已关闭','runner_command_not_admitted'));this.pending.get(record.id)!.delete(key)}
  117. void this.request(record.id,'gateway.close',{connectionId:id}).catch(()=>{})
  118. }}
  119. },
  120. lease:async(options)=>{
  121. requireComputer();requireProfile(options.profile);options.assertActive()
  122. const id=randomUUID();this.leases.set(id,{runnerId:record.id,input:options,calls:new Map()})
  123. let disposed=false
  124. const dispose=async()=>{if(disposed)return;disposed=true;this.leases.delete(id);options.signal.removeEventListener('abort',abort);await this.request(record.id,'lease.close',{leaseId:id}).catch(()=>{})}
  125. const abort=()=>{void dispose()};options.signal.addEventListener('abort',abort,{once:true})
  126. try {
  127. await this.request(record.id,'lease.create',{leaseId:id,profile:options.profile,workId:options.workId,session:options.session(),catalog:options.catalog()})
  128. options.assertActive()
  129. if(options.signal.aborted)throw new Error('执行已停止')
  130. return {bind:async()=>{options.assertActive();await this.request(record.id,'lease.bind',{leaseId:id,session:options.session()});options.assertActive()},dispose} satisfies WorkspaceToolLease
  131. } catch(error){await dispose();throw error}
  132. },
  133. }}
  134. }
  135. async retireHelper(owner:string,helper:import('../shared/workspace.js').WorkspaceAgent):Promise<void>{
  136. if(!helper.temporaryGoalId||!helper.archived||!helper.helperRunnerId)throw new HttpError(403,'只能清理已退役的任务助手','helper_cleanup_forbidden')
  137. const current=this.store.require<import('../shared/workspace.js').WorkspaceAgent>(owner,'agent',helper.id)
  138. if(!current.archived||current.temporaryGoalId!==helper.temporaryGoalId)throw new HttpError(409,'助手状态已改变','helper_cleanup_forbidden')
  139. const record=this.store.require<RunnerRecord>('_system','runner',helper.helperRunnerId)
  140. if(record.sourceNodeId!==helper.nodeId||(record.sourceOwner!=='_system'&&record.sourceOwner!==owner))throw new HttpError(403,'清理节点不匹配','helper_cleanup_forbidden')
  141. if(!this.online.get(record.id)?.features.includes('helper-retirement-v1'))throw new HttpError(503,'等待支持清理的原执行节点上线','runner_offline')
  142. await this.request(record.id,'computer.retire',{environmentId:helper.id,agentId:helper.id,ownerKey:hash(owner)})
  143. }
  144. adminRouter():Router {
  145. const router=new Router()
  146. router.get('/api/app/admin/runners',ctx=>{const actor=this.auth.requireAdmin(ctx);ctx.body={protocol:RUNNER_PROTOCOL,runners:this.records().map(r=>this.summary(r)),sources:[{id:'local',name:'本地来源'},...this.store.list<import('./workspaceGateway.js').WorkspaceNode>(actor.id,'node').filter(n=>n.transport!=='paired-web').map(n=>({id:n.id,name:n.name}))]}})
  147. router.post('/api/app/admin/runners',ctx=>{const actor=this.auth.requireAdmin(ctx);ctx.body=this.enroll(actor.id,(ctx.request as any).body);ctx.status=201})
  148. router.delete('/api/app/admin/runners/:id',ctx=>{this.auth.requireAdmin(ctx);this.remove(ctx.params.id);ctx.body={ok:true}})
  149. return router
  150. }
  151. middleware():Koa.Middleware {
  152. return async(ctx,next)=>{
  153. const match=/^\/api\/runner\/v1\/([0-9a-f-]{36})\/(poll|admit|result|event|tool|check|artifact)$/.exec(ctx.path)
  154. if(!match)return next()
  155. const record=this.store.get<RunnerRecord>('_system','runner',match[1]!),token=ctx.get('authorization').replace(/^Bearer /,'')
  156. if(ctx.get('origin')||!record?.enabled||!ctx.get('authorization').startsWith('Bearer ')||!timingSafeEqual(Buffer.from(record.tokenHash),Buffer.from(hash(token))))
  157. throw new HttpError(403,'执行节点授权无效','runner_unauthorized')
  158. const instance=ctx.get('x-runner-instance')
  159. if(!/^[0-9a-f-]{36}$/.test(instance)||ctx.get('x-runner-protocol')!==String(RUNNER_PROTOCOL))throw new HttpError(409,'执行节点协议不兼容','runner_protocol_mismatch')
  160. let previous=this.online.get(record.id)
  161. if(match[2]==='poll'&&previous?.instance===instance&&ctx.get('x-runner-reset')==='1'){this.disconnect(record.id);previous=undefined}
  162. if(match[2]!=='poll'&&previous?.instance!==instance)throw new HttpError(409,'执行节点会话已更换','runner_instance_changed')
  163. if(this.retired.get(record.id)?.has(instance))throw new HttpError(409,'执行节点实例已被替换','runner_instance_retired')
  164. if(previous&&previous.instance!==instance){
  165. const retired=this.retired.get(record.id)??new Set<string>()
  166. if(retired.size>=256)throw new HttpError(409,'执行节点更换过于频繁,请重新注册','runner_instance_limit')
  167. retired.add(previous.instance);this.retired.set(record.id,retired);this.disconnect(record.id);previous=undefined
  168. }
  169. if(match[2]!=='poll'&&ctx.get('x-runner-epoch')!==previous?.epoch)throw new HttpError(409,'执行连接代次已改变','runner_epoch_changed')
  170. const state=this.online.get(record.id)??{instance,seen:Date.now(),features:[],epoch:`${this.epoch}:${randomUUID()}`};state.seen=Date.now();if(match[2]==='poll')state.features=ctx.get('x-runner-features').split(',').filter(value=>['computer-worker-v1','artifact-chunks-v1','helper-retirement-v1'].includes(value));this.online.set(record.id,state)
  171. ctx.set('Cache-Control','no-store')
  172. if(match[2]==='poll') {
  173. if(ctx.method!=='GET')throw new HttpError(405,'仅允许 GET','method_not_allowed')
  174. const available=()=>[...(this.pending.get(record.id)?.values()??[])].filter(p=>p.nextDelivery<=Date.now())
  175. if(previous&&!available().length)await new Promise<void>(resolve=>{
  176. const done=()=>{clearTimeout(timer);ctx.res.off('close',done);if(state.wake===done)state.wake=undefined;resolve()}
  177. const retry=Math.min(15000,...[...(this.pending.get(record.id)?.values()??[])].map(p=>Math.max(1,p.nextDelivery-Date.now())))
  178. const timer=setTimeout(done,retry);state.wake?.();state.wake=done;ctx.res.once('close',done)
  179. })
  180. if(this.online.get(record.id)!==state)throw new HttpError(409,'执行节点会话已更换','runner_instance_changed')
  181. let bytes=0
  182. const batch=available().filter(item=>{const size=Buffer.byteLength(JSON.stringify(item.command));if(bytes+size>38*1024*1024)return false;bytes+=size;return true});for(const item of batch)item.nextDelivery=Date.now()+5000
  183. ctx.body={epoch:state.epoch,commands:batch.map(p=>p.command)};return
  184. }
  185. if(ctx.method!=='POST')throw new HttpError(405,'仅允许 POST','method_not_allowed')
  186. let size=0;const chunks:Buffer[]=[]
  187. for await(const chunk of ctx.req){size+=chunk.length;if(size>16*1024*1024)throw new HttpError(413,'执行节点响应过大','runner_payload_limit');chunks.push(Buffer.from(chunk))}
  188. let body:any
  189. try {body=JSON.parse(Buffer.concat(chunks).toString())}catch{throw new HttpError(400,'JSON 无效','invalid_json')}
  190. if(!body||typeof body!=='object'||Array.isArray(body))throw new HttpError(400,'请求必须是对象','invalid_json')
  191. if(match[2]==='artifact'){
  192. const value=parse(z.object({connectionId:z.string().uuid(),id:z.string().uuid(),phase:z.enum(['begin','append','finish']),name:z.string().min(1).max(240).optional(),size:z.number().int().min(0).max(25*1024*1024).optional(),digest:z.string().regex(/^[a-f0-9]{64}$/).optional(),index:z.number().int().min(0).optional(),data:z.string().max(1024*1024).optional()}).strict(),body)
  193. const connection=this.connections.get(value.connectionId)
  194. if(connection?.runnerId!==record.id||!connection.valid()||!connection.publishArtifact)throw new HttpError(403,'产物不属于当前有效任务','artifact_forbidden')
  195. let upload=this.artifacts.get(value.id)
  196. if(value.phase==='begin'){
  197. if(!value.name||value.size===undefined||!value.digest)throw new HttpError(400,'产物信息不完整','artifact_invalid')
  198. if(upload&&(upload.connectionId!==value.connectionId||upload.name!==value.name||upload.size!==value.size||upload.digest!==value.digest))throw new HttpError(409,'产物编号已用于其他内容','idempotency_conflict')
  199. if(!upload){
  200. const current=[...this.artifacts.values()]
  201. if(current.filter(item=>item.connectionId===value.connectionId).length>=8||current.filter(item=>item.runnerId===record.id&&item.result===undefined).reduce((sum,item)=>sum+item.size,0)+value.size>64*1024*1024)throw new HttpError(429,'待传产物过多','artifact_limit')
  202. upload={runnerId:record.id,connectionId:value.connectionId,name:value.name,size:value.size,digest:value.digest,chunks:[],bytes:0,next:0};this.artifacts.set(value.id,upload)
  203. }
  204. }else{
  205. if(!upload||upload.connectionId!==value.connectionId||upload.runnerId!==record.id)throw new HttpError(404,'产物传输不存在','artifact_missing')
  206. if(value.phase==='append'){
  207. if(value.index===undefined||value.data===undefined||upload.result!==undefined)throw new HttpError(400,'产物分块无效','artifact_invalid')
  208. const bytes=Buffer.from(value.data,'base64')
  209. if(value.index<upload.next){if(!upload.chunks[value.index]?.equals(bytes))throw new HttpError(409,'重复分块内容不一致','idempotency_conflict')}
  210. else{if(value.index!==upload.next||upload.bytes+bytes.length>upload.size)throw new HttpError(409,'分块顺序或大小无效','artifact_invalid');upload.chunks.push(bytes);upload.bytes+=bytes.length;upload.next++}
  211. }else if(upload.result===undefined){
  212. if(upload.bytes!==upload.size)throw new HttpError(409,'产物尚未传输完整','artifact_incomplete')
  213. const bytes=Buffer.concat(upload.chunks)
  214. if(createHash('sha256').update(bytes).digest('hex')!==upload.digest)throw new HttpError(409,'产物校验失败','artifact_digest_mismatch')
  215. upload.result=await connection.publishArtifact(upload.name,bytes);upload.chunks=[]
  216. }
  217. }
  218. ctx.body={ok:true,next:upload!.next,result:upload!.result};return
  219. }
  220. if(match[2]==='check'){const connection=this.connections.get(body.connectionId);ctx.body={allowed:connection?.runnerId===record.id&&connection.valid()};return}
  221. if(match[2]==='admit') {
  222. const pending=this.pending.get(record.id)?.get(body.id),command=pending?.command
  223. let allowed=!!command&&command.expiresAt>Date.now()&&pending!.valid()
  224. if(command?.kind==='gateway.rpc'||command?.kind==='gateway.open'){const connection=this.connections.get(String(command.payload.connectionId));allowed&&=connection?.runnerId===record.id&&(command.kind==='gateway.rpc'&&['session.interrupt','session.close'].includes(String(command.payload.method))||connection.valid())}
  225. if(command?.kind==='lease.create'||command?.kind==='lease.bind') {
  226. const lease=this.leases.get(String(command.payload.leaseId))
  227. try {if(lease?.runnerId!==record.id)allowed=false;else lease.input.assertActive()}catch{allowed=false}
  228. }
  229. ctx.body={allowed};return
  230. }
  231. if(match[2]==='result') {
  232. const waiter=this.pending.get(record.id)?.get(body.id)
  233. if(waiter){clearTimeout(waiter.timer);this.pending.get(record.id)!.delete(body.id);body.error?waiter.reject(new HttpError(502,String(body.error.message??'执行节点失败').slice(0,1000),String(body.error.code??'runner_error'))):waiter.resolve(body.result)}
  234. ctx.body={ok:true};return
  235. }
  236. if(match[2]==='event') {
  237. const connection=this.connections.get(body.connectionId)
  238. if(connection?.runnerId!==record.id)throw new HttpError(410,'执行通道已关闭','runner_connection_closed')
  239. if(!connection.valid()){this.connections.delete(body.connectionId);connection.onDisconnect();throw new HttpError(410,'执行通道授权已失效','runner_connection_closed')}
  240. if(body.closed){this.connections.delete(body.connectionId);connection.onDisconnect()}
  241. else if(body.frame&&typeof body.frame.type==='string')connection.onEvent(body.frame)
  242. ctx.body={ok:true};return
  243. }
  244. const value=parse(z.object({leaseId:z.string().uuid(),toolId:z.string().min(1).max(100),callId:z.string().min(1).max(200),arguments:z.record(z.string(),z.unknown())}).strict(),body)
  245. const lease=this.leases.get(value.leaseId)
  246. if(lease?.runnerId!==record.id)throw new HttpError(410,'工具授权已失效','runner_lease_expired')
  247. lease.input.assertActive()
  248. const fingerprint=hash(JSON.stringify([value.toolId,value.arguments]));let call=lease.calls.get(value.callId)
  249. if(call&&call.fingerprint!==fingerprint)throw new HttpError(409,'重复调用参数不一致','idempotency_conflict')
  250. if(!call){if(lease.calls.size>=128)throw new HttpError(429,'本轮工具调用已达上限','runner_call_limit');call={fingerprint,result:Promise.resolve().then(()=>lease.input.call(value.toolId,value.arguments,value.callId))};lease.calls.set(value.callId,call)}
  251. const result=await call.result;lease.input.assertActive();ctx.body={result}
  252. }
  253. }
  254. close(){clearInterval(this.watchdog);for(const id of [...this.online.keys()])this.disconnect(id)}
  255. }