workspaceRuntime.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. import {DESKTOP_ENVIRONMENT_TOOLS,DESKTOP_ENVIRONMENT_RULES,type DesktopEnvironments} from './desktopEnvironments.js'
  2. import {GROK_COMPUTER_TOOLS,GROK_COMPUTER_RULES,type GrokCloud} from './grokCloud.js'
  3. import { randomUUID } from 'node:crypto'
  4. import { readFileSync } from 'node:fs'
  5. import { z } from 'zod'
  6. import { WorkspaceStore, parse } from './workspaceStore.js'
  7. import { WorkspaceNodes, WorkspaceGateway, type GatewayFrame } from './workspaceGateway.js'
  8. import { HttpError } from './errors.js'
  9. import { applyWorkingDirectory, configuredWorkingDirectory } from './sessionWorkingDirectory.js'
  10. import {type StoredWorkspaceFile} from './workspaceAssets.js'
  11. import { UploadStore } from './uploads.js'
  12. import type {
  13. WorkspaceAgent as Agent,
  14. WorkspaceConversation as Conversation,
  15. WorkspaceMessage as Message,
  16. WorkspaceRun,
  17. WorkspaceInteraction,
  18. } from '../shared/workspace.js'
  19. import { WorkspaceScheduler, type Work, NO_REPLY, HOST_FALLBACK } from './workspaceScheduler.js'
  20. import { mentionedAgents } from './workspaceMentions.js'
  21. import { WorkspaceTeamTools, TEAM_TOOL_RULES } from './workspaceTeamTools.js'
  22. import { createWorkspaceToolLease, type WorkspaceToolLease } from './workspaceToolLease.js'
  23. import { WorkspaceTaskCoordinator } from './taskCoordinator.js'
  24. export { mentionedAgents } from './workspaceMentions.js'
  25. type Run = WorkspaceRun
  26. export interface WorkspaceBinding {
  27. runnerId?: string
  28. execution?:string
  29. computerEnvironmentId?:string
  30. remoteAgentId?: string
  31. id: string
  32. nodeId: string
  33. profile: string
  34. storedId: string
  35. runtimeId: string
  36. aliases: string[]
  37. runId: string
  38. messageId: string
  39. conversationTaskId?: string
  40. taskId?: string
  41. contextSeq?: number
  42. }
  43. interface LiveTurn {
  44. gateway: WorkspaceGateway
  45. runtimeId: string
  46. runId: string
  47. agentId: string
  48. conversationTaskId?: string
  49. taskId: string
  50. done(error?: Error): void
  51. }
  52. export const sendInput = z
  53. .object({
  54. requestId: z.string().uuid(),
  55. content: z.string().max(65_536).default(''),
  56. taskId: z.string().uuid().optional(),
  57. mentionIds: z.array(z.string().uuid()).max(8).default([]),
  58. fileIds: z.array(z.string().uuid()).max(8).default([]),
  59. })
  60. .strict()
  61. .refine((b) => b.content.trim() || b.fileIds.length, '请输入消息或添加附件')
  62. export class WorkspaceRuntime extends WorkspaceScheduler {
  63. get idleForUpdate(): boolean {
  64. return this.live.size === 0 && this.executing.size === 0 && !this.store.db.prepare("SELECT 1 FROM workspace_entities WHERE kind IN ('run','turn') AND COALESCE(json_extract(data,'$.status'),'unknown') NOT IN ('complete','failed','interrupted') LIMIT 1").get()
  65. }
  66. desktopEnvironments?:DesktopEnvironments
  67. cloud?:GrokCloud
  68. inspector?:import('./workspaceInspector.js').WorkspaceInspector
  69. private live = new Map<string, LiveTurn>()
  70. readonly teamTools: WorkspaceTeamTools
  71. readonly tasks: WorkspaceTaskCoordinator
  72. retireHelper:(owner:string,helper:Agent)=>Promise<void>=async()=>{throw new Error('电脑清理服务未连接')}
  73. publishArtifact:(owner:string,message:Message,agent:Agent,name:string,bytes:Buffer)=>import('../shared/workspace.js').WorkspaceFile=()=>{throw new Error('产物服务未初始化')}
  74. onTeamCreated: (owner: string, team: Conversation) => void = () => {}
  75. constructor(store: WorkspaceStore, readonly nodes: WorkspaceNodes, readonly uploads: UploadStore, userActive: (owner: string) => boolean = () => true,
  76. readonly authorizationVersion: (owner: string) => number = () => 0) {
  77. super(store, userActive)
  78. this.teamTools = new WorkspaceTeamTools(store, nodes, this)
  79. this.tasks = new WorkspaceTaskCoordinator(store, this)
  80. }
  81. send(owner: string, conversationId: string, input: unknown): Run {
  82. return this.submit(owner, conversationId, input)
  83. }
  84. /** Server-owned provenance. This is never exposed as a model-supplied identity. */
  85. dispatch(owner: string, conversationId: string, input: unknown, source: {
  86. agentId: string; assignmentId?: string; targetAgentId?: string; kind: NonNullable<Run['triggerKind']>; instruction?: string; taskReference?: {conversationId:string;taskId:string}
  87. }): Run {
  88. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', source.agentId))
  89. return this.submit(owner, conversationId, input, source)
  90. }
  91. private files(owner:string,ids:string[]){return ids.map(id=>{const file=this.store.get<StoredWorkspaceFile>(owner,'file',id);if(file){if(file.sourceNodeId&&file.profile)this.nodes.requireSource(owner,{nodeId:file.sourceNodeId,profile:file.profile});return file}return {...this.uploads.records([id],owner)[0]!,sender:'user' as const}})}
  92. private submit(owner: string, conversationId: string, input: unknown, source?: {
  93. agentId: string; assignmentId?: string; targetAgentId?: string; kind: NonNullable<Run['triggerKind']>; instruction?: string; taskReference?: {conversationId:string;taskId:string}
  94. }): Run {
  95. if (!this.userActive(owner)) throw new HttpError(403,'账号授权已失效','account_inactive')
  96. const body = parse(sendInput, input)
  97. for (const id of this.store.require<Conversation>(owner, 'conversation', conversationId).memberIds)
  98. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', id))
  99. const result = this.store.command(owner, body.requestId, { conversationId, ...body, ...(source ? { source } : {}) }, () => {
  100. const c = this.store.require<Conversation>(owner, 'conversation', conversationId)
  101. if (c.archived) throw new HttpError(409, '聊天已归档', 'conversation_archived')
  102. const conversationTask = this.store.resolveTask(owner, conversationId, body.taskId),
  103. conversationTaskId = conversationTask?.id
  104. if (conversationTaskId) {
  105. const alreadyActive = this.store.list<Run>(owner, 'run').some(run => run.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status))
  106. if (!alreadyActive && this.store.activeTaskCount(owner, conversationId) >= 4)
  107. throw new HttpError(409, '最多同时运行 4 个任务', 'workspace_task_concurrency_limit')
  108. }
  109. if (body.mentionIds.some((a) => !this.store.taskMemberIds(owner,c,conversationTaskId).includes(a)))
  110. throw new HttpError(400, '只能 @ 群内成员', 'invalid_mentions')
  111. const records = this.files(owner,body.fileIds)
  112. const now = Date.now(),
  113. runId = randomUUID(),
  114. agents = this.store.taskMemberIds(owner,c,conversationTaskId).map((id) => this.store.require<Agent>(owner, 'agent', id))
  115. const mentions = [
  116. ...new Set(
  117. [...body.mentionIds, ...mentionedAgents(body.content, agents)],
  118. ),
  119. ]
  120. const message: Message = {
  121. id: randomUUID(),
  122. conversationId,
  123. conversationTaskId,
  124. seq: 0,
  125. role: source ? 'system' : 'user',
  126. ...(source?.taskReference ? {taskReference:source.taskReference} : {}),
  127. ...(source ? { agentId: source.agentId, agentName: this.store.require<Agent>(owner, 'agent', source.agentId).name } : {}),
  128. content: body.content.trim(),
  129. reasoning: '',
  130. runId,
  131. status: 'complete',
  132. attachments: records.map((f) => ({
  133. id: f.id,
  134. name: f.name,
  135. mimeType: f.mimeType,
  136. size: f.size,
  137. sender: f.sender,
  138. createdAt: now,
  139. })),
  140. tools: [],
  141. createdAt: now,
  142. }
  143. this.store.saveMessage(owner, message)
  144. for (const file of records) {
  145. const existing = this.store.get<Record<string, unknown>>(owner, 'file', file.id)
  146. if (existing && !existing.messageId)
  147. this.store.put(owner, 'file', file.id, {
  148. ...existing,
  149. conversationId,
  150. messageId: message.id,
  151. })
  152. }
  153. const run: Run = {
  154. id: runId,
  155. conversationId,
  156. conversationTaskId,
  157. messageId: message.id,
  158. mentionIds: mentions,
  159. activeAgentId: c.administratorId,
  160. status: 'queued',
  161. round: 0,
  162. createdAt: now,
  163. updatedAt: now,
  164. authorizationVersion: this.authorizationVersion(owner),
  165. ...(source ? { assignmentId: source.assignmentId, targetAgentId: source.targetAgentId, triggerKind: source.kind, internalInstruction: source.instruction } : {}),
  166. }
  167. this.admit(owner, run, c, message)
  168. this.uploads.markReferenced(body.fileIds, owner)
  169. return run
  170. })
  171. this.wake()
  172. return this.store.require<Run>(owner, 'run', result.id)
  173. }
  174. protected async performTurn(
  175. owner: string,
  176. c: Conversation,
  177. agent: Agent,
  178. run: Work,
  179. recovering = false,
  180. ): Promise<Message> {
  181. this.requireAuthorization(owner, run.runId)
  182. this.store.requireAgentTask(owner,agent,c.id,run.conversationTaskId)
  183. this.nodes.requireSource(owner, agent)
  184. if (agent.remoteAgentId) agent = await this.nodes.refreshRemoteAgent(owner,agent)
  185. const key = this.bindingKey(c.id, run.conversationTaskId, agent.id),
  186. target = agent.remoteAgentId || agent.execution==='computer' ? this.nodes.targetForAgent(owner,agent) : this.nodes.target(owner, agent.nodeId)
  187. const gateway = new WorkspaceGateway(target,{workId:run.id,publishArtifact:async(name,bytes)=>{
  188. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,agent)
  189. const file=this.publishArtifact(owner,resultMessage,agent,name,bytes)
  190. if(!resultMessage.attachments.some(item=>item.id===file.id))resultMessage.attachments.push(file)
  191. this.store.saveMessage(owner,resultMessage)
  192. return {...file,url:`/api/app/files/${file.id}/download`}
  193. },authorize:()=>{
  194. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,agent)
  195. const current=this.getWork(owner,run.id),latest=this.store.require<Agent>(owner,'agent',agent.id),conversation=this.store.require<Conversation>(owner,'conversation',c.id)
  196. if(this.closing||conversation.archived||!this.store.taskMemberIds(owner,conversation,run.conversationTaskId).includes(agent.id)||this.store.require<Run>(owner,'run',run.runId).stopRequested||current.cancelRequested||['interrupted','complete','failed'].includes(current.status)||latest.archived||latest.computerEnvironmentId!==agent.computerEnvironmentId||(latest.execution??'profile')!==(agent.execution??'profile')||latest.teamAuthorizationVersion!==agent.teamAuthorizationVersion)throw new HttpError(403,'本轮机器人或任务授权已结束','run_authorization_revoked')
  197. }})
  198. gateway.onTrace=entry=>this.inspector?.record(owner,c.id,{...entry,agentId:agent.id,runId:run.runId,taskId:run.conversationTaskId})
  199. let binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
  200. const movedRunner=!!this.store.get(owner,'binding-reset',key)||!!binding&&(binding.computerEnvironmentId!==agent.computerEnvironmentId||binding.runnerId!==target.runner?.id||(binding.execution??'profile')!==(agent.execution??'profile'))
  201. if(movedRunner) {
  202. if(recovering)throw new HttpError(409,'执行节点已变化,不能在另一节点重放原执行','runner_target_changed')
  203. binding=undefined
  204. }
  205. let message =
  206. run.currentMessageId
  207. ? this.store.require<Message>(owner, 'message', run.currentMessageId)
  208. : undefined
  209. if (!message) {
  210. message = {
  211. id: randomUUID(),
  212. conversationId: c.id,
  213. conversationTaskId: run.conversationTaskId,
  214. seq: 0,
  215. role: 'assistant',
  216. execution:agent.execution??'profile',
  217. agentId: agent.id,
  218. agentName: agent.name,
  219. content: '',
  220. reasoning: '',
  221. status: 'streaming',
  222. runId: run.runId,
  223. taskId: run.id,
  224. visible: run.replyMode !== 'automatic' || run.requiredReply,
  225. tools: [],
  226. attachments: [],
  227. createdAt: Date.now(),
  228. }
  229. run.currentMessageId = message.id
  230. this.store.atomic(() => {
  231. this.store.saveMessage(owner, message!)
  232. this.saveWork(owner, run)
  233. })
  234. }
  235. if(!recovering&&message.status==='queued'){message.status='streaming';message.error=undefined;message.visible=run.replyMode!=='automatic'||run.requiredReply}
  236. const resultMessage = message
  237. let submitted = recovering,
  238. settled = false,
  239. completedEvidence = false,
  240. completing = false,
  241. runtimeId = '',
  242. lastFlush = 0
  243. let flushTimer: ReturnType<typeof setTimeout> | undefined
  244. const toolController = new AbortController()
  245. let toolLease: WorkspaceToolLease | undefined
  246. let resolveTurn!: (m: Message) => void, rejectTurn!: (e: Error) => void
  247. const completion = new Promise<Message>((resolve, reject) => {
  248. resolveTurn = resolve
  249. rejectTurn = reject
  250. })
  251. // Register rejection immediately; setup RPCs can still be awaiting a reply.
  252. void completion.catch(() => {})
  253. const finish = (error?: Error) => {
  254. if (settled) return
  255. settled = true
  256. toolController.abort()
  257. void toolLease?.dispose()
  258. clearTimeout(flushTimer)
  259. flushTimer = undefined
  260. this.live.delete(key)
  261. try {
  262. const current = this.getWork(owner, run.id)
  263. if(error&&!submitted&&current.status!=='interrupted'&&error instanceof HttpError&&['computer_busy','computer_quota','runner_offline'].includes(error.code??'')){
  264. current.status='queued';current.resourceWait=true;current.error='等待执行节点或电脑资源';resultMessage.status='queued';resultMessage.visible=false;resultMessage.error=undefined
  265. }else if (error) {
  266. current.status = current.status === 'interrupted' ? 'interrupted' : submitted ? 'uncertain' : 'failed'
  267. current.error = error.message.slice(0, 1000)
  268. resultMessage.status = current.status
  269. resultMessage.error = current.error
  270. const optionalUnpublished = current.replyMode === 'automatic' && !current.requiredReply && resultMessage.visible === false
  271. resultMessage.visible = !optionalUnpublished && (submitted || current.status !== 'interrupted')
  272. if (!resultMessage.content.trim() && current.status === 'failed') resultMessage.content = `执行失败:${current.error}`
  273. } else {
  274. const silent = (resultMessage.content.trim() === NO_REPLY || !resultMessage.content.trim()) && current.replyMode === 'automatic' && (!current.requiredReply || current.hadInteraction) && !resultMessage.tools.length && !resultMessage.attachments.length
  275. current.silent = silent
  276. if (current.replyMode === 'automatic') {
  277. resultMessage.content = resultMessage.content.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '').trim()
  278. resultMessage.reasoning = resultMessage.reasoning.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '')
  279. }
  280. if (current.requiredReply && !silent && !resultMessage.content) resultMessage.content = HOST_FALLBACK
  281. if (!silent && !resultMessage.content && !resultMessage.attachments.length && !resultMessage.tools.length) {
  282. current.status = 'failed'; current.error = '未返回有效回复'; resultMessage.content = '执行失败:未返回有效回复'
  283. } else { current.status = 'complete'; current.error = undefined }
  284. resultMessage.visible = !silent
  285. if (silent) resultMessage.reasoning = ''
  286. resultMessage.status = current.status
  287. resultMessage.error = current.error
  288. }
  289. if (current.status !== 'uncertain') {
  290. for (const tool of resultMessage.tools) {
  291. if (!/complete|error|failed/.test(String(tool.status))) tool.status = current.status === 'complete' ? 'tool.complete' : 'tool.error'
  292. }
  293. }
  294. this.store.atomic(() => {
  295. this.store.saveMessage(owner, resultMessage)
  296. this.saveWork(owner, current)
  297. if (current.status !== 'uncertain') this.resolveInteractions(owner, current.id)
  298. })
  299. if (error) rejectTurn(error)
  300. else resolveTurn(resultMessage)
  301. } catch (failure) { rejectTurn(failure instanceof Error ? failure : new Error('无法保存执行状态')) }
  302. finally { gateway.close() }
  303. }
  304. gateway.onDisconnect = () =>
  305. finish(completedEvidence ? undefined : new Error('Hermes 连接断开'))
  306. gateway.onEvent = (frame: GatewayFrame) => {
  307. if (settled || !runtimeId || frame.session_id !== runtimeId) return
  308. this.inspector?.record(owner,c.id,{direction:'event',method:frame.type,data:frame.payload,agentId:agent.id,runId:run.runId,taskId:run.conversationTaskId})
  309. const p = frame.payload ?? {},
  310. type = frame.type
  311. if(type==='computer.paused'||type==='computer.resumed'){const current=this.getWork(owner,run.id);current.status=type==='computer.paused'?'waiting':'running';this.saveWork(owner,current);return}
  312. if (type === 'message.delta') {
  313. resultMessage.content += String(p.text ?? p.delta ?? '')
  314. if (resultMessage.content.trim() && !NO_REPLY.startsWith(resultMessage.content.trim()) && !resultMessage.content.trim().startsWith('[[YAOYAO_')) resultMessage.visible = true
  315. }
  316. else if (type === 'reasoning.delta')
  317. resultMessage.reasoning += String(p.text ?? p.delta ?? '')
  318. else if (type === 'message.interim') {
  319. resultMessage.content += '\n\n'
  320. } else if (type.startsWith('tool.')) {
  321. resultMessage.visible = true
  322. const id = String(p.tool_id ?? p.id ?? ''),
  323. index = resultMessage.tools.findIndex((t) => t.id === id)
  324. const value = { ...p, id, status: type }
  325. if (index >= 0) resultMessage.tools[index] = { ...resultMessage.tools[index], ...value }
  326. else resultMessage.tools.push(value)
  327. } else if (
  328. ['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(
  329. type,
  330. )
  331. ) {
  332. const upstreamId = String(p.request_id ?? p.requestId ?? p.id ?? '')
  333. const previous = this.store.list<WorkspaceInteraction>(owner, 'interaction').find(i => {
  334. const b = this.store.get<{ taskId: string; upstreamId: string }>(owner, 'interaction-binding', i.id)
  335. return b?.taskId === run.id && b.upstreamId === upstreamId
  336. })
  337. if (previous?.resolved) return
  338. const interaction: WorkspaceInteraction = previous ?? {
  339. id: randomUUID(),
  340. conversationId: c.id,
  341. conversationTaskId: run.conversationTaskId,
  342. runId: run.runId,
  343. agentId: agent.id,
  344. kind: type.startsWith('approval') ? 'approval' : 'clarification',
  345. message: String(p.question ?? p.message ?? p.prompt ?? '需要确认'),
  346. choices: Array.isArray(p.choices) ? p.choices.map(String) : [],
  347. resolved: false,
  348. }
  349. this.store.put(owner, 'interaction', interaction.id, interaction)
  350. this.store.put(owner, 'interaction-binding', interaction.id, { key, upstreamId, taskId: run.id, conversationTaskId: run.conversationTaskId })
  351. this.store.event(owner, 'interaction.changed', interaction, c.id)
  352. const current = this.getWork(owner, run.id)
  353. current.hadInteraction = true
  354. current.status = 'waiting'
  355. this.saveWork(owner, current)
  356. this.notify(owner, c, this.store.require<Run>(owner, 'run', run.runId), undefined, interaction)
  357. } else if (['message.complete', 'run.completed'].includes(type)) {
  358. if (typeof p.text === 'string') resultMessage.content = p.text
  359. if (typeof p.reasoning === 'string') resultMessage.reasoning = p.reasoning
  360. if (p.status === 'interrupted') {
  361. const current = this.getWork(owner, run.id)
  362. current.status = 'interrupted'
  363. this.saveWork(owner, current)
  364. finish(new Error('已停止'))
  365. } else if (p.error || p.status === 'failed') {
  366. submitted = false
  367. finish(new HttpError(502, String(p.error ?? '运行失败'), 'run_failed'))
  368. } else if (!completing) {
  369. completedEvidence = true
  370. completing = true
  371. let timeout: ReturnType<typeof setTimeout>
  372. void Promise.race([
  373. gateway.rpc('session.usage', { session_id: runtimeId }),
  374. new Promise<undefined>((resolve) => {
  375. timeout = setTimeout(() => resolve(undefined), 1000)
  376. }),
  377. ])
  378. .then((usage) => {
  379. if (usage && !this.closing) {
  380. const used = usage.context_used ?? usage.used_tokens,
  381. limit = usage.context_max ?? usage.context_limit
  382. const contextKey = run.conversationTaskId ?? c.id,
  383. context = {
  384. ...usage,
  385. conversationTaskId: run.conversationTaskId,
  386. usedTokens: used,
  387. limitTokens: limit,
  388. percent:
  389. typeof used === 'number' && typeof limit === 'number' && limit > 0
  390. ? Math.round((used / limit) * 1000) / 10
  391. : undefined,
  392. }
  393. this.store.put(owner, 'context', contextKey, context)
  394. this.store.event(
  395. owner,
  396. 'context.changed',
  397. context,
  398. c.id,
  399. )
  400. }
  401. })
  402. .catch(() => {})
  403. .finally(() => {
  404. clearTimeout(timeout)
  405. finish()
  406. })
  407. }
  408. return
  409. } else if (['error', 'message.error', 'run.failed'].includes(type)) {
  410. submitted = false
  411. finish(new HttpError(502, String(p.message ?? p.error ?? '运行失败'), 'run_failed'))
  412. return
  413. } else if (['session.usage', 'usage.update', 'context.update'].includes(type)) {
  414. const context = { ...p, conversationTaskId: run.conversationTaskId }
  415. this.store.put(owner, 'context', run.conversationTaskId ?? c.id, context)
  416. this.store.event(owner, 'context.changed', context, c.id)
  417. } else if (type === 'session.info' && binding) {
  418. const storedId = p.stored_session_id ?? p.session_key
  419. if (typeof storedId === 'string' && storedId && storedId !== binding.storedId) {
  420. binding.aliases = [...new Set([...binding.aliases, binding.storedId, storedId])]
  421. binding.storedId = storedId
  422. this.store.put(owner, 'binding', key, binding)
  423. }
  424. }
  425. const flush = () => {
  426. clearTimeout(flushTimer)
  427. flushTimer = undefined
  428. if (settled || this.closing) return
  429. try {
  430. this.store.saveMessage(owner, resultMessage)
  431. lastFlush = Date.now()
  432. } catch (error) {
  433. finish(error instanceof Error ? error : new Error('无法保存流式消息'))
  434. }
  435. }
  436. const remaining = 100 - (Date.now() - lastFlush)
  437. if (remaining <= 0) flush()
  438. // A stream may pause after any chunk. Publish the latest text even when
  439. // no subsequent event arrives to trigger the next leading-edge flush.
  440. else if (flushTimer === undefined) flushTimer = setTimeout(flush, remaining)
  441. }
  442. try {
  443. await gateway.connect()
  444. this.requireAuthorization(owner, run.runId)
  445. this.nodes.requireSource(owner, agent)
  446. // Paired Web nodes enforce their own profile config at the destination.
  447. const cwd = recovering || target.pairedToken ? undefined
  448. : await configuredWorkingDirectory((path, options) => target.session.request(path, options), agent.profile)
  449. this.nodes.requireSource(owner, agent)
  450. const opened = binding?.storedId
  451. ? await gateway.rpc('session.resume', {
  452. profile: agent.profile,
  453. session_id: binding.storedId,
  454. omit_messages: true,
  455. ...(recovering&&target.runner?.computer?{recoverOnly:true}:{}),
  456. close_on_disconnect: false,
  457. })
  458. : await gateway.rpc('session.create', {
  459. profile: agent.profile,
  460. title: `Yaoyao ${c.id}${run.conversationTaskId ? ` / ${run.conversationTaskId}` : ''}`,
  461. source: 'yaoyao_workspace',
  462. ...(cwd ? { cwd } : {}),
  463. hidden: true,
  464. room_plumbing: true,
  465. close_on_disconnect: false,
  466. })
  467. runtimeId = String(opened.session_id ?? '')
  468. const storedId = String(
  469. opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? binding?.storedId ?? '',
  470. )
  471. if (
  472. !runtimeId ||
  473. !storedId ||
  474. (opened.info?.profile_name && opened.info.profile_name !== agent.profile)
  475. )
  476. throw new Error('Hermes 会话身份不匹配')
  477. binding = {
  478. runnerId: target.runner?.id,
  479. execution:agent.execution,
  480. computerEnvironmentId:agent.computerEnvironmentId,
  481. id: key,
  482. nodeId: agent.nodeId,
  483. remoteAgentId: agent.remoteAgentId,
  484. profile: agent.profile,
  485. storedId,
  486. runtimeId,
  487. aliases: [
  488. ...new Set([
  489. ...(binding?.aliases ?? []),
  490. ...(binding ? [binding.storedId] : []),
  491. storedId,
  492. ]),
  493. ],
  494. runId: run.runId,
  495. conversationTaskId: run.conversationTaskId,
  496. taskId: run.id,
  497. contextSeq: binding?.contextSeq ?? 0,
  498. messageId: resultMessage.id,
  499. }
  500. this.store.put(owner, 'binding', key, binding)
  501. this.live.set(key, { gateway, runtimeId, runId: run.runId, conversationTaskId: run.conversationTaskId, taskId: run.id, agentId: agent.id, done: finish })
  502. if (this.closing || this.getWork(owner, run.id).cancelRequested || this.getWork(owner, run.id).status === 'interrupted')
  503. throw new Error('运行已停止')
  504. if (recovering) {
  505. if (opened.running) {
  506. const current = this.getWork(owner, run.id)
  507. current.status = 'running'
  508. this.saveWork(owner, current)
  509. } else {
  510. const marker = `[yaoyao-run:${run.runId}:${resultMessage.id}]`
  511. let answer: { content?: string; text?: string } | undefined
  512. let found = false, seenLastEvent = false
  513. for (let page = 0; page < 20 && !found; page++) {
  514. const response = await target.session.request(`/api/sessions/${encodeURIComponent(storedId)}/messages`, {
  515. search: new URLSearchParams({ profile: agent.profile, limit: '500', offset: String(page * 500), order: 'latest', include_compacted: 'true' }),
  516. maxResponseBytes: 8 * 1024 * 1024,
  517. })
  518. if (response.status !== 200) throw new Error('无法核对历史')
  519. const history = JSON.parse(response.body.toString()).messages
  520. if (!Array.isArray(history)) throw new Error('历史响应无效')
  521. for (const item of [...history].reverse()) {
  522. if (item.role === 'user') {
  523. if (String(item.content ?? item.text).includes(marker)) { found = true; break }
  524. answer = undefined; seenLastEvent = false
  525. } else if (!seenLastEvent && ['assistant', 'tool'].includes(item.role)) {
  526. seenLastEvent = true
  527. const calls = item.tool_calls
  528. const hasCalls = Array.isArray(calls) ? calls.length > 0 : !!calls && calls !== '[]'
  529. if (item.role === 'assistant' && !hasCalls && !item.function_call && item.finish_reason !== 'tool_calls' && (item.content || item.text)) answer = item
  530. }
  531. }
  532. if (history.length < 500) break
  533. }
  534. if (!found || !answer) throw new Error('无法确认本轮的最终回复,正在核对原执行;不会重复提交')
  535. resultMessage.content = String(answer.content ?? answer.text)
  536. binding.contextSeq = Math.max(binding.contextSeq ?? 0, run.contextThroughSeq ?? 0)
  537. this.store.put(owner, 'binding', key, binding)
  538. finish()
  539. }
  540. } else {
  541. if (opened.running) throw new HttpError(409, '上游会话仍在运行', 'session_busy')
  542. this.nodes.requireSource(owner, agent)
  543. const team=agent.canManageTeam===true&&!this.store.require<Run>(owner,'run',run.runId).assignmentId
  544. const cloud=!!this.cloud?.selected(owner,agent)
  545. const desktop=this.desktopEnvironments?.selected(owner,agent),desktopEpoch=this.desktopEnvironments?.epoch??''
  546. if(team||cloud||desktop){
  547. if(team){
  548. const granted=this.getWork(owner,run.id);granted.teamManagementRevision=agent.revision;this.saveWork(owner,granted)
  549. await this.teamTools.requireAvailable(owner,agent)
  550. }
  551. if(desktop)await this.desktopEnvironments!.requireAvailable(owner,agent,target)
  552. if(cloud)await this.cloud!.requireAvailable(owner,agent,target)
  553. const assertActive=()=>{
  554. if(settled||this.closing||toolController.signal.aborted)throw new Error('运行已停止')
  555. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,this.store.require<Agent>(owner,'agent',agent.id))
  556. if(team)this.teamTools.assertTurn(owner,run.id)
  557. }
  558. toolLease=await createWorkspaceToolLease({
  559. target,profile:agent.profile,workId:run.id,signal:toolController.signal,
  560. session:()=>({runtimeId,storedId:binding!.storedId}),assertActive,
  561. catalog:()=>[...(team?this.teamTools.catalog(owner,run.id):[]),...(cloud?GROK_COMPUTER_TOOLS:[]),...(desktop?DESKTOP_ENVIRONMENT_TOOLS.filter(t=>desktop==='browser'||t.id!=='desktop_browser'):[])],
  562. call:async(toolId,args)=>{assertActive();return toolId.startsWith('desktop_')?this.desktopEnvironments!.call(owner,agent.id,toolId,args,toolController.signal,assertActive,desktop!,desktopEpoch):toolId.startsWith('cloud_computer_')?this.cloud!.call(owner,agent.id,toolId,args,toolController.signal):this.teamTools.call(owner,run.id,toolId,args)},
  563. onFailure:error=>{if(!settled)void gateway.rpc('session.interrupt',{session_id:runtimeId}).catch(()=>{}).finally(()=>finish(error))},
  564. })
  565. await toolLease.bind();if(settled)return await completion
  566. }
  567. await applyWorkingDirectory((method, params) => gateway.rpc(method, params), runtimeId, cwd, undefined, opened.info?.cwd)
  568. const trigger = this.store.require<Message>(owner, 'message', run.messageId)
  569. const attachmentRefs: string[] = []
  570. for (const file of trigger.attachments) {
  571. this.requireAuthorization(owner, run.runId)
  572. const record = this.files(owner,[file.id])[0]!
  573. const bytes = readFileSync(record.path).toString('base64')
  574. const attached = record.mimeType.startsWith('image/')
  575. ? await gateway.rpc('image.attach_bytes', {
  576. session_id: runtimeId,
  577. filename: record.name,
  578. content_base64: bytes,
  579. })
  580. : await gateway.rpc('file.attach', {
  581. session_id: runtimeId,
  582. name: record.name,
  583. data_url: `data:${record.mimeType};base64,${bytes}`,
  584. })
  585. if (attached.ref_text) attachmentRefs.push(String(attached.ref_text))
  586. }
  587. const members = run.turnConfiguration!.members
  588. const goal = run.conversationTaskId ? this.store.get<import('../shared/agentTasks.js').AgentGoal>(owner, 'goal', run.conversationTaskId) : undefined
  589. const assignmentId = this.store.require<Run>(owner, 'run', run.runId).assignmentId
  590. const rules = [
  591. `你是 ${agent.name}。以下是用户为这个独立机器人配置的角色与规则(版本 ${agent.revision}):\n${agent.remoteAgentId ? '配置由远端机器人管理。' : agent.instructions}`,
  592. c.kind === 'group' && Object.keys(c.memberRoles ?? {}).length
  593. ? `本群角色分工(仅在本群生效):\n${members.flatMap(member => {
  594. const role = c.memberRoles?.[member.id]
  595. return role ? [`@${member.name}:${role.name};${role.description}`] : []
  596. }).join('\n')}\n协作时使用上面的真实成员名称进行 @,不要使用职责名称代替成员名称。`
  597. : '',
  598. c.kind === 'group'
  599. ? `你正在群聊「${c.name}」发言。群成员:${members.map((a) => `@${a.name} (id=${a.id})`).join('、')}。\n群规则:${c.instructions}\n${c.mode === 'host' ? (agent.id === c.administratorId ? '你是管理员。必要时用精确 @成员名称 委派工作;收到结果后复核并给用户结论。任务完成时不要继续 @。' : '执行当前委派任务。公开给出结果,由管理员复核;不要安排其他成员。') : '按自己的职责回复,只在需要协作时 @成员。不要重复已完成的工作。'}`
  600. : '',
  601. run.requiredReply ? '你必须公开处理本次消息,直接回答、委派或澄清;禁止静默。管理员可按依赖一次 @一人,也可同时 @多人并行执行,整批结束后系统统一交回复核。' : run.replyMode === 'automatic' ? `你按自动参与配置收到消息。若与职责无关,禁止调用工具、禁止 @,完整答复只能是 ${NO_REPLY}。有关时正常回答。` : '',
  602. `本轮用户指定成员:${this.store.require<Run>(owner, 'run', run.runId).mentionIds.map(id => members.find(a => a.id === id)).filter(Boolean).map(a => '@' + a!.name).join('、') || '未指定'}`,
  603. '角色规则不赋予额外工具权限;仍遵守基础 Hermes 的工具和安全约束。',
  604. this.store.require<Run>(owner, 'run', run.runId).internalInstruction || '',
  605. goal ? `当前团队目标 ID:${goal.id}。目标:${goal.objective.slice(0,8000)}\n验收要求:${goal.acceptanceCriteria.join(';')}\n${assignmentId ? `你在执行子任务 ${assignmentId},请完成分派并提交结果,不要扩大团队或再次委派。` : '优先使用 workspace_assign_task 进行有依赖和验收要求的结构化分派;成员结果需要通过 workspace_review_assignment 复核。最终使用 workspace_finish_team_task 记录完成、受阻或等待用户。不要将一次模型回复结束当作目标完成。'}` : '',
  606. agent.temporaryGoalId ? `你是当前任务的临时助手,任务 ID:${agent.temporaryGoalId}。仅处理分派工作,使用 computer_export 回传产物。任务结束后会退役;不要创建团队或改变自身权限。` : '',
  607. team ? TEAM_TOOL_RULES : '',
  608. desktop ? DESKTOP_ENVIRONMENT_RULES : '',
  609. cloud ? GROK_COMPUTER_RULES : '',
  610. `[yaoyao-run:${run.runId}:${resultMessage.id}]`,
  611. ]
  612. .filter(Boolean)
  613. .join('\n\n')
  614. const text = c.kind === 'group' ? this.contextText(owner, c, agent, run, binding.contextSeq ?? 0, movedRunner)
  615. : movedRunner ? `执行节点已切换。以下是原会话的近期记录,旧路径和执行状态需要在当前节点重新核实;不要重新执行已完成的操作。\n\n${this.contextText(owner,c,agent,run,0,true)}` : trigger.content
  616. const admission = this.getWork(owner, run.id)
  617. if (!this.store.taskMemberIds(owner,this.store.require<Conversation>(owner,'conversation',c.id),run.conversationTaskId).includes(agent.id)) {
  618. admission.status = 'interrupted'; admission.error = '执行前成员已移除'; this.saveWork(owner, admission)
  619. throw new Error('执行前成员已移除')
  620. }
  621. this.nodes.requireSource(owner, agent)
  622. this.requireAuthorization(owner, run.runId)
  623. if (admission.cancelRequested || admission.status === 'interrupted') throw new Error('运行已停止')
  624. admission.contextThroughSeq = run.contextThroughSeq ?? run.triggerSeq
  625. admission.submitted = true
  626. this.saveWork(owner, admission)
  627. submitted = true
  628. try {
  629. await gateway.rpc('prompt.submit', {
  630. session_id: runtimeId,
  631. ...(target.runner?.computer?{workMarker:`[yaoyao-run:${run.runId}:${resultMessage.id}]`}:{}),
  632. text: `${rules}\n\n${text}\n${attachmentRefs.join('\n')}`,
  633. })
  634. this.store.remove(owner,'binding-reset',key)
  635. binding.contextSeq = Math.max(binding.contextSeq ?? 0, admission.contextThroughSeq)
  636. this.store.put(owner, 'binding', key, binding)
  637. } catch (error) {
  638. // A JSON-RPC error is a definitive rejection, not a lost receipt.
  639. if (error instanceof HttpError && ['gateway_rejected','runner_command_not_admitted'].includes(error.code??'')) { submitted = false; const current = this.getWork(owner, run.id); current.submitted = false; this.saveWork(owner, current) }
  640. throw error
  641. }
  642. }
  643. return await completion
  644. } catch (error) {
  645. finish(error instanceof Error ? error : new Error('执行失败'))
  646. return await completion
  647. }
  648. }
  649. private requireAuthorization(owner: string, runId: string): void {
  650. const run=this.store.require<Run>(owner,'run',runId)
  651. if(!this.userActive(owner)||(run.authorizationVersion!==undefined&&run.authorizationVersion!==this.authorizationVersion(owner)))
  652. throw new HttpError(403,'本轮账号授权已失效','run_authorization_revoked')
  653. }
  654. private contextText(owner: string, c: Conversation, agent: Agent, work: Work, after: number, includeOwn = false): string {
  655. const rootTrigger = this.store.require<Message>(owner, 'message', work.messageId)
  656. const roots = new Map(this.store.list<Run>(owner, 'run').filter(r => r.conversationId === c.id && r.conversationTaskId === work.conversationTaskId).map(r => [r.id, this.store.get<Message>(owner, 'message', r.messageId)?.seq ?? 0]))
  657. const history = this.store.messages(owner, c.id, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, true, work.conversationTaskId)
  658. const unfinished = history.find(m => m.seq > after && m.seq <= work.triggerSeq && (['queued', 'streaming', 'uncertain'].includes(m.status) || (m.runId && (roots.get(m.runId) ?? 0) > rootTrigger.seq)))
  659. work.contextThroughSeq = unfinished ? unfinished.seq - 1 : work.triggerSeq
  660. const eligible = history
  661. .filter(m => m.seq > after && m.seq <= work.triggerSeq && m.visible !== false && ['complete', 'failed', 'interrupted'].includes(m.status)
  662. && (includeOwn || !(m.role === 'assistant' && m.agentId === agent.id)) && (!m.runId || (roots.get(m.runId) ?? 0) <= rootTrigger.seq))
  663. const selected: string[] = []
  664. let size = 0, omitted = 0
  665. for (const message of [...eligible].reverse()) {
  666. const files = message.attachments.map(f => `[附件 ${f.name}](${f.sourcePath || `/api/app/files/${f.id}/download`})`).join('\n')
  667. const content = message.content.length > 24_000 ? message.content.slice(0, 12_000) + '\n[内容过长,保留首尾片段]\n' + message.content.slice(-12_000) : message.content
  668. const reasoning = message.reasoning ? `\n思考摘要:${message.reasoning.slice(0, 2000)}` : ''
  669. const tools = [...new Set(message.tools.map(t => String(t.name ?? t.tool_name ?? '')).filter(name => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,119}$/.test(name)))].slice(0, 16)
  670. const row = `${message.role === 'user' ? '用户' : message.agentName ?? '系统'}(${message.status}):${content}${reasoning}${tools.length ? `\n使用工具:${tools.join('、')}` : ''}${message.error ? `\n错误:${message.error}` : ''}${files ? '\n' + files : ''}`
  671. if (selected.length >= 50 || size + row.length > 30_000) { omitted++; continue }
  672. selected.unshift(row); size += row.length
  673. }
  674. // Preserve a large trigger as a bounded excerpt rather than silently losing it.
  675. if (!selected.length && eligible.length) selected.push(eligible.at(-1)!.content.slice(-30_000))
  676. const batch = work.reviewOf ? this.works(owner, work.runId).filter(t => t.batchId === work.reviewOf).map(t => `${this.store.get<Agent>(owner, 'agent', t.agentId)?.name ?? t.agentId}:${t.status}${t.error ? `;${t.error}` : ''}`).join('\n') : ''
  677. return `${batch ? `本批次执行结果:\n${batch}\n\n` : ''}${omitted ? `较早上下文有 ${omitted} 条因长度限制省略,请勿假定已完整读取。\n\n` : ''}${selected.join('\n\n')}`
  678. }
  679. private resolveInteractions(owner: string, taskId: string): void {
  680. for (const interaction of this.store.list<WorkspaceInteraction>(owner, 'interaction')) {
  681. const binding = this.store.get<{ taskId?: string }>(owner, 'interaction-binding', interaction.id)
  682. if (binding?.taskId === taskId && !interaction.resolved) {
  683. interaction.resolved = true
  684. this.store.put(owner, 'interaction', interaction.id, interaction)
  685. this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId)
  686. }
  687. }
  688. }
  689. async respond(owner: string, id: string, answer: string): Promise<void> {
  690. type Reply = WorkspaceInteraction & { answer?: string; responseState?: 'sending' | 'uncertain' | 'sent' }
  691. const interaction = this.store.require<Reply>(owner, 'interaction', id)
  692. this.requireAuthorization(owner,interaction.runId)
  693. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', interaction.agentId))
  694. if (interaction.resolved) {
  695. if (interaction.answer && interaction.answer !== answer) throw new HttpError(409, '该请求已使用其他答复完成', 'interaction_answer_conflict')
  696. return
  697. }
  698. if (interaction.responseState === 'sending' || interaction.responseState === 'uncertain') throw new HttpError(409, '答复状态待确认,请核对原请求', 'interaction_uncertain')
  699. const binding = this.store.require<{ key: string; upstreamId: string; taskId: string }>(owner, 'interaction-binding', id)
  700. const live = this.live.get(binding.key)
  701. if (!live || live.taskId !== binding.taskId || live.runId !== interaction.runId) throw new HttpError(409, '请先恢复此轮连接', 'interaction_offline')
  702. if (interaction.kind === 'approval' && !['once', 'session', 'always', 'deny', 'allow', 'approve'].includes(answer)) throw new HttpError(400, '审批选项无效', 'invalid_approval')
  703. interaction.answer = answer; interaction.responseState = 'sending'
  704. this.store.put(owner, 'interaction', id, interaction)
  705. try {
  706. await live.gateway.rpc(interaction.kind === 'approval' ? 'approval.respond' : 'clarify.respond', {
  707. session_id: live.runtimeId, request_id: binding.upstreamId,
  708. ...(interaction.kind === 'approval' ? { choice: answer } : { answer }),
  709. })
  710. } catch (error) {
  711. const latest = this.store.require<Reply>(owner, 'interaction', id)
  712. if (!latest.resolved) {
  713. latest.responseState = error instanceof HttpError && error.code === 'gateway_rejected' ? undefined : 'uncertain'
  714. this.store.put(owner, 'interaction', id, latest)
  715. }
  716. throw error
  717. }
  718. interaction.resolved = true; interaction.responseState = 'sent'
  719. this.store.put(owner, 'interaction', id, interaction)
  720. this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId)
  721. const current = this.getWork(owner, binding.taskId)
  722. if (current.status === 'waiting') { current.status = 'running'; this.saveWork(owner, current) }
  723. }
  724. protected async interruptTurn(owner: string, work: Work): Promise<void> {
  725. const key = this.bindingKey(work.conversationId, work.conversationTaskId, work.agentId)
  726. const live = this.live.get(key)
  727. if (live?.taskId === work.id) {
  728. await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId })
  729. const current = this.getWork(owner, work.id)
  730. if (['complete', 'failed', 'interrupted'].includes(current.status)) return
  731. current.status = 'interrupted'; current.error = '已停止'
  732. this.saveWork(owner, current)
  733. if(current.currentMessageId){const message=this.store.require<Message>(owner,'message',current.currentMessageId);message.status='interrupted';message.error='已停止';this.store.saveMessage(owner,message)}
  734. live.done(new Error('已停止'))
  735. } else {
  736. const binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
  737. if (work.submitted) {
  738. if (!binding || binding.taskId !== work.id) throw new Error('无法确认待停止成员的会话身份')
  739. const target=binding.remoteAgentId||binding.execution==='computer'?this.nodes.targetForAgent(owner,{...binding,id:work.agentId}):this.nodes.target(owner,binding.nodeId)
  740. if(binding.runnerId!==target.runner?.id)throw new Error('执行节点已变化,无法确认原任务已停止')
  741. const gateway = new WorkspaceGateway(target,{workId:work.id,cleanupOnly:true,sessionId:binding.storedId,authorize:()=>{const current=this.store.get<WorkspaceBinding>(owner,'binding',key);if(current?.taskId!==work.id||current.storedId!==binding.storedId)throw new Error('原会话绑定已改变')}})
  742. try {
  743. await gateway.connect()
  744. const opened = await gateway.rpc('session.resume', { profile: binding.profile, session_id: binding.storedId, omit_messages: true, close_on_disconnect: false,...(binding.execution==='computer'?{recoverOnly:true}:{}) })
  745. if (opened.running) await gateway.rpc('session.interrupt', { session_id: opened.session_id })
  746. } finally { gateway.close() }
  747. }
  748. const current = this.getWork(owner, work.id)
  749. current.status = 'interrupted'; current.error = '已停止'
  750. this.saveWork(owner, current)
  751. if (current.currentMessageId) {
  752. const message = this.store.require<Message>(owner, 'message', current.currentMessageId)
  753. message.status = 'interrupted'; this.store.saveMessage(owner, message)
  754. }
  755. }
  756. this.resolveInteractions(owner, work.id)
  757. }
  758. override async stopTask(owner: string, conversationId: string, taskId: string, visited = new Set<string>()): Promise<void> {
  759. const key = `${owner}:${taskId}`
  760. if (visited.has(key)) return
  761. visited.add(key)
  762. this.tasks.cancel(owner, taskId)
  763. await Promise.all([super.stopTask(owner, conversationId, taskId), this.tasks.cancelOrigin(owner, conversationId, taskId, visited)])
  764. }
  765. override async stopConversation(owner: string, conversationId: string): Promise<void> {
  766. for (const task of this.store.list<import('../shared/workspace.js').WorkspaceTask>(owner, 'conversation-task'))
  767. if (task.conversationId === conversationId) this.tasks.cancel(owner, task.id)
  768. await Promise.all([super.stopConversation(owner, conversationId), this.tasks.cancelOrigin(owner, conversationId)])
  769. }
  770. close(): void {
  771. this.tasks.close()
  772. this.closeScheduler()
  773. for (const live of [...this.live.values()]) live.done(new Error('服务关闭'))
  774. this.live.clear()
  775. }
  776. }