workspaceRuntime.ts 58 KB

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