workspaceRuntime.ts 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. import {DESKTOP_ENVIRONMENT_TOOLS,DESKTOP_ENVIRONMENT_RULES,SERVER_COMPUTER_RULES,DESKTOP_FILE_TOOL_IDS,DESKTOP_FILE_TRANSFER_RULES,type DesktopEnvironments} from './desktopEnvironments.js'
  2. import {GROK_COMPUTER_TOOLS,grokComputerRules,type GrokCloud} from './grokCloud.js'
  3. import {VM_COMPUTER_TOOLS,VM_COMPUTER_RULES,VmToolSession} from './vmComputer.js'
  4. import { randomUUID } from 'node:crypto'
  5. import { readFileSync } from 'node:fs'
  6. import { z } from 'zod'
  7. import { WorkspaceStore, parse } from './workspaceStore.js'
  8. import { WorkspaceNodes, WorkspaceGateway, type GatewayFrame } from './workspaceGateway.js'
  9. import { HttpError } from './errors.js'
  10. import { applyWorkingDirectory, configuredWorkingDirectory } from './sessionWorkingDirectory.js'
  11. import {type StoredWorkspaceFile} from './workspaceAssets.js'
  12. import { UploadStore } from './uploads.js'
  13. import type {
  14. WorkspaceAgent as Agent,
  15. WorkspaceConversation as Conversation,
  16. WorkspaceMessage as Message,
  17. WorkspaceRun,
  18. WorkspaceInteraction,
  19. WorkspaceAgentUsageSummary,
  20. } from '../shared/workspace.js'
  21. import { personaSection } from '../shared/workspace.js'
  22. import { readHostTools } from './hostToolSettings.js'
  23. import { resolveBotModelSettings, applyBotModelSettings, botModelTarget, BotModelConfirmationError } from './botModelSettings.js'
  24. function globalComputers(home: string) {
  25. try { return readHostTools(home) }
  26. catch { return { denyServerTools: false, approvalPolicy: 'ask' as const, scriptMachine: false, serverComputer: false, vm: false, cloud: false } }
  27. }
  28. function estimateTokens(text: string): number {
  29. let units = 0
  30. for (const ch of text) units += (ch.codePointAt(0) ?? 0) > 0xff ? 1 : 0.25
  31. return Math.ceil(units)
  32. }
  33. function environmentMentions(text: string, hostNames: string[]) {
  34. const cloud = /云虚拟机|云电脑|云服务器|cloud_computer|Grok/i.test(text)
  35. const vm = /虚拟环境|虚拟机|\bVM\b/i.test(text) || /computer_(desktop|shell|action|read_file|write_file)/.test(text)
  36. const named = hostNames.some(name => name.length >= 2 && name !== '本机' && text.includes(name))
  37. const script = /脚本机|客户端|本机/.test(text) || named
  38. const server = /服务器|本机/.test(text) || (/desktop_/.test(text) && !script)
  39. const desktop = server || script || /desktop_/.test(text)
  40. return { desktop, server, script, vm, cloud }
  41. }
  42. import { WorkspaceScheduler, type Work, NO_REPLY, HOST_FALLBACK, WORKSPACE_CONCURRENCY_LIMIT, RESOURCE_WAIT_CODES } from './workspaceScheduler.js'
  43. import type { WorkspacePlugins, OpenBotPlugins } from './botPlugins/workspacePlugins.js'
  44. import { mentionedAgents } from './workspaceMentions.js'
  45. import { WorkspaceTeamTools, TEAM_TOOL_RULES } from './workspaceTeamTools.js'
  46. import { createWorkspaceToolLease, type WorkspaceToolLease } from './workspaceToolLease.js'
  47. import { WorkspaceTaskCoordinator } from './taskCoordinator.js'
  48. import { isDiscussion, discussionRounds } from './workspaceDiscussion.js'
  49. import { WorkspaceKnowledge } from './workspaceKnowledge.js'
  50. import type { OpenVikingService } from './openVikingService.js'
  51. import { WorkspaceCollaboration } from './workspaceCollaboration.js'
  52. import { WorkspaceKnowledgeTools, BOT_KNOWLEDGE_RULES } from './workspaceKnowledgeTools.js'
  53. export { mentionedAgents } from './workspaceMentions.js'
  54. type Run = WorkspaceRun
  55. export interface WorkspaceBinding {
  56. memoryVersion?: string
  57. runnerId?: string
  58. execution?:string
  59. vmExecution?:Agent["vmExecution"]
  60. hermesComputer?:boolean
  61. computerEnvironmentId?:string
  62. remoteAgentId?: string
  63. id: string
  64. nodeId: string
  65. profile: string
  66. storedId: string
  67. runtimeId: string
  68. aliases: string[]
  69. runId: string
  70. messageId: string
  71. conversationTaskId?: string
  72. taskId?: string
  73. contextSeq?: number
  74. }
  75. interface LiveTurn {
  76. gateway: WorkspaceGateway
  77. runtimeId: string
  78. runId: string
  79. agentId: string
  80. conversationTaskId?: string
  81. taskId: string
  82. done(error?: Error): void
  83. }
  84. const deviceHostId = z.union([
  85. z.literal('local'),
  86. z.string().uuid(),
  87. ])
  88. export const sendInput = z
  89. .object({
  90. requestId: z.string().uuid(),
  91. content: z.string().max(65_536).default(''),
  92. taskId: z.string().uuid().optional(),
  93. mode: z.enum(['chat', 'goal']).optional(),
  94. rounds: z.number().int().min(1).max(12).optional(),
  95. coordinatorId: z.string().uuid().optional(),
  96. projectId: z.string().min(1).max(100).nullable().optional(),
  97. mentionIds: z.array(z.string().uuid()).max(8).default([]),
  98. fileIds: z.array(z.string().uuid()).max(8).default([]),
  99. /** Desktop host the client is messaging from: 'local' or paired host uuid. */
  100. deviceHost: deviceHostId.nullish(),
  101. })
  102. .strict()
  103. .refine((b) => b.content.trim() || b.fileIds.length, '请输入消息或添加附件')
  104. export class WorkspaceRuntime extends WorkspaceScheduler {
  105. readonly knowledge: WorkspaceKnowledge
  106. readonly openViking?: OpenVikingService
  107. readonly collaboration: WorkspaceCollaboration
  108. readonly knowledgeTools: WorkspaceKnowledgeTools
  109. onMemoryCandidate: (owner: string, run: Run) => void = () => {}
  110. plugins?: WorkspacePlugins
  111. assertCanSubmit:()=>void=()=>{}
  112. get idleForUpdate(): boolean {
  113. 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()
  114. }
  115. desktopEnvironments?:DesktopEnvironments
  116. cloud?:GrokCloud
  117. /** Wired to the runner hub: false degrades envs VM turns to profile sessions. */
  118. computerAvailable?:(owner:string,agent:Agent)=>boolean
  119. inspector?:import('./workspaceInspector.js').WorkspaceInspector
  120. private live = new Map<string, LiveTurn>()
  121. readonly teamTools: WorkspaceTeamTools
  122. readonly tasks: WorkspaceTaskCoordinator
  123. retireHelper:(owner:string,helper:Agent)=>Promise<void>=async()=>{throw new Error('电脑清理服务未连接')}
  124. publishArtifact:(owner:string,message:Message,agent:Agent,name:string,bytes:Buffer)=>import('../shared/workspace.js').WorkspaceFile=()=>{throw new Error('产物服务未初始化')}
  125. onTeamCreated: (owner: string, team: Conversation) => void = () => {}
  126. constructor(store: WorkspaceStore, readonly nodes: WorkspaceNodes, readonly uploads: UploadStore, userActive: (owner: string) => boolean = () => true,
  127. readonly authorizationVersion: (owner: string) => number = () => 0, openViking?: OpenVikingService) {
  128. super(store, userActive)
  129. this.openViking = openViking
  130. this.teamTools = new WorkspaceTeamTools(store, nodes, this)
  131. this.tasks = new WorkspaceTaskCoordinator(store, this)
  132. this.knowledge = new WorkspaceKnowledge(store.home, store, openViking)
  133. this.collaboration = new WorkspaceCollaboration(store, this)
  134. this.knowledgeTools = new WorkspaceKnowledgeTools(this)
  135. this.onRunSettled = (owner, run) => {
  136. this.collaboration.settled(owner, run)
  137. if (run.status === 'complete' && (!run.triggerKind || run.triggerKind === 'peer')) queueMicrotask(() => { if (!this.closing) this.onMemoryCandidate(owner, run) })
  138. }
  139. }
  140. async bindNewAgent(owner: string, id: string): Promise<void> {
  141. if (!this.openViking?.enabled) return
  142. await this.openViking.ensureUser(owner, { id, temporaryGoalId: undefined })
  143. }
  144. async cleanupAgent(owner: string, id: string): Promise<void> {
  145. if (!this.openViking) return
  146. await this.openViking.removeUser(owner, { id, temporaryGoalId: undefined })
  147. }
  148. send(owner: string, conversationId: string, input: unknown): Run {
  149. return this.submit(owner, conversationId, input)
  150. }
  151. async botCapabilities(owner: string, agent: Agent, target = this.nodes.target(owner, agent.nodeId)): Promise<{ tools: boolean; memory: boolean; extraction: boolean }> {
  152. try {
  153. const response = await target.session.request('/api/plugins/yaoyao-bot-bridge/capabilities', { search: new URLSearchParams({ profile: agent.profile }) })
  154. const value = JSON.parse(response.body.toString())
  155. const tools = response.status === 200 && value.ready === true && value.native_tools === true && value.in_process === true
  156. return { tools, memory: tools && value.memory_isolation === true, extraction: value.memory_extraction === true }
  157. } catch (error) {
  158. if (error instanceof HttpError && RESOURCE_WAIT_CODES.has(error.code ?? '')) throw error
  159. return { tools: false, memory: false, extraction: false }
  160. }
  161. }
  162. async stopPeerRun(owner: string, id: string): Promise<void> { await super.stop(owner, id) }
  163. async preemptPeerWork(owner: string, agentId: string, exceptRunId: string): Promise<void> {
  164. 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))]
  165. for (const id of ids) if (this.store.get<Run>(owner, 'run', id)?.triggerKind) await super.stop(owner, id).catch(() => {})
  166. }
  167. override async stop(owner: string, id: string): Promise<void> {
  168. const root = this.store.require<Run>(owner, 'run', id)
  169. await this.collaboration.stopFor(owner, chain => chain.rootRunId === id || chain.id === root.collaborationChainId)
  170. await super.stop(owner, id)
  171. }
  172. /** Server-owned provenance. This is never exposed as a model-supplied identity. */
  173. dispatch(owner: string, conversationId: string, input: unknown, source: {
  174. agentId: string; assignmentId?: string; targetAgentId?: string; kind: NonNullable<Run['triggerKind']>; instruction?: string; taskReference?: {conversationId:string;taskId:string}
  175. peerMessageId?: string; collaborationChainId?: string; priority?: boolean; projectId?: string; deviceHost?: string
  176. }): Run {
  177. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', source.agentId))
  178. return this.submit(owner, conversationId, input, source)
  179. }
  180. 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}})}
  181. private submit(owner: string, conversationId: string, input: unknown, source?: {
  182. agentId: string; assignmentId?: string; targetAgentId?: string; kind: NonNullable<Run['triggerKind']>; instruction?: string; taskReference?: {conversationId:string;taskId:string}
  183. peerMessageId?: string; collaborationChainId?: string; priority?: boolean; projectId?: string; deviceHost?: string
  184. }): Run {
  185. if (!this.userActive(owner)) throw new HttpError(403,'账号授权已失效','account_inactive')
  186. this.assertCanSubmit()
  187. const body = parse(sendInput, input)
  188. for (const id of this.store.require<Conversation>(owner, 'conversation', conversationId).memberIds)
  189. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', id))
  190. const result = this.store.command(owner, body.requestId, { conversationId, ...body, ...(source ? { source } : {}) }, () => {
  191. const c = this.store.require<Conversation>(owner, 'conversation', conversationId)
  192. if (c.archived) throw new HttpError(409, '聊天已归档', 'conversation_archived')
  193. const projectId = source?.kind === 'peer' ? source.projectId : c.kind === 'group' ? c.projectId : body.projectId ?? undefined
  194. if (projectId) for (const id of source?.targetAgentId ? [source.targetAgentId] : c.memberIds) this.knowledge.requireProjectMember(owner, projectId, id)
  195. const conversationTask = this.store.resolveTask(owner, conversationId, body.taskId),
  196. conversationTaskId = conversationTask?.id
  197. if (conversationTaskId) {
  198. const alreadyActive = this.store.list<Run>(owner, 'run').some(run => run.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status))
  199. if (!alreadyActive && this.store.activeTaskCount(owner, conversationId) >= WORKSPACE_CONCURRENCY_LIMIT)
  200. throw new HttpError(409, `最多同时运行 ${WORKSPACE_CONCURRENCY_LIMIT} 个任务`, 'workspace_task_concurrency_limit')
  201. }
  202. if (body.mentionIds.some((a) => !this.store.taskMemberIds(owner,c,conversationTaskId).includes(a)))
  203. throw new HttpError(400, '只能 @ 群内成员', 'invalid_mentions')
  204. const records = this.files(owner,body.fileIds)
  205. const now = Date.now(),
  206. runId = randomUUID(),
  207. agents = this.store.taskMemberIds(owner,c,conversationTaskId).map((id) => this.store.require<Agent>(owner, 'agent', id))
  208. let goal = conversationTaskId ? this.store.get<import('../shared/agentTasks.js').AgentGoal>(owner, 'goal', conversationTaskId) : undefined
  209. if (body.mode === 'goal') {
  210. if (source || c.kind !== 'group' || !conversationTask || !body.content.trim())
  211. throw new HttpError(400, '请在群聊中说明需要交付的结果', 'goal_request_invalid')
  212. if (goal) throw new HttpError(409, '当前话题已有目标,请继续原目标或新建话题', 'goal_exists')
  213. if (body.coordinatorId) {
  214. if (!c.memberIds.includes(body.coordinatorId)) throw new HttpError(400, '负责人需要是群成员', 'invalid_members')
  215. c.administratorId = body.coordinatorId
  216. }
  217. const coordinator = this.store.require<Agent>(owner, 'agent', c.administratorId)
  218. if (coordinator.temporaryGoalId || coordinator.archived || coordinator.remoteAgentId)
  219. throw new HttpError(403, '负责人需要是本机上未归档的 Bot', 'goal_forbidden')
  220. if (body.coordinatorId) this.store.put(owner, 'conversation', c.id, c)
  221. if (this.store.list<Run>(owner, 'run').some(r => r.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(r.status)))
  222. throw new HttpError(409, '请等待当前回复结束后再启动目标', 'goal_busy')
  223. goal = this.tasks.begin(owner, conversationTask, coordinator, body.content.trim(),
  224. { conversationId, conversationTaskId, runId, agentId: coordinator.id })
  225. }
  226. const mentions = [
  227. ...new Set(
  228. [...body.mentionIds, ...mentionedAgents(body.content, agents)],
  229. ),
  230. ]
  231. const message: Message = {
  232. id: randomUUID(),
  233. conversationId,
  234. conversationTaskId,
  235. seq: 0,
  236. role: source ? 'system' : 'user',
  237. peerMessageId: source?.peerMessageId,
  238. ...(source?.taskReference ? {taskReference:source.taskReference} : {}),
  239. ...(source ? { agentId: source.agentId, agentName: this.store.require<Agent>(owner, 'agent', source.agentId).name } : {}),
  240. ...((source ? source.deviceHost : body.deviceHost) ? { deviceHost: (source ? source.deviceHost : body.deviceHost)! } : {}),
  241. content: body.content.trim(),
  242. reasoning: '',
  243. runId,
  244. status: 'complete',
  245. attachments: records.map((f) => ({
  246. id: f.id,
  247. name: f.name,
  248. mimeType: f.mimeType,
  249. size: f.size,
  250. sender: f.sender,
  251. createdAt: now,
  252. })),
  253. tools: [],
  254. createdAt: now,
  255. }
  256. this.store.saveMessage(owner, message)
  257. for (const file of records) {
  258. const existing = this.store.get<Record<string, unknown>>(owner, 'file', file.id)
  259. if (existing && !existing.messageId)
  260. this.store.put(owner, 'file', file.id, {
  261. ...existing,
  262. conversationId,
  263. messageId: message.id,
  264. })
  265. }
  266. const run: Run = {
  267. id: runId,
  268. conversationId,
  269. conversationTaskId,
  270. messageId: message.id,
  271. ...((source ? source.deviceHost : body.deviceHost) ? { deviceHost: (source ? source.deviceHost : body.deviceHost)! } : {}),
  272. mentionIds: mentions,
  273. activeAgentId: c.administratorId,
  274. status: 'queued',
  275. round: 0,
  276. createdAt: now,
  277. updatedAt: now,
  278. authorizationVersion: this.authorizationVersion(owner),
  279. projectId,
  280. peerMessageId: source?.peerMessageId,
  281. collaborationChainId: source?.collaborationChainId,
  282. priority: source?.priority,
  283. ...(source ? { assignmentId: source.assignmentId, targetAgentId: source.targetAgentId, triggerKind: source.kind, internalInstruction: source.instruction } : {}),
  284. ...(source?.kind !== 'peer' && goal && ['running', 'review', 'waiting'].includes(goal.status) ? { goalId: goal.id, targetAgentId: source?.targetAgentId ?? goal.coordinatorId } : {}),
  285. }
  286. if (isDiscussion(c) && !run.goalId && !run.assignmentId && !source?.targetAgentId) run.discussion = { memberIds: mentions.length ? mentions : [...c.memberIds], rounds: discussionRounds(body.content, body.rounds) }
  287. this.admit(owner, run, c, message)
  288. this.uploads.markReferenced(body.fileIds, owner)
  289. return run
  290. })
  291. this.wake()
  292. return this.store.require<Run>(owner, 'run', result.id)
  293. }
  294. protected async performTurn(
  295. owner: string,
  296. c: Conversation,
  297. agent: Agent,
  298. run: Work,
  299. recovering = false,
  300. ): Promise<Message> {
  301. this.requireAuthorization(owner, run.runId)
  302. this.store.requireAgentTask(owner,agent,c.id,run.conversationTaskId)
  303. this.nodes.requireSource(owner, agent)
  304. if (agent.remoteAgentId) throw new HttpError(410, '远程机器人已停用', 'remote_agent_removed')
  305. const key = this.bindingKey(c.id, run.conversationTaskId, agent.id),
  306. chatExecution = 'profile',
  307. target = this.nodes.target(owner, agent.nodeId)
  308. let vmTools: VmToolSession | undefined
  309. const gateway = new WorkspaceGateway(target,{workId:run.id,publishArtifact:async(name,bytes)=>{
  310. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,agent)
  311. const file=this.publishArtifact(owner,resultMessage,agent,name,bytes)
  312. if(!resultMessage.attachments.some(item=>item.id===file.id))resultMessage.attachments.push(file)
  313. this.store.saveMessage(owner,resultMessage)
  314. return {...file,url:`/api/app/files/${file.id}/download`}
  315. },authorize:()=>{
  316. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,agent)
  317. 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)
  318. 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')
  319. }})
  320. gateway.onTrace=entry=>this.inspector?.record(owner,c.id,{...entry,agentId:agent.id,runId:run.runId,taskId:run.conversationTaskId})
  321. const botCapabilities = await this.botCapabilities(owner, agent, target)
  322. const dispatchedVm = globalComputers(this.store.home).vm && botCapabilities.tools && !agent.remoteAgentId
  323. const root = this.store.require<Run>(owner, 'run', run.runId)
  324. if (root.peerMessageId && !recovering) {
  325. const peer = this.store.require<import('../shared/workspaceKnowledge.js').WorkspacePeerMessage>(owner, 'peer-message', root.peerMessageId)
  326. const sender = this.store.require<Agent>(owner, 'agent', peer.fromAgentId)
  327. if (sender.archived || peer.status === 'stopped') throw new HttpError(403, 'Bot 协作权限已撤销', 'collaboration_forbidden')
  328. this.nodes.requireSource(owner, sender)
  329. }
  330. const memory = botCapabilities.memory && !recovering ? await this.knowledge.context(owner, agent.id, root.projectId) : { text: '', version: 'unsupported' }
  331. const memoryStatus = botCapabilities.memory ? 'ready' : 'upgrade_required'
  332. if (agent.memoryStatus !== memoryStatus) {
  333. agent = { ...agent, memoryStatus }
  334. this.store.put(owner, 'agent', agent.id, agent)
  335. this.store.event(owner, 'agent.changed', this.store.agentSummary(agent))
  336. }
  337. let binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
  338. const memoryChanged = !recovering && !!binding?.memoryVersion && binding.memoryVersion !== memory.version
  339. const movedRunner=memoryChanged||!!this.store.get(owner,'binding-reset',key)||!!binding&&(binding.runnerId!==target.runner?.id||(binding.execution??'profile')!==chatExecution||!!binding.hermesComputer!==!!target.runner?.hermesComputer)
  340. if(movedRunner) {
  341. if(recovering)throw new HttpError(409,'执行节点已变化,不能在另一节点重放原执行','runner_target_changed')
  342. binding=undefined
  343. }
  344. let message =
  345. run.currentMessageId
  346. ? this.store.require<Message>(owner, 'message', run.currentMessageId)
  347. : undefined
  348. if (!message) {
  349. message = {
  350. id: randomUUID(),
  351. conversationId: c.id,
  352. conversationTaskId: run.conversationTaskId,
  353. seq: 0,
  354. role: 'assistant',
  355. execution:chatExecution,
  356. agentId: agent.id,
  357. agentName: agent.name,
  358. content: '',
  359. reasoning: '',
  360. status: 'streaming',
  361. runId: run.runId,
  362. taskId: run.id,
  363. visible: run.replyMode !== 'automatic' || run.requiredReply,
  364. tools: [],
  365. attachments: [],
  366. createdAt: Date.now(),
  367. }
  368. run.currentMessageId = message.id
  369. this.store.atomic(() => {
  370. this.store.saveMessage(owner, message!)
  371. this.saveWork(owner, run)
  372. })
  373. }
  374. if(!recovering&&message.status==='queued'){message.status='streaming';message.error=undefined;message.visible=run.replyMode!=='automatic'||run.requiredReply}
  375. const resultMessage = message
  376. let submitted = recovering,
  377. settled = false,
  378. completedEvidence = false,
  379. completing = false,
  380. runtimeId = '',
  381. lastFlush = 0
  382. let flushTimer: ReturnType<typeof setTimeout> | undefined
  383. let usageCompletion: Promise<void> | undefined
  384. let submittedText = ''
  385. const toolController = new AbortController()
  386. let toolLease: WorkspaceToolLease | undefined
  387. let pluginLease: OpenBotPlugins | undefined
  388. let resolveTurn!: (m: Message) => void, rejectTurn!: (e: Error) => void
  389. const completion = new Promise<Message>((resolve, reject) => {
  390. resolveTurn = resolve
  391. rejectTurn = reject
  392. })
  393. // Register rejection immediately; setup RPCs can still be awaiting a reply.
  394. void completion.catch(() => {})
  395. const finish = (error?: Error) => {
  396. if (settled) return
  397. settled = true
  398. toolController.abort()
  399. void toolLease?.dispose()
  400. void pluginLease?.dispose()
  401. clearTimeout(flushTimer)
  402. flushTimer = undefined
  403. this.live.delete(key)
  404. try {
  405. const current = this.getWork(owner, run.id)
  406. if (current.cancelRequested && current.status === 'interrupted') {
  407. resultMessage.status = 'interrupted'
  408. resultMessage.error = '已停止'
  409. this.store.atomic(() => {
  410. this.store.saveMessage(owner, resultMessage)
  411. this.saveWork(owner, current)
  412. this.resolveInteractions(owner, current.id)
  413. })
  414. if (error) rejectTurn(error)
  415. else resolveTurn(resultMessage)
  416. return
  417. }
  418. if(error&&!submitted&&current.status!=='interrupted'&&error instanceof HttpError&&RESOURCE_WAIT_CODES.has(error.code??'')){
  419. current.status='queued';current.resourceWait=true;current.error='等待执行节点或电脑资源';resultMessage.status='queued';resultMessage.visible=false;resultMessage.error=undefined
  420. }else if (error) {
  421. current.status = current.status === 'interrupted' ? 'interrupted' : submitted ? 'uncertain' : 'failed'
  422. current.error = error.message.slice(0, 1000)
  423. resultMessage.status = current.status
  424. resultMessage.error = current.error
  425. const optionalUnpublished = current.replyMode === 'automatic' && !current.requiredReply && resultMessage.visible === false
  426. resultMessage.visible = !optionalUnpublished && (submitted || current.status !== 'interrupted')
  427. if (!resultMessage.content.trim() && current.status === 'failed') resultMessage.content = `执行失败:${current.error}`
  428. } else {
  429. if (root.discussion && /^(?:\(?pass\)?\.?|\[\[YAOYAO_NO_REPLY_V1\]\])$/i.test(resultMessage.content.trim())) resultMessage.content = ''
  430. const silent = (resultMessage.content.trim() === NO_REPLY || !resultMessage.content.trim()) && current.replyMode === 'automatic' && (!current.requiredReply || current.hadInteraction) && !resultMessage.tools.length && !resultMessage.attachments.length
  431. current.silent = silent
  432. if (current.replyMode === 'automatic') {
  433. resultMessage.content = resultMessage.content.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '').trim()
  434. resultMessage.reasoning = resultMessage.reasoning.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '')
  435. }
  436. if (current.requiredReply && !silent && !resultMessage.content) resultMessage.content = HOST_FALLBACK
  437. if (!silent && !resultMessage.content && !resultMessage.attachments.length && !resultMessage.tools.length) {
  438. current.status = 'failed'; current.error = '未返回有效回复'; resultMessage.content = '执行失败:未返回有效回复'
  439. } else { current.status = 'complete'; current.error = undefined }
  440. resultMessage.visible = !silent
  441. if (silent) resultMessage.reasoning = ''
  442. resultMessage.status = current.status
  443. resultMessage.error = current.error
  444. }
  445. if (current.status !== 'uncertain') {
  446. for (const tool of resultMessage.tools) {
  447. if (!/complete|error|failed/.test(String(tool.status))) tool.status = current.status === 'complete' ? 'tool.complete' : 'tool.error'
  448. }
  449. }
  450. this.store.atomic(() => {
  451. this.store.saveMessage(owner, resultMessage)
  452. this.saveWork(owner, current)
  453. if (current.status !== 'uncertain') this.resolveInteractions(owner, current.id)
  454. })
  455. if (error) rejectTurn(error)
  456. else resolveTurn(resultMessage)
  457. } catch (failure) { rejectTurn(failure instanceof Error ? failure : new Error('无法保存执行状态')) }
  458. finally { vmTools?.close(); if (usageCompletion) void usageCompletion.finally(() => gateway.close()); else gateway.close() }
  459. }
  460. gateway.onDisconnect = () =>
  461. finish(completedEvidence ? undefined : new Error('Hermes 连接断开'))
  462. gateway.onEvent = (frame: GatewayFrame) => {
  463. if (settled || !runtimeId || frame.session_id !== runtimeId) return
  464. const currentTurn = this.getWork(owner, run.id)
  465. if (currentTurn.cancelRequested || currentTurn.status === 'interrupted') return
  466. this.inspector?.record(owner,c.id,{direction:'event',method:frame.type,data:frame.payload,agentId:agent.id,runId:run.runId,taskId:run.conversationTaskId})
  467. const p = frame.payload ?? {},
  468. type = frame.type
  469. const firstContent = type === 'message.delta' && !resultMessage.content.trim()
  470. 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}
  471. if (type === 'message.delta') {
  472. resultMessage.content += String(p.text ?? p.delta ?? '')
  473. if (resultMessage.content.trim() && !NO_REPLY.startsWith(resultMessage.content.trim()) && !resultMessage.content.trim().startsWith('[[YAOYAO_')) resultMessage.visible = true
  474. }
  475. else if (type === 'reasoning.delta')
  476. resultMessage.reasoning += String(p.text ?? p.delta ?? '')
  477. else if (type === 'message.interim') {
  478. resultMessage.content += '\n\n'
  479. } else if (type.startsWith('tool.')) {
  480. resultMessage.visible = true
  481. const id = String(p.tool_id ?? p.id ?? ''),
  482. index = resultMessage.tools.findIndex((t) => t.id === id)
  483. const value = { ...p, id, status: type }
  484. if (index >= 0) resultMessage.tools[index] = { ...resultMessage.tools[index], ...value }
  485. else resultMessage.tools.push(value)
  486. } else if (
  487. ['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(
  488. type,
  489. )
  490. ) {
  491. const upstreamId = String(p.request_id ?? p.requestId ?? p.id ?? '')
  492. const previous = this.store.list<WorkspaceInteraction>(owner, 'interaction').find(i => {
  493. const b = this.store.get<{ taskId: string; upstreamId: string }>(owner, 'interaction-binding', i.id)
  494. return b?.taskId === run.id && b.upstreamId === upstreamId
  495. })
  496. if (previous?.resolved) return
  497. const interaction: WorkspaceInteraction = previous ?? {
  498. id: randomUUID(),
  499. conversationId: c.id,
  500. conversationTaskId: run.conversationTaskId,
  501. runId: run.runId,
  502. agentId: agent.id,
  503. kind: type.startsWith('approval') ? 'approval' : 'clarification',
  504. message: String(p.question ?? p.message ?? p.prompt ?? '需要确认'),
  505. choices: Array.isArray(p.choices) ? p.choices.map(String) : [],
  506. resolved: false,
  507. }
  508. this.store.put(owner, 'interaction', interaction.id, interaction)
  509. this.store.put(owner, 'interaction-binding', interaction.id, { key, upstreamId, taskId: run.id, conversationTaskId: run.conversationTaskId })
  510. this.store.event(owner, 'interaction.changed', interaction, c.id)
  511. const current = this.getWork(owner, run.id)
  512. current.hadInteraction = true
  513. current.status = 'waiting'
  514. this.saveWork(owner, current)
  515. const policy = globalComputers(this.store.home).approvalPolicy
  516. if (interaction.kind === 'approval' && policy !== 'ask' && !previous) {
  517. // Use the same ownership, authorization and response deduplication as
  518. // a manual answer. Never grant session-wide or permanent approval.
  519. void this.respond(owner, interaction.id, policy === 'allow' ? 'once' : 'deny').catch(() => {
  520. const latest = this.store.get<WorkspaceInteraction>(owner, 'interaction', interaction.id)
  521. if (latest && !latest.resolved) this.notify(owner, c, this.store.require<Run>(owner, 'run', run.runId), undefined, latest)
  522. })
  523. } else if (!previous) this.notify(owner, c, this.store.require<Run>(owner, 'run', run.runId), undefined, interaction)
  524. } else if(type==='interaction.cancelled'){
  525. const upstreamId=String(p.request_id??'')
  526. for(const interaction of this.store.list<WorkspaceInteraction>(owner,'interaction')){
  527. const binding=this.store.get<{taskId:string;upstreamId:string}>(owner,'interaction-binding',interaction.id)
  528. if(!interaction.resolved&&binding?.taskId===run.id&&binding.upstreamId===upstreamId){
  529. interaction.resolved=true;this.store.put(owner,'interaction',interaction.id,interaction)
  530. this.store.event(owner,'interaction.changed',interaction,c.id)
  531. }
  532. }
  533. const current=this.getWork(owner,run.id)
  534. if(current.status==='waiting'&&!this.store.list<WorkspaceInteraction>(owner,'interaction').some(i=>i.runId===run.runId&&i.agentId===agent.id&&!i.resolved)){
  535. current.status='running';this.saveWork(owner,current)
  536. }
  537. } else if (['message.complete', 'run.completed'].includes(type)) {
  538. if (typeof p.text === 'string') resultMessage.content = p.text
  539. if (typeof p.reasoning === 'string') resultMessage.reasoning = p.reasoning
  540. if (p.status === 'interrupted') {
  541. const current = this.getWork(owner, run.id)
  542. current.status = 'interrupted'
  543. this.saveWork(owner, current)
  544. finish(new Error('已停止'))
  545. } else if (p.error || p.status === 'failed') {
  546. submitted = false
  547. finish(new HttpError(502, String(p.error ?? '运行失败'), 'run_failed'))
  548. } else if (!completing) {
  549. completedEvidence = true
  550. completing = true
  551. const outputText = [resultMessage.content, resultMessage.reasoning, resultMessage.tools.length ? JSON.stringify(resultMessage.tools) : ''].filter(Boolean).join('\n')
  552. this.recordTurnTokens(owner, agent.id, estimateTokens(submittedText), estimateTokens(outputText))
  553. finish()
  554. }
  555. return
  556. } else if (['error', 'message.error', 'run.failed'].includes(type)) {
  557. submitted = false
  558. finish(new HttpError(502, String(p.message ?? p.error ?? '运行失败'), 'run_failed'))
  559. return
  560. } else if (['session.usage', 'usage.update', 'context.update'].includes(type)) {
  561. if (type !== 'context.update') this.recordAgentUsage(owner, key, agent.id, p)
  562. const context = { ...p, conversationTaskId: run.conversationTaskId }
  563. this.store.put(owner, 'context', run.conversationTaskId ?? c.id, context)
  564. this.store.event(owner, 'context.changed', context, c.id)
  565. } else if (type === 'session.info' && binding) {
  566. const storedId = p.stored_session_id ?? p.session_key
  567. if (typeof storedId === 'string' && storedId && storedId !== binding.storedId) {
  568. binding.aliases = [...new Set([...binding.aliases, binding.storedId, storedId])]
  569. binding.storedId = storedId
  570. this.store.put(owner, 'binding', key, binding)
  571. }
  572. }
  573. const flush = () => {
  574. clearTimeout(flushTimer)
  575. flushTimer = undefined
  576. if (settled || this.closing) return
  577. try {
  578. this.store.saveMessage(owner, resultMessage)
  579. lastFlush = Date.now()
  580. } catch (error) {
  581. finish(error instanceof Error ? error : new Error('无法保存流式消息'))
  582. }
  583. }
  584. const remaining = (this.store.messagePatchesEnabled ? 33 : 100) - (Date.now() - lastFlush)
  585. if (firstContent || !['message.delta', 'reasoning.delta', 'message.interim'].includes(type) || remaining <= 0) flush()
  586. // A stream may pause after any chunk. Publish the latest text even when
  587. // no subsequent event arrives to trigger the next leading-edge flush.
  588. else if (flushTimer === undefined) flushTimer = setTimeout(flush, remaining)
  589. }
  590. try {
  591. await gateway.connect()
  592. this.requireAuthorization(owner, run.runId)
  593. this.nodes.requireSource(owner, agent)
  594. // Paired Web nodes enforce their own profile config at the destination.
  595. const cwd = recovering || target.pairedToken ? undefined
  596. : await configuredWorkingDirectory((path, options) => target.session.request(path, options), agent.profile)
  597. this.nodes.requireSource(owner, agent)
  598. // Hermes rejects disabled_toolsets on session.create. Host-tool denial
  599. // stays a YaoYao policy; it is not a session-create parameter.
  600. const createSession = () => gateway.rpc('session.create', {
  601. profile: agent.profile,
  602. title: `Yaoyao ${c.id}${run.conversationTaskId ? ` / ${run.conversationTaskId}` : ''}`,
  603. source: 'yaoyao_workspace',
  604. ...(cwd ? { cwd } : {}),
  605. hidden: true,
  606. room_plumbing: true,
  607. close_on_disconnect: false,
  608. })
  609. let opened
  610. if (binding?.storedId) {
  611. try {
  612. opened = await gateway.rpc('session.resume', {
  613. profile: agent.profile,
  614. session_id: binding.storedId,
  615. omit_messages: true,
  616. ...(recovering&&target.runner?.computer?{recoverOnly:true}:{}),
  617. close_on_disconnect: false,
  618. })
  619. } catch (error) {
  620. const code = error instanceof HttpError ? error.code : ''
  621. const message = error instanceof Error ? error.message : ''
  622. if (recovering || (code !== 'computer_session_mode_changed' && !message.includes('执行方式已改变'))) throw error
  623. binding = undefined
  624. opened = await createSession()
  625. }
  626. } else opened = await createSession()
  627. runtimeId = String(opened.session_id ?? '')
  628. const storedId = String(
  629. opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? binding?.storedId ?? '',
  630. )
  631. if (
  632. !runtimeId ||
  633. !storedId ||
  634. (opened.info?.profile_name && opened.info.profile_name !== agent.profile)
  635. )
  636. throw new Error('Hermes 会话身份不匹配')
  637. binding = {
  638. memoryVersion: recovering ? binding?.memoryVersion : memory.version,
  639. runnerId: target.runner?.id,
  640. execution:chatExecution,
  641. vmExecution:undefined,
  642. hermesComputer:target.runner?.hermesComputer,
  643. computerEnvironmentId:agent.computerEnvironmentId,
  644. id: key,
  645. nodeId: agent.nodeId,
  646. remoteAgentId: agent.remoteAgentId,
  647. profile: agent.profile,
  648. storedId,
  649. runtimeId,
  650. aliases: [
  651. ...new Set([
  652. ...(binding?.aliases ?? []),
  653. ...(binding ? [binding.storedId] : []),
  654. storedId,
  655. ]),
  656. ],
  657. runId: run.runId,
  658. conversationTaskId: run.conversationTaskId,
  659. taskId: run.id,
  660. contextSeq: binding?.contextSeq ?? 0,
  661. messageId: resultMessage.id,
  662. }
  663. this.store.put(owner, 'binding', key, binding)
  664. this.live.set(key, { gateway, runtimeId, runId: run.runId, conversationTaskId: run.conversationTaskId, taskId: run.id, agentId: agent.id, done: finish })
  665. if (this.closing || this.getWork(owner, run.id).cancelRequested || this.getWork(owner, run.id).status === 'interrupted')
  666. throw new Error('运行已停止')
  667. if (recovering) {
  668. if (opened.running) {
  669. const current = this.getWork(owner, run.id)
  670. current.status = 'running'
  671. this.saveWork(owner, current)
  672. } else {
  673. const marker = `[yaoyao-run:${run.runId}:${resultMessage.id}]`
  674. let answer: { content?: string; text?: string } | undefined
  675. let found = false, seenLastEvent = false
  676. for (let page = 0; page < 20 && !found; page++) {
  677. const response = await target.session.request(`/api/sessions/${encodeURIComponent(storedId)}/messages`, {
  678. search: new URLSearchParams({ profile: agent.profile, limit: '500', offset: String(page * 500), order: 'latest', include_compacted: 'true' }),
  679. maxResponseBytes: 8 * 1024 * 1024,
  680. })
  681. if (response.status !== 200) throw new Error('无法核对历史')
  682. const history = JSON.parse(response.body.toString()).messages
  683. if (!Array.isArray(history)) throw new Error('历史响应无效')
  684. for (const item of [...history].reverse()) {
  685. if (item.role === 'user') {
  686. if (String(item.content ?? item.text).includes(marker)) { found = true; break }
  687. answer = undefined; seenLastEvent = false
  688. } else if (!seenLastEvent && ['assistant', 'tool'].includes(item.role)) {
  689. seenLastEvent = true
  690. const calls = item.tool_calls
  691. const hasCalls = Array.isArray(calls) ? calls.length > 0 : !!calls && calls !== '[]'
  692. if (item.role === 'assistant' && !hasCalls && !item.function_call && item.finish_reason !== 'tool_calls' && (item.content || item.text)) answer = item
  693. }
  694. }
  695. if (history.length < 500) break
  696. }
  697. if (!found || !answer) throw new Error('无法确认本轮的最终回复,正在核对原执行;不会重复提交')
  698. resultMessage.content = String(answer.content ?? answer.text)
  699. binding.contextSeq = Math.max(binding.contextSeq ?? 0, run.contextThroughSeq ?? 0)
  700. this.store.put(owner, 'binding', key, binding)
  701. finish()
  702. }
  703. } else {
  704. if (opened.running) throw new HttpError(409, '上游会话仍在运行', 'session_busy')
  705. this.nodes.requireSource(owner, agent)
  706. const team=botCapabilities.tools&&!agent.temporaryGoalId&&!agent.remoteAgentId&&!this.store.require<Run>(owner,'run',run.runId).assignmentId
  707. const cloud=!!this.cloud?.selected(owner,agent)
  708. const plugins=!!this.plugins?.selected(owner,agent)
  709. const envTools=this.desktopEnvironments?.envTools(owner,agent)??{view:false,browser:false,file:false}
  710. const desktop=envTools.view||envTools.file
  711. const desktopEpochs=this.desktopEnvironments?.hostEpochs(owner,agent)??{}
  712. const knowledge = botCapabilities.tools && !agent.remoteAgentId
  713. const vmHolder:{session?:VmToolSession}={}
  714. const requireVm=()=>{if(!globalComputers(this.store.home).vm)throw new HttpError(403,'全局设置未开放虚拟机。','computer_disabled')}
  715. const callVm=async(name:string,args:unknown)=>{
  716. requireVm()
  717. if(!vmHolder.session){
  718. const vmTarget=this.nodes.targetForAgent(owner,{...agent,execution:'computer'})
  719. vmHolder.session=new VmToolSession(vmTarget,agent.profile,run.id,()=>{
  720. requireVm();this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,agent)
  721. 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)
  722. 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)throw new HttpError(403,'本轮机器人或任务授权已结束','run_authorization_revoked')
  723. },async(name,bytes)=>{
  724. this.requireAuthorization(owner,run.runId)
  725. const file=this.publishArtifact(owner,resultMessage,agent,name,bytes)
  726. if(!resultMessage.attachments.some(item=>item.id===file.id))resultMessage.attachments.push(file)
  727. this.store.saveMessage(owner,resultMessage)
  728. return {...file,url:`/api/app/files/${file.id}/download`}
  729. })
  730. vmTools=vmHolder.session
  731. }
  732. return vmHolder.session.call(name,args)
  733. }
  734. if(team||cloud||desktop||plugins||knowledge||dispatchedVm){
  735. if(team){const granted=this.getWork(owner,run.id);granted.teamManagementRevision=agent.revision;this.saveWork(owner,granted)}
  736. if(desktop)await this.desktopEnvironments!.requireAvailable(owner,agent,target)
  737. if(cloud)await this.cloud!.requireAvailable(owner,agent,target)
  738. const assertActive=()=>{
  739. if(settled||this.closing||toolController.signal.aborted)throw new HttpError(410,'本轮运行已结束,请发起新一轮对话后重试。','run_finished')
  740. this.requireAuthorization(owner,run.runId);this.nodes.requireSource(owner,this.store.require<Agent>(owner,'agent',agent.id))
  741. if(team)this.teamTools.assertTurn(owner,run.id)
  742. 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')}
  743. }
  744. if(plugins)pluginLease=await this.plugins!.open(owner,agent,target,toolController.signal,assertActive)
  745. toolLease=await createWorkspaceToolLease({
  746. target,profile:agent.profile,workId:run.id,signal:toolController.signal,
  747. workspaceMemory:botCapabilities.memory,
  748. session:()=>({runtimeId,storedId:binding!.storedId}),assertActive,
  749. catalog:()=>[...(team?this.teamTools.catalog(owner,run.id):[]),...(knowledge?this.knowledgeTools.catalog(owner,run.id,botCapabilities.memory):[]),...(cloud?GROK_COMPUTER_TOOLS:[]),...(dispatchedVm?VM_COMPUTER_TOOLS:[]),...(desktop?DESKTOP_ENVIRONMENT_TOOLS.filter(t=>(envTools.view&&['desktop_environment_view','desktop_environment_action'].includes(t.id))||(envTools.file&&DESKTOP_FILE_TOOL_IDS.has(t.id))):[]),...(pluginLease?.catalog()??[])],
  750. 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,'local',desktopEpochs,root.deviceHost):toolId.startsWith('cloud_computer_')?this.cloud!.call(owner,agent.id,toolId,args,toolController.signal):toolId.startsWith('computer_')&&dispatchedVm?callVm(toolId,args):this.teamTools.call(owner,run.id,toolId,args)},
  751. onFailure:error=>{if(!settled)void gateway.rpc('session.interrupt',{session_id:runtimeId}).catch(()=>{}).finally(()=>finish(error))},
  752. })
  753. await toolLease.bind();if(settled)return await completion
  754. }
  755. await applyWorkingDirectory((method, params) => gateway.rpc(method, params), runtimeId, cwd, undefined, opened.info?.cwd)
  756. // Binding initializes cold Hermes sessions; its persisted runtime can overwrite
  757. // pre-build config acknowledgements. Apply Bot settings only after that boundary.
  758. if (agent.modelSettings !== undefined) {
  759. const entry = { method: 'bot.model-settings', agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId }
  760. const snapshot = { revision: agent.revision, settings: agent.modelSettings }
  761. this.inspector?.record(owner, c.id, { ...entry, direction: 'request', data: snapshot })
  762. try {
  763. const resolution = await resolveBotModelSettings(target, agent.profile, agent.modelSettings)
  764. const confirmed = agent.modelSettingsConfirmation === botModelTarget(resolution.effective)
  765. if (resolution.confirmationMessage && !confirmed) throw new HttpError(409, '此模型需要确认,请打开 Bot 个人资料保存模型设置。', 'model_confirmation_required')
  766. await applyBotModelSettings((method, params) => gateway.rpc(method, params), runtimeId, resolution.effective, confirmed)
  767. this.inspector?.record(owner, c.id, { ...entry, direction: 'response', data: { ...snapshot, applied: true, effective: resolution.effective } })
  768. } catch (error) {
  769. // Context-dependent native warnings cannot be known from the model
  770. // catalogue. Bring them back to the profile's existing save flow.
  771. if (error instanceof BotModelConfirmationError) {
  772. const latest = this.store.require<Agent>(owner, 'agent', agent.id)
  773. if (latest.revision === agent.revision) this.store.put(owner, 'agent', latest.id, { ...latest,
  774. modelSettingsPendingConfirmation: { target: error.target, message: error.confirmationMessage } })
  775. }
  776. this.inspector?.record(owner, c.id, { ...entry, direction: 'response', data: { ...snapshot, applied: false, error: error instanceof Error ? error.message : '模型设置应用失败' } })
  777. throw error
  778. }
  779. }
  780. const trigger = this.store.require<Message>(owner, 'message', run.messageId)
  781. const attachmentRefs: string[] = []
  782. for (const file of trigger.attachments) {
  783. this.requireAuthorization(owner, run.runId)
  784. const record = this.files(owner,[file.id])[0]!
  785. const bytes = readFileSync(record.path).toString('base64')
  786. const attached = record.mimeType.startsWith('image/')
  787. ? await gateway.rpc('image.attach_bytes', {
  788. session_id: runtimeId,
  789. filename: record.name,
  790. content_base64: bytes,
  791. })
  792. : await gateway.rpc('file.attach', {
  793. session_id: runtimeId,
  794. name: record.name,
  795. data_url: `data:${record.mimeType};base64,${bytes}`,
  796. })
  797. if (attached.ref_text) attachmentRefs.push(String(attached.ref_text))
  798. }
  799. const members = run.turnConfiguration!.members
  800. const goal = run.conversationTaskId ? this.store.get<import('../shared/agentTasks.js').AgentGoal>(owner, 'goal', run.conversationTaskId) : undefined
  801. const assignmentId = this.store.require<Run>(owner, 'run', run.runId).assignmentId
  802. const globals = globalComputers(this.store.home)
  803. const eligible = !agent.remoteAgentId && !agent.archived
  804. const open = [eligible && globals.scriptMachine ? '脚本机' : '', eligible && globals.serverComputer ? '服务器' : '', eligible && globals.vm ? '虚拟环境' : '', eligible && globals.cloud ? '云虚拟机' : ''].filter(Boolean)
  805. const hostNames = this.desktopEnvironments?.hostStates(owner).map(host => host.name).filter(Boolean) ?? []
  806. const prior = this.store.messages(owner, c.id, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, true, run.conversationTaskId)
  807. .filter(message => message.id !== resultMessage.id && message.seq <= run.triggerSeq)
  808. .map(message => `${message.content}\n${message.tools.map(tool => String(tool.name ?? tool.tool_name ?? '')).join(' ')}`)
  809. .join('\n')
  810. const hit = environmentMentions(`${trigger.content}\n${prior}`, hostNames)
  811. const envDirective = `Hermes 只运行在服务器,其原生终端和文件工具始终操作服务器,不代表用户所说的「本机」。操作用户消息来源电脑必须使用带目标的 desktop_* 工具。Hermes 的网页、浏览器、终端和文件工具均可使用。不要使用 Hermes 的 memory 工具,长期记忆只用 Bot 自己的记忆。另外可以使用全局开放的电脑环境:${open.join('、') || '无'}。所有 Bot 使用同一套全局电脑权限,环境可同时使用。没开放的电脑环境不要用。这些环境是额外的桌面,不代替 Hermes 工具。`
  812. const rules = [
  813. envDirective,
  814. `你是 ${agent.name}。${agent.description ? `描述:${agent.description}\n\n` : ''}${personaSection(agent) ? `用户为它设定的工作规范:\n${personaSection(agent)}\n\n` : ''}以下是用户为这个独立机器人配置的角色与规则(版本 ${agent.revision}):\n${agent.remoteAgentId ? '配置由远端机器人管理。' : agent.instructions}`,
  815. c.kind === 'group' && Object.keys(c.memberRoles ?? {}).length
  816. ? `本群角色分工(仅在本群生效):\n${members.flatMap(member => {
  817. const role = c.memberRoles?.[member.id]
  818. return role ? [`@${member.name}:${role.name};${role.description}`] : []
  819. }).join('\n')}\n协作时使用上面的真实成员名称进行 @,不要使用职责名称代替成员名称。`
  820. : '',
  821. this.store.require<Run>(owner, 'run', run.runId).discussion
  822. ? `你正在群聊「${c.name}」平等讨论,第 ${run.depth + 1} 轮。你只代表自己,必须给出一条公开、有实质内容的回答,保留用户原始要求。不要代替其他成员发言,不要用私信或 @ 再次派发本轮工作。系统会安排其他成员。`
  823. : c.kind === 'group'
  824. ? `你正在群聊「${c.name}」发言。群成员:${members.map((a) => `@${a.name} (id=${a.id})`).join('、')}。\n群规则:${c.instructions}\n${c.mode === 'host' ? (agent.id === c.administratorId ? '你是管理员。必要时用精确 @成员名称 委派工作;收到结果后复核并给用户结论。任务完成时不要继续 @。' : '执行当前委派任务。公开给出结果,由管理员复核;不要安排其他成员。') : '按自己的职责回复,只在需要协作时 @成员。不要重复已完成的工作。'}`
  825. : '',
  826. c.kind === 'group' ? '只有安排具体的新工作时才用 @成员派工,并写明需要执行的动作。收到、感谢、审核通过、等待用户指令等确认不需要再次 @。任务收尾直接向用户报告结果;不要重复确认或把同一结果反复交回其他成员。' : '',
  827. run.requiredReply ? '你必须公开处理本次消息,直接回答、委派或澄清;禁止静默。管理员可按依赖一次 @一人,也可同时 @多人并行执行,整批结束后系统统一交回复核。' : run.replyMode === 'automatic' ? `你按自动参与配置收到消息。若与职责无关或仅是已完成工作的重复确认,禁止调用工具、禁止 @,完整答复只能是 ${NO_REPLY}。有新工作或新结果时正常回答。` : '',
  828. `本轮用户指定成员:${this.store.require<Run>(owner, 'run', run.runId).mentionIds.map(id => members.find(a => a.id === id)).filter(Boolean).map(a => '@' + a!.name).join('、') || '未指定'}`,
  829. '角色规则不赋予额外工具权限;仍遵守基础 Hermes 的工具和安全约束。',
  830. this.store.require<Run>(owner, 'run', run.runId).internalInstruction || '',
  831. 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 记录完成、受阻或等待用户,完成时提供实际依据。'}` : '',
  832. agent.temporaryGoalId ? `你是当前任务的临时助手,任务 ID:${agent.temporaryGoalId}。仅处理分派工作,使用 computer_export 回传产物。任务结束后会退役;不要创建团队或改变自身权限。` : '',
  833. team ? TEAM_TOOL_RULES : '',
  834. knowledge ? BOT_KNOWLEDGE_RULES : '',
  835. memory.text,
  836. root.projectId ? `当前项目 ID:${root.projectId}。只能使用当前项目记忆。` : '',
  837. `本次来源消息 ID:${run.messageId};当前会话 ID:${c.id}。`,
  838. plugins ? '本轮已挂载用户为当前 Bot 授权的插件工具,工具名以 plugin_ 开头,说明中包含实际服务和操作。仅按用户当前任务使用;连接或重新授权应用请让用户打开 Bot 模式的工具 → 已连接应用。不要索取 API Key 或在回复中展示凭据。' : '',
  839. desktop && hit.server && globals.serverComputer ? SERVER_COMPUTER_RULES+(this.desktopEnvironments?.onlineHostsLine(owner,root.deviceHost)??'') : '',
  840. desktop && hit.script && globals.scriptMachine ? DESKTOP_ENVIRONMENT_RULES+(this.desktopEnvironments?.onlineHostsLine(owner,root.deviceHost)??'') : '',
  841. this.desktopEnvironments?.deviceContextLine(owner,root.deviceHost) ?? '本轮未提供来源电脑;操作电脑时必须明确目标。',
  842. envTools.file ? DESKTOP_FILE_TRANSFER_RULES : '',
  843. cloud && hit.cloud ? grokComputerRules() : '',
  844. dispatchedVm && hit.vm ? VM_COMPUTER_RULES : '',
  845. `[yaoyao-run:${run.runId}:${resultMessage.id}]`,
  846. ]
  847. .filter(Boolean)
  848. .join('\n\n')
  849. const text = c.kind === 'group' ? this.contextText(owner, c, agent, run, binding.contextSeq ?? 0, movedRunner)
  850. : movedRunner ? `执行节点已切换。以下是原会话的近期记录,旧路径和执行状态需要在当前节点重新核实;不要重新执行已完成的操作。\n\n${this.contextText(owner,c,agent,run,0,true)}` : trigger.content
  851. const admission = this.getWork(owner, run.id)
  852. if (!this.store.taskMemberIds(owner,this.store.require<Conversation>(owner,'conversation',c.id),run.conversationTaskId).includes(agent.id)) {
  853. admission.status = 'interrupted'; admission.error = '执行前成员已移除'; this.saveWork(owner, admission)
  854. throw new Error('执行前成员已移除')
  855. }
  856. this.nodes.requireSource(owner, agent)
  857. this.requireAuthorization(owner, run.runId)
  858. if (admission.cancelRequested || admission.status === 'interrupted') throw new Error('运行已停止')
  859. admission.contextThroughSeq = run.contextThroughSeq ?? run.triggerSeq
  860. admission.submitted = true
  861. this.saveWork(owner, admission)
  862. submitted = true
  863. try {
  864. submittedText = `${rules}\n\n${text}\n${attachmentRefs.join('\n')}`
  865. await gateway.rpc('prompt.submit', {
  866. session_id: runtimeId,
  867. ...(target.runner?.computer?{workMarker:`[yaoyao-run:${run.runId}:${resultMessage.id}]`}:{}),
  868. text: submittedText,
  869. })
  870. this.store.remove(owner,'binding-reset',key)
  871. binding.contextSeq = Math.max(binding.contextSeq ?? 0, admission.contextThroughSeq)
  872. this.store.put(owner, 'binding', key, binding)
  873. } catch (error) {
  874. // A JSON-RPC error is a definitive rejection, not a lost receipt.
  875. 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) }
  876. throw error
  877. }
  878. }
  879. return await completion
  880. } catch (error) {
  881. finish(error instanceof Error ? error : new Error('执行失败'))
  882. return await completion
  883. }
  884. }
  885. private requireAuthorization(owner: string, runId: string): void {
  886. const run=this.store.require<Run>(owner,'run',runId)
  887. if(!this.userActive(owner)||(run.authorizationVersion!==undefined&&run.authorizationVersion!==this.authorizationVersion(owner)))
  888. throw new HttpError(403,'本轮账号授权已失效','run_authorization_revoked')
  889. }
  890. private contextText(owner: string, c: Conversation, agent: Agent, work: Work, after: number, includeOwn = false): string {
  891. const rootTrigger = this.store.require<Message>(owner, 'message', work.messageId)
  892. 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]))
  893. const history = this.store.messages(owner, c.id, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, true, work.conversationTaskId)
  894. 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)))
  895. work.contextThroughSeq = unfinished ? unfinished.seq - 1 : work.triggerSeq
  896. const eligible = history
  897. .filter(m => m.seq > after && m.seq <= work.triggerSeq && m.visible !== false && ['complete', 'failed', 'interrupted'].includes(m.status)
  898. && (includeOwn || !(m.role === 'assistant' && m.agentId === agent.id)) && (!m.runId || (roots.get(m.runId) ?? 0) <= rootTrigger.seq))
  899. const selected: string[] = []
  900. let size = 0, omitted = 0
  901. for (const message of [...eligible].reverse()) {
  902. const files = message.attachments.map(f => `[附件 ${f.name}](${f.sourcePath || `/api/app/files/${f.id}/download`})`).join('\n')
  903. const content = message.content.length > 24_000 ? message.content.slice(0, 12_000) + '\n[内容过长,保留首尾片段]\n' + message.content.slice(-12_000) : message.content
  904. const reasoning = message.reasoning ? `\n思考摘要:${message.reasoning.slice(0, 2000)}` : ''
  905. 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)
  906. const row = `${message.role === 'user' ? '用户' : message.agentName ?? '系统'}(${message.status}):${content}${reasoning}${tools.length ? `\n使用工具:${tools.join('、')}` : ''}${message.error ? `\n错误:${message.error}` : ''}${files ? '\n' + files : ''}`
  907. if (selected.length >= 50 || size + row.length > 30_000) { omitted++; continue }
  908. selected.unshift(row); size += row.length
  909. }
  910. // Preserve a large trigger as a bounded excerpt rather than silently losing it.
  911. if (!selected.length && eligible.length) selected.push(eligible.at(-1)!.content.slice(-30_000))
  912. 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') : ''
  913. const request = this.store.require<Run>(owner, 'run', work.runId).discussion ? `本次用户原始要求:\n${rootTrigger.content.slice(0, 16000)}\n\n` : ''
  914. return `${request}${batch ? `本批次执行结果:\n${batch}\n\n` : ''}${omitted ? `较早上下文有 ${omitted} 条因长度限制省略,请勿假定已完整读取。\n\n` : ''}${selected.join('\n\n')}`
  915. }
  916. async respond(owner: string, id: string, answer: string): Promise<void> {
  917. type Reply = WorkspaceInteraction & { answer?: string; responseState?: 'sending' | 'uncertain' | 'sent' }
  918. const interaction = this.store.require<Reply>(owner, 'interaction', id)
  919. this.requireAuthorization(owner,interaction.runId)
  920. this.nodes.requireSource(owner, this.store.require<Agent>(owner, 'agent', interaction.agentId))
  921. if (interaction.resolved) {
  922. if (interaction.answer && interaction.answer !== answer) throw new HttpError(409, '该请求已使用其他答复完成', 'interaction_answer_conflict')
  923. return
  924. }
  925. if (interaction.responseState === 'sending' || interaction.responseState === 'uncertain') throw new HttpError(409, '答复状态待确认,请核对原请求', 'interaction_uncertain')
  926. const binding = this.store.require<{ key: string; upstreamId: string; taskId: string }>(owner, 'interaction-binding', id)
  927. const live = this.live.get(binding.key)
  928. if (!live || live.taskId !== binding.taskId || live.runId !== interaction.runId) throw new HttpError(409, '请先恢复此轮连接', 'interaction_offline')
  929. if (interaction.kind === 'approval' && !['once', 'session', 'always', 'deny', 'allow', 'approve', 'auto'].includes(answer)) throw new HttpError(400, '审批选项无效', 'invalid_approval')
  930. const automatic = interaction.kind === 'approval' && answer === 'auto'
  931. interaction.answer = answer; interaction.responseState = 'sending'
  932. this.store.atomic(() => {
  933. // Approval replies never change the global policy.
  934. // Legacy auto replies approve this operation only. Global policy is admin-owned.
  935. this.store.put(owner, 'interaction', id, interaction)
  936. })
  937. try {
  938. await live.gateway.rpc(interaction.kind === 'approval' ? 'approval.respond' : 'clarify.respond', {
  939. session_id: live.runtimeId, request_id: binding.upstreamId,
  940. ...(interaction.kind === 'approval' ? { choice: automatic ? 'once' : answer } : { answer }),
  941. })
  942. } catch (error) {
  943. const latest = this.store.require<Reply>(owner, 'interaction', id)
  944. if (!latest.resolved) {
  945. latest.responseState = error instanceof HttpError && error.code === 'gateway_rejected' ? undefined : 'uncertain'
  946. this.store.put(owner, 'interaction', id, latest)
  947. }
  948. if (automatic) throw new HttpError(409, '本次答复未确认,请检查当前任务状态;全局审批策略未改变。', 'approval_auto_response_failed')
  949. throw error
  950. }
  951. interaction.resolved = true; interaction.responseState = 'sent'
  952. this.store.put(owner, 'interaction', id, interaction)
  953. this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId)
  954. const current = this.getWork(owner, binding.taskId)
  955. if (current.status === 'waiting') { current.status = 'running'; this.saveWork(owner, current) }
  956. }
  957. protected async interruptTurn(owner: string, work: Work): Promise<void> {
  958. const key = this.bindingKey(work.conversationId, work.conversationTaskId, work.agentId)
  959. const live = this.live.get(key)
  960. if (live?.taskId === work.id) {
  961. await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId })
  962. const current = this.getWork(owner, work.id)
  963. if (['complete', 'failed', 'interrupted'].includes(current.status)) {
  964. live.done(new Error('已停止'))
  965. return
  966. }
  967. current.status = 'interrupted'; current.error = '已停止'
  968. this.saveWork(owner, current)
  969. if(current.currentMessageId){const message=this.store.require<Message>(owner,'message',current.currentMessageId);message.status='interrupted';message.error='已停止';this.store.saveMessage(owner,message)}
  970. live.done(new Error('已停止'))
  971. } else {
  972. const binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
  973. if (work.submitted) {
  974. if (!binding || binding.taskId !== work.id) throw new Error('无法确认待停止成员的会话身份')
  975. const target=binding.remoteAgentId||binding.execution==='computer'?this.nodes.targetForAgent(owner,{...binding,id:work.agentId}):this.nodes.target(owner,binding.nodeId)
  976. if(binding.runnerId!==target.runner?.id)throw new Error('执行节点已变化,无法确认原任务已停止')
  977. 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('原会话绑定已改变')}})
  978. try {
  979. await gateway.connect()
  980. 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}:{}) })
  981. if (opened.running) await gateway.rpc('session.interrupt', { session_id: opened.session_id })
  982. } finally { gateway.close() }
  983. }
  984. const current = this.getWork(owner, work.id)
  985. current.status = 'interrupted'; current.error = '已停止'
  986. this.saveWork(owner, current)
  987. if (current.currentMessageId) {
  988. const message = this.store.require<Message>(owner, 'message', current.currentMessageId)
  989. message.status = 'interrupted'; this.store.saveMessage(owner, message)
  990. }
  991. }
  992. this.resolveInteractions(owner, work.id)
  993. }
  994. override async stopTask(owner: string, conversationId: string, taskId: string, visited = new Set<string>()): Promise<void> {
  995. const key = `${owner}:${taskId}`
  996. if (visited.has(key)) return
  997. visited.add(key)
  998. await this.collaboration.stopFor(owner, chain => chain.originConversationId === conversationId && chain.originTaskId === taskId)
  999. this.tasks.cancel(owner, taskId)
  1000. await Promise.all([super.stopTask(owner, conversationId, taskId), this.tasks.cancelOrigin(owner, conversationId, taskId, visited)])
  1001. }
  1002. override async stopConversation(owner: string, conversationId: string): Promise<void> {
  1003. await this.collaboration.stopFor(owner, chain => chain.originConversationId === conversationId)
  1004. for (const task of this.store.list<import('../shared/workspace.js').WorkspaceTask>(owner, 'conversation-task'))
  1005. if (task.conversationId === conversationId) this.tasks.cancel(owner, task.id)
  1006. await Promise.all([super.stopConversation(owner, conversationId), this.tasks.cancelOrigin(owner, conversationId)])
  1007. }
  1008. private recordTurnTokens(owner: string, agentId: string, input: number, output: number): void {
  1009. if (!input && !output) return
  1010. this.store.atomic(() => {
  1011. const now = new Date(),
  1012. date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
  1013. id = `${agentId}:${date}`
  1014. const day = this.store.get<WorkspaceAgentUsageSummary & { agentId: string; date: string; updatedAt: number }>(owner, 'agent-token-day', id)
  1015. ?? { agentId, date, input: 0, output: 0, total: 0, updatedAt: 0 }
  1016. day.input += input
  1017. day.output += output
  1018. day.total += input + output
  1019. day.updatedAt = now.getTime()
  1020. this.store.put(owner, 'agent-token-day', id, day)
  1021. })
  1022. }
  1023. /**
  1024. * Hermes reports cumulative per-session token counters (input/output/total) alongside
  1025. * context occupancy. Attribute the growth since the last snapshot to the agent's daily
  1026. * usage bucket; a session reset (counters dropping) only re-baselines.
  1027. */
  1028. private recordAgentUsage(owner: string, key: string, agentId: string, usage: unknown): void {
  1029. if (!usage || typeof usage !== 'object') return
  1030. const value = usage as Record<string, unknown>
  1031. const counter = (...names: string[]) => {
  1032. for (const name of names) {
  1033. const raw = value[name]
  1034. if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0) return Math.round(raw)
  1035. }
  1036. return undefined
  1037. }
  1038. const input = counter('input', 'prompt', 'input_tokens'),
  1039. output = counter('output', 'completion', 'output_tokens'),
  1040. total = counter('total', 'total_tokens') ?? (input === undefined && output === undefined ? undefined : (input ?? 0) + (output ?? 0))
  1041. if (total === undefined) return
  1042. this.store.atomic(() => {
  1043. const baseline = this.store.get<{ input?: number; output?: number; total?: number }>(owner, 'usage-baseline', key) ?? {}
  1044. const grew = (current: number | undefined, previous: number | undefined) => (current === undefined ? 0 : Math.max(0, current - (previous ?? 0)))
  1045. const inputDelta = grew(input, baseline.input), outputDelta = grew(output, baseline.output), totalDelta = grew(total, baseline.total)
  1046. this.store.put(owner, 'usage-baseline', key, { input, output, total })
  1047. if (!inputDelta && !outputDelta && !totalDelta) return
  1048. const now = new Date(),
  1049. date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
  1050. id = `${agentId}:${date}`
  1051. const day = this.store.get<WorkspaceAgentUsageSummary & { agentId: string; date: string; updatedAt: number }>(owner, 'agent-token-day', id)
  1052. ?? { agentId, date, input: 0, output: 0, total: 0, updatedAt: 0 }
  1053. day.input += inputDelta; day.output += outputDelta; day.total += Math.max(totalDelta, inputDelta + outputDelta)
  1054. day.updatedAt = now.getTime()
  1055. this.store.put(owner, 'agent-token-day', id, day)
  1056. })
  1057. }
  1058. close(): void {
  1059. this.collaboration.close()
  1060. this.tasks.close()
  1061. this.closeScheduler()
  1062. for (const live of [...this.live.values()]) live.done(new Error('服务关闭'))
  1063. this.live.clear()
  1064. }
  1065. }