workspaceRuntime.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. import { randomUUID } from 'node:crypto'
  2. import { readFileSync } from 'node:fs'
  3. import { z } from 'zod'
  4. import { WorkspaceStore, parse } from './workspaceStore.js'
  5. import { WorkspaceNodes, WorkspaceGateway, type GatewayFrame } from './workspaceGateway.js'
  6. import { HttpError } from './errors.js'
  7. import { UploadStore } from './uploads.js'
  8. import type {
  9. WorkspaceAgent as Agent,
  10. WorkspaceConversation as Conversation,
  11. WorkspaceMessage as Message,
  12. WorkspaceRun,
  13. WorkspaceInteraction,
  14. } from '../shared/workspace.js'
  15. type Run = WorkspaceRun & {
  16. queue: string[]
  17. next: string[]
  18. hostReturn: boolean
  19. currentMessageId?: string
  20. turnConfiguration?: {
  21. mode: 'host' | 'free'
  22. administratorId: string
  23. members: Array<Pick<Agent, 'id' | 'name'>>
  24. }
  25. }
  26. export interface WorkspaceBinding {
  27. id: string
  28. nodeId: string
  29. profile: string
  30. storedId: string
  31. runtimeId: string
  32. aliases: string[]
  33. runId: string
  34. messageId: string
  35. }
  36. interface LiveTurn {
  37. gateway: WorkspaceGateway
  38. runtimeId: string
  39. runId: string
  40. agentId: string
  41. done(error?: Error): void
  42. }
  43. export const sendInput = z
  44. .object({
  45. requestId: z.string().uuid(),
  46. content: z.string().max(65_536).default(''),
  47. mentionIds: z.array(z.string().uuid()).max(8).default([]),
  48. fileIds: z.array(z.string().uuid()).max(8).default([]),
  49. })
  50. .strict()
  51. .refine((b) => b.content.trim() || b.fileIds.length, '请输入消息或添加附件')
  52. export function mentionedAgents(text: string, agents: Array<Pick<Agent, 'id' | 'name'>>): string[] {
  53. const plain = text
  54. .replace(/```[\s\S]*?```/g, '')
  55. .replace(/`[^`]*`/g, '')
  56. .split('\n')
  57. .filter((l) => !l.trimStart().startsWith('>'))
  58. .join('\n')
  59. if (/(?:^|\s)@all(?=$|[\s,。,::!!??])/i.test(plain)) return agents.map((a) => a.id)
  60. return agents
  61. .filter((a) => {
  62. const escaped = a.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  63. return new RegExp(`(?:^|\\s)@${escaped}(?=$|[\\s,。,::!!??])`, 'u').test(plain)
  64. })
  65. .map((a) => a.id)
  66. }
  67. export class WorkspaceRuntime {
  68. private live = new Map<string, LiveTurn>()
  69. private executing = new Set<string>()
  70. private closing = false
  71. onMessage: (owner: string, message: Message) => Promise<void> = async () => {}
  72. onNotify: (
  73. owner: string,
  74. c: Conversation,
  75. run: Run,
  76. message?: Message,
  77. interaction?: WorkspaceInteraction,
  78. ) => void = () => {}
  79. private notify(
  80. owner: string,
  81. c: Conversation,
  82. run: Run,
  83. message?: Message,
  84. interaction?: WorkspaceInteraction,
  85. ): void {
  86. try {
  87. this.onNotify(owner, c, run, message, interaction)
  88. } catch {
  89. /* Optional push failures never change the durable execution result. */
  90. }
  91. }
  92. constructor(
  93. readonly store: WorkspaceStore,
  94. readonly nodes: WorkspaceNodes,
  95. readonly uploads: UploadStore,
  96. readonly userActive: (owner: string) => boolean = () => true,
  97. ) {
  98. // An admitted but unacknowledged turn may already have executed a tool.
  99. for (const owner of store.owners())
  100. for (const run of store.list<Run>(owner, 'run')) {
  101. if (['running', 'waiting'].includes(run.status)) {
  102. run.status = 'uncertain'
  103. run.error = '服务已重启,请核对运行状态'
  104. store.saveRun(owner, run)
  105. }
  106. }
  107. }
  108. start(): void {
  109. for (const owner of this.store.owners())
  110. for (const run of this.store.list<Run>(owner, 'run')) {
  111. if (run.status === 'queued') void this.execute(owner, run.id)
  112. else if (run.status === 'uncertain') void this.reconcile(owner, run.id).catch(() => {})
  113. }
  114. }
  115. send(owner: string, conversationId: string, input: unknown): Run {
  116. const body = parse(sendInput, input)
  117. const result = this.store.command(owner, body.requestId, { conversationId, ...body }, () => {
  118. const c = this.store.require<Conversation>(owner, 'conversation', conversationId)
  119. if (c.archived) throw new HttpError(409, '聊天已归档', 'conversation_archived')
  120. if (c.activeRunId) throw new HttpError(409, '请等待当前回复结束或先停止', 'conversation_busy')
  121. if (body.mentionIds.some((a) => !c.memberIds.includes(a)))
  122. throw new HttpError(400, '只能 @ 群内成员', 'invalid_mentions')
  123. const records = this.uploads.records(body.fileIds, owner)
  124. const now = Date.now(),
  125. runId = randomUUID(),
  126. agents = c.memberIds.map((id) => this.store.require<Agent>(owner, 'agent', id))
  127. const mentions = [
  128. ...new Set(
  129. body.mentionIds.length ? body.mentionIds : mentionedAgents(body.content, agents),
  130. ),
  131. ]
  132. const queue =
  133. c.kind === 'direct'
  134. ? [...c.memberIds]
  135. : mentions.length
  136. ? mentions
  137. : c.mode === 'free' && c.autoReplyIds.length
  138. ? [...c.autoReplyIds]
  139. : [c.administratorId]
  140. const message: Message = {
  141. id: randomUUID(),
  142. conversationId,
  143. seq: 0,
  144. role: 'user',
  145. content: body.content.trim(),
  146. reasoning: '',
  147. runId,
  148. status: 'complete',
  149. attachments: records.map((f) => ({
  150. id: f.id,
  151. name: f.name,
  152. mimeType: f.mimeType,
  153. size: f.size,
  154. sender: 'user',
  155. createdAt: now,
  156. })),
  157. tools: [],
  158. createdAt: now,
  159. }
  160. this.store.saveMessage(owner, message)
  161. for (const file of records) {
  162. const existing = this.store.get<Record<string, unknown>>(owner, 'file', file.id)
  163. if (existing)
  164. this.store.put(owner, 'file', file.id, {
  165. ...existing,
  166. conversationId,
  167. messageId: message.id,
  168. })
  169. }
  170. const run: Run = {
  171. id: runId,
  172. conversationId,
  173. messageId: message.id,
  174. mentionIds: mentions,
  175. activeAgentId: queue[0],
  176. status: 'queued',
  177. round: 0,
  178. queue,
  179. next: [],
  180. hostReturn: c.mode === 'host' && queue.some((id) => id !== c.administratorId),
  181. createdAt: now,
  182. updatedAt: now,
  183. }
  184. this.store.saveRun(owner, run)
  185. this.uploads.markReferenced(body.fileIds, owner)
  186. return run
  187. })
  188. if (this.store.require<Run>(owner, 'run', result.id).status === 'queued')
  189. void this.execute(owner, result.id)
  190. return this.store.require<Run>(owner, 'run', result.id)
  191. }
  192. private async execute(owner: string, id: string): Promise<void> {
  193. if (this.executing.has(id) || this.closing) return
  194. this.executing.add(id)
  195. try {
  196. while (!this.closing) {
  197. const run = this.store.require<Run>(owner, 'run', id)
  198. if (!['queued', 'running'].includes(run.status)) break
  199. if (!this.userActive(owner)) throw new HttpError(403, '账号已停用', 'account_disabled')
  200. const c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
  201. if (!run.queue.length) {
  202. if (
  203. c.kind === 'direct' ||
  204. run.round + 1 >= c.maxReplyRounds ||
  205. (!run.next.length && !run.hostReturn)
  206. ) {
  207. run.status = 'complete'
  208. this.store.saveRun(owner, run)
  209. this.notify(
  210. owner,
  211. c,
  212. run,
  213. this.store
  214. .messages(owner, c.id)
  215. .filter((m) => m.runId === id && m.role === 'assistant')
  216. .at(-1),
  217. )
  218. break
  219. }
  220. run.round += 1
  221. run.queue = run.hostReturn ? [c.administratorId] : [...new Set(run.next)]
  222. run.hostReturn = false
  223. run.next = []
  224. this.store.saveRun(owner, run)
  225. }
  226. const agent = this.store.require<Agent>(owner, 'agent', run.queue[0]!)
  227. run.turnConfiguration = {
  228. mode: c.mode,
  229. administratorId: c.administratorId,
  230. members: c.memberIds.map((id) => {
  231. const a = this.store.require<Agent>(owner, 'agent', id)
  232. return { id: a.id, name: a.name }
  233. }),
  234. }
  235. run.status = 'running'
  236. run.activeAgentId = agent.id
  237. this.store.saveRun(owner, run)
  238. const message = await this.turn(owner, c, agent, run)
  239. await this.onMessage(owner, message).catch(() => {})
  240. if (this.closing) return
  241. this.advance(owner, run.id, agent.id, message)
  242. }
  243. } catch (error) {
  244. if (!this.closing) {
  245. const run = this.store.require<Run>(owner, 'run', id)
  246. if (!['interrupted', 'uncertain'].includes(run.status)) {
  247. run.status = 'failed'
  248. run.error = (error instanceof Error ? error.message : '执行失败').slice(0, 1000)
  249. this.store.saveRun(owner, run)
  250. this.store.saveMessage(owner, {
  251. id:randomUUID(), conversationId:run.conversationId, seq:0, role:'system',
  252. content:`执行失败:${run.error}`, reasoning:'', runId:run.id, status:'failed',
  253. attachments:[], tools:[], createdAt:Date.now(),
  254. })
  255. this.notify(owner, this.store.require(owner, 'conversation', run.conversationId), run)
  256. }
  257. }
  258. } finally {
  259. this.executing.delete(id)
  260. }
  261. }
  262. private advance(owner: string, runId: string, agentId: string, message: Message): void {
  263. this.store.atomic(() => {
  264. const run = this.store.require<Run>(owner, 'run', runId)
  265. if (run.status === 'interrupted') return
  266. const c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
  267. const configuration = run.turnConfiguration
  268. if (!configuration) throw new Error('运行配置缺失,已停止自动协作')
  269. if (configuration.mode === 'free' || agentId === configuration.administratorId)
  270. run.next.push(
  271. ...mentionedAgents(message.content, configuration.members).filter((id) => id !== agentId),
  272. )
  273. if (
  274. c.kind === 'group' &&
  275. configuration.mode === 'host' &&
  276. agentId !== configuration.administratorId
  277. )
  278. run.hostReturn = true
  279. if (run.queue[0] === agentId) run.queue.shift()
  280. run.activeAgentId = run.queue[0]
  281. run.currentMessageId = undefined
  282. run.error = undefined
  283. run.status = 'running'
  284. this.store.saveRun(owner, run)
  285. })
  286. }
  287. private async turn(
  288. owner: string,
  289. c: Conversation,
  290. agent: Agent,
  291. run: Run,
  292. recovering = false,
  293. ): Promise<Message> {
  294. const key = `${c.id}:${agent.id}`,
  295. target = this.nodes.target(owner, agent.nodeId)
  296. const gateway = new WorkspaceGateway(target)
  297. run.activeAgentId = agent.id
  298. this.store.saveRun(owner, run)
  299. let binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
  300. let message =
  301. recovering && run.currentMessageId
  302. ? this.store.require<Message>(owner, 'message', run.currentMessageId)
  303. : undefined
  304. if (!message) {
  305. message = {
  306. id: randomUUID(),
  307. conversationId: c.id,
  308. seq: 0,
  309. role: 'assistant',
  310. agentId: agent.id,
  311. agentName: agent.name,
  312. content: '',
  313. reasoning: '',
  314. status: 'streaming',
  315. runId: run.id,
  316. tools: [],
  317. attachments: [],
  318. createdAt: Date.now(),
  319. }
  320. run.currentMessageId = message.id
  321. this.store.atomic(() => {
  322. this.store.saveMessage(owner, message!)
  323. this.store.saveRun(owner, run)
  324. })
  325. }
  326. const resultMessage = message
  327. let submitted = recovering,
  328. settled = false,
  329. completedEvidence = false,
  330. completing = false,
  331. runtimeId = '',
  332. lastFlush = 0
  333. let resolveTurn!: (m: Message) => void, rejectTurn!: (e: Error) => void
  334. const completion = new Promise<Message>((resolve, reject) => {
  335. resolveTurn = resolve
  336. rejectTurn = reject
  337. })
  338. // Register rejection immediately; setup RPCs can still be awaiting a reply.
  339. void completion.catch(() => {})
  340. const finish = (error?: Error) => {
  341. if (settled) return
  342. settled = true
  343. this.live.delete(key)
  344. if (error) {
  345. const current = this.store.require<Run>(owner, 'run', run.id)
  346. resultMessage.status =
  347. current.status === 'interrupted' ? 'interrupted' : submitted ? 'uncertain' : 'failed'
  348. if (submitted && current.status !== 'interrupted') {
  349. current.status = 'uncertain'
  350. current.error = '执行状态待确认,未自动重发'
  351. this.store.saveRun(owner, current)
  352. }
  353. this.store.saveMessage(owner, resultMessage)
  354. rejectTurn(error)
  355. } else {
  356. resultMessage.status = 'complete'
  357. this.store.saveMessage(owner, resultMessage)
  358. resolveTurn(resultMessage)
  359. }
  360. gateway.close()
  361. }
  362. gateway.onDisconnect = () =>
  363. finish(completedEvidence ? undefined : new Error('Hermes 连接断开'))
  364. gateway.onEvent = (frame: GatewayFrame) => {
  365. if (settled || !runtimeId || frame.session_id !== runtimeId) return
  366. const p = frame.payload ?? {},
  367. type = frame.type
  368. if (type === 'message.delta') resultMessage.content += String(p.text ?? p.delta ?? '')
  369. else if (type === 'reasoning.delta')
  370. resultMessage.reasoning += String(p.text ?? p.delta ?? '')
  371. else if (type === 'message.interim') {
  372. resultMessage.content += '\n\n'
  373. } else if (type.startsWith('tool.')) {
  374. const id = String(p.tool_id ?? p.id ?? ''),
  375. index = resultMessage.tools.findIndex((t) => t.id === id)
  376. const value = { ...p, id, status: type }
  377. if (index >= 0) resultMessage.tools[index] = { ...resultMessage.tools[index], ...value }
  378. else resultMessage.tools.push(value)
  379. } else if (
  380. ['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(
  381. type,
  382. )
  383. ) {
  384. const upstreamId = String(p.request_id ?? p.requestId ?? p.id ?? '')
  385. const interaction: WorkspaceInteraction = {
  386. id: randomUUID(),
  387. conversationId: c.id,
  388. runId: run.id,
  389. agentId: agent.id,
  390. kind: type.startsWith('approval') ? 'approval' : 'clarification',
  391. message: String(p.question ?? p.message ?? p.prompt ?? '需要确认'),
  392. choices: Array.isArray(p.choices) ? p.choices.map(String) : [],
  393. resolved: false,
  394. }
  395. this.store.put(owner, 'interaction', interaction.id, interaction)
  396. this.store.put(owner, 'interaction-binding', interaction.id, { key, upstreamId })
  397. this.store.event(owner, 'interaction.changed', interaction, c.id)
  398. const current = this.store.require<Run>(owner, 'run', run.id)
  399. current.status = 'waiting'
  400. this.store.saveRun(owner, current)
  401. this.notify(owner, c, current, undefined, interaction)
  402. } else if (['message.complete', 'run.completed'].includes(type)) {
  403. if (typeof p.text === 'string') resultMessage.content = p.text
  404. if (p.status === 'interrupted') {
  405. const current = this.store.require<Run>(owner, 'run', run.id)
  406. current.status = 'interrupted'
  407. this.store.saveRun(owner, current)
  408. finish(new Error('已停止'))
  409. } else if (p.error || p.status === 'failed') {
  410. submitted = false
  411. finish(new HttpError(502, String(p.error ?? '运行失败'), 'run_failed'))
  412. } else if (!completing) {
  413. completedEvidence = true
  414. completing = true
  415. let timeout: ReturnType<typeof setTimeout>
  416. void Promise.race([
  417. gateway.rpc('session.usage', { session_id: runtimeId }),
  418. new Promise<undefined>((resolve) => {
  419. timeout = setTimeout(() => resolve(undefined), 1000)
  420. }),
  421. ])
  422. .then((usage) => {
  423. if (usage && !this.closing) {
  424. const used = usage.context_used ?? usage.used_tokens,
  425. limit = usage.context_max ?? usage.context_limit
  426. this.store.put(owner, 'context', c.id, {
  427. ...usage,
  428. usedTokens: used,
  429. limitTokens: limit,
  430. percent:
  431. typeof used === 'number' && typeof limit === 'number' && limit > 0
  432. ? Math.round((used / limit) * 1000) / 10
  433. : undefined,
  434. })
  435. this.store.event(
  436. owner,
  437. 'context.changed',
  438. this.store.get(owner, 'context', c.id),
  439. c.id,
  440. )
  441. }
  442. })
  443. .catch(() => {})
  444. .finally(() => {
  445. clearTimeout(timeout)
  446. finish()
  447. })
  448. }
  449. return
  450. } else if (['error', 'message.error', 'run.failed'].includes(type)) {
  451. submitted = false
  452. finish(new HttpError(502, String(p.message ?? p.error ?? '运行失败'), 'run_failed'))
  453. return
  454. } else if (['session.usage', 'usage.update', 'context.update'].includes(type)) {
  455. this.store.put(owner, 'context', c.id, p)
  456. this.store.event(owner, 'context.changed', p, c.id)
  457. } else if (type === 'session.info' && binding) {
  458. const storedId = p.stored_session_id ?? p.session_key
  459. if (typeof storedId === 'string' && storedId && storedId !== binding.storedId) {
  460. binding.aliases = [...new Set([...binding.aliases, binding.storedId, storedId])]
  461. binding.storedId = storedId
  462. this.store.put(owner, 'binding', key, binding)
  463. }
  464. }
  465. if (Date.now() - lastFlush >= 100) {
  466. this.store.saveMessage(owner, resultMessage)
  467. lastFlush = Date.now()
  468. }
  469. }
  470. try {
  471. await gateway.connect()
  472. const opened = binding?.storedId
  473. ? await gateway.rpc('session.resume', {
  474. profile: agent.profile,
  475. session_id: binding.storedId,
  476. omit_messages: true,
  477. close_on_disconnect: false,
  478. })
  479. : await gateway.rpc('session.create', {
  480. profile: agent.profile,
  481. title: `Yaoyao ${c.id}`,
  482. source: 'yaoyao_workspace',
  483. hidden: true,
  484. room_plumbing: true,
  485. close_on_disconnect: false,
  486. })
  487. runtimeId = String(opened.session_id ?? '')
  488. const storedId = String(
  489. opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? binding?.storedId ?? '',
  490. )
  491. if (
  492. !runtimeId ||
  493. !storedId ||
  494. (opened.info?.profile_name && opened.info.profile_name !== agent.profile)
  495. )
  496. throw new Error('Hermes 会话身份不匹配')
  497. binding = {
  498. id: key,
  499. nodeId: agent.nodeId,
  500. profile: agent.profile,
  501. storedId,
  502. runtimeId,
  503. aliases: [
  504. ...new Set([
  505. ...(binding?.aliases ?? []),
  506. ...(binding ? [binding.storedId] : []),
  507. storedId,
  508. ]),
  509. ],
  510. runId: run.id,
  511. messageId: resultMessage.id,
  512. }
  513. this.store.put(owner, 'binding', key, binding)
  514. this.live.set(key, { gateway, runtimeId, runId: run.id, agentId: agent.id, done: finish })
  515. if (this.closing || this.store.require<Run>(owner, 'run', run.id).status === 'interrupted')
  516. throw new Error('运行已停止')
  517. if (recovering) {
  518. if (opened.running) {
  519. const current = this.store.require<Run>(owner, 'run', run.id)
  520. current.status = 'running'
  521. this.store.saveRun(owner, current)
  522. } else {
  523. const response = await target.session.request(
  524. `/api/sessions/${encodeURIComponent(storedId)}/messages`,
  525. {
  526. search: new URLSearchParams({
  527. profile: agent.profile,
  528. limit: '500',
  529. order: 'latest',
  530. include_compacted: 'true',
  531. }),
  532. },
  533. )
  534. if (response.status !== 200) throw new Error('无法核对历史')
  535. const history = JSON.parse(response.body.toString()).messages ?? []
  536. const marker = `[yaoyao-run:${run.id}:${resultMessage.id}]`
  537. const index = history.findLastIndex(
  538. (m: any) => m.role === 'user' && String(m.content ?? m.text).includes(marker),
  539. )
  540. const answer =
  541. index >= 0
  542. ? history
  543. .slice(index + 1)
  544. .filter((m: any) => m.role === 'assistant' && (m.content || m.text))
  545. .at(-1)
  546. : undefined
  547. if (!answer) throw new Error('无法确认本轮是否执行完成,请检查后停止此轮')
  548. resultMessage.content = String(answer.content ?? answer.text)
  549. finish()
  550. }
  551. } else {
  552. if (opened.running) throw new HttpError(409, '上游会话仍在运行', 'session_busy')
  553. const trigger = this.store.require<Message>(owner, 'message', run.messageId)
  554. const attachmentRefs: string[] = []
  555. for (const file of trigger.attachments) {
  556. const record = this.uploads.records([file.id], owner)[0]!
  557. const bytes = readFileSync(record.path).toString('base64')
  558. const attached = record.mimeType.startsWith('image/')
  559. ? await gateway.rpc('image.attach_bytes', {
  560. session_id: runtimeId,
  561. filename: record.name,
  562. content_base64: bytes,
  563. })
  564. : await gateway.rpc('file.attach', {
  565. session_id: runtimeId,
  566. name: record.name,
  567. data_url: `data:${record.mimeType};base64,${bytes}`,
  568. })
  569. if (attached.ref_text) attachmentRefs.push(String(attached.ref_text))
  570. }
  571. const members = run.turnConfiguration!.members
  572. const rules = [
  573. `你是 ${agent.name}。以下是用户为这个独立 Agent 配置的角色与规则(版本 ${agent.revision}):\n${agent.instructions}`,
  574. c.kind === 'group'
  575. ? `你正在群聊「${c.name}」发言。群成员:${members.map((a) => `@${a.name} (id=${a.id})`).join('、')}。\n群规则:${c.instructions}\n${c.mode === 'host' ? (agent.id === c.administratorId ? '你是管理员。必要时用精确 @成员名称 委派工作;收到结果后复核并给用户结论。任务完成时不要继续 @。' : '执行当前委派任务。公开给出结果,由管理员复核;不要安排其他成员。') : '按自己的职责回复,只在需要协作时 @成员。不要重复已完成的工作。'}`
  576. : '',
  577. '角色规则不赋予额外工具权限;仍遵守基础 Hermes 的工具和安全约束。',
  578. `[yaoyao-run:${run.id}:${resultMessage.id}]`,
  579. ]
  580. .filter(Boolean)
  581. .join('\n\n')
  582. const text =
  583. c.kind === 'group'
  584. ? this.store
  585. .messages(owner, c.id)
  586. .filter((m) => !['queued','streaming'].includes(m.status))
  587. .map(
  588. (m) => `${m.role === 'user' ? '用户' : (m.agentName ?? 'Agent')}:${m.content}`,
  589. )
  590. .join('\n\n')
  591. : trigger.content
  592. submitted = true
  593. await gateway.rpc('prompt.submit', {
  594. session_id: runtimeId,
  595. text: `${rules}\n\n${text}\n${attachmentRefs.join('\n')}`,
  596. })
  597. }
  598. return await completion
  599. } catch (error) {
  600. finish(error instanceof Error ? error : new Error('执行失败'))
  601. return await completion
  602. }
  603. }
  604. async respond(owner: string, id: string, answer: string): Promise<void> {
  605. const interaction = this.store.require<WorkspaceInteraction>(owner, 'interaction', id)
  606. if (interaction.resolved) return
  607. const b = this.store.require<{ key: string; upstreamId: string }>(
  608. owner,
  609. 'interaction-binding',
  610. id,
  611. ),
  612. live = this.live.get(b.key)
  613. if (!live || live.runId !== interaction.runId)
  614. throw new HttpError(409, '请先恢复此轮连接', 'interaction_offline')
  615. if (
  616. interaction.kind === 'approval' &&
  617. !['once', 'always', 'deny', 'allow', 'approve'].includes(answer)
  618. )
  619. throw new HttpError(400, '审批选项无效', 'invalid_approval')
  620. await live.gateway.rpc(
  621. interaction.kind === 'approval' ? 'approval.respond' : 'clarify.respond',
  622. {
  623. session_id: live.runtimeId,
  624. request_id: b.upstreamId,
  625. ...(interaction.kind === 'approval' ? { choice: answer } : { answer }),
  626. },
  627. )
  628. interaction.resolved = true
  629. this.store.put(owner, 'interaction', id, interaction)
  630. this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId)
  631. const run = this.store.require<Run>(owner, 'run', interaction.runId)
  632. run.status = 'running'
  633. this.store.saveRun(owner, run)
  634. }
  635. async stop(owner: string, id: string): Promise<void> {
  636. const run = this.store.require<Run>(owner, 'run', id)
  637. if (['complete', 'failed', 'interrupted'].includes(run.status)) return
  638. let live = [...this.live.values()].find((t) => t.runId === id)
  639. if (live) {
  640. await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId })
  641. run.status = 'interrupted'
  642. this.store.saveRun(owner, run)
  643. live.done(new Error('已停止'))
  644. } else {
  645. const bindings = this.store
  646. .list<WorkspaceBinding>(owner, 'binding')
  647. .filter((b) => b.runId === id)
  648. for (const b of bindings) {
  649. const g = new WorkspaceGateway(this.nodes.target(owner, b.nodeId))
  650. try {
  651. await g.connect()
  652. const s = await g.rpc('session.resume', {
  653. profile: b.profile,
  654. session_id: b.storedId,
  655. close_on_disconnect: false,
  656. omit_messages: true,
  657. })
  658. if (s.running) await g.rpc('session.interrupt', { session_id: s.session_id })
  659. } finally {
  660. g.close()
  661. }
  662. }
  663. run.status = 'interrupted'
  664. this.store.saveRun(owner, run)
  665. }
  666. for (const i of this.store
  667. .list<WorkspaceInteraction>(owner, 'interaction')
  668. .filter((i) => i.runId === id && !i.resolved)) {
  669. i.resolved = true
  670. this.store.put(owner, 'interaction', i.id, i)
  671. this.store.event(owner, 'interaction.changed', i, i.conversationId)
  672. }
  673. }
  674. async reconcile(owner: string, id: string): Promise<void> {
  675. if (this.executing.has(id) || this.closing) return
  676. const run = this.store.require<Run>(owner, 'run', id)
  677. if (run.status !== 'uncertain' || !run.currentMessageId || !run.queue.length) return
  678. this.executing.add(id)
  679. try {
  680. const agent = this.store.require<Agent>(owner, 'agent', run.queue[0]!),
  681. c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
  682. const message = await this.turn(owner, c, agent, run, true)
  683. this.advance(owner, id, agent.id, message)
  684. } finally {
  685. this.executing.delete(id)
  686. }
  687. await this.execute(owner, id)
  688. }
  689. close(): void {
  690. this.closing = true
  691. for (const t of this.live.values()) {
  692. t.gateway.close()
  693. t.done(new Error('服务关闭'))
  694. }
  695. this.live.clear()
  696. }
  697. }