workspaceRuntime.ts 69 KB

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