workspaceScheduler.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import { randomUUID } from 'node:crypto'
  2. import { WorkspaceStore } from './workspaceStore.js'
  3. import { HttpError } from './errors.js'
  4. import { mentionedAgents } from './workspaceMentions.js'
  5. import type { WorkspaceAgent as Agent, WorkspaceConversation as Conversation, WorkspaceMessage as Message, WorkspaceRun as Run, WorkspaceInteraction } from '../shared/workspace.js'
  6. export const NO_REPLY = '[[YAOYAO_NO_REPLY_V1]]'
  7. export const HOST_FALLBACK = '我还不能确定你希望我处理什么,请补充具体目标、范围,或明确需要我协调的 Agent。'
  8. const terminal = (status: string) => ['complete', 'failed', 'interrupted'].includes(status)
  9. export interface Work {
  10. id: string
  11. runId: string
  12. conversationId: string
  13. agentId: string
  14. messageId: string
  15. triggerSeq: number
  16. depth: number
  17. batchId: string
  18. reviewOf?: string
  19. replyMode: 'mentioned' | 'automatic'
  20. requiredReply: boolean
  21. status: Run['status']
  22. currentMessageId?: string
  23. submitted?: boolean
  24. cancelRequested?: boolean
  25. planned?: boolean
  26. silent?: boolean
  27. hadInteraction?: boolean
  28. error?: string
  29. contextThroughSeq?: number
  30. turnConfiguration?: { mode: 'host' | 'free'; administratorId: string; members: Array<Pick<Agent, 'id' | 'name'>> }
  31. createdAt: number
  32. }
  33. /** Durable per-member work and cascade ledger; Hermes transport lives in WorkspaceRuntime. */
  34. export abstract class WorkspaceScheduler {
  35. protected closing = false
  36. protected executing = new Set<string>()
  37. private wakePending = false
  38. private pumping = false
  39. private retryTimer?: ReturnType<typeof setTimeout>
  40. private recoverAfter = new Map<string, number>()
  41. private attempts = new Map<string, number>()
  42. private interrupting = new Set<string>()
  43. onMessage: (owner: string, message: Message) => Promise<void> = async () => {}
  44. onNotify: (owner: string, c: Conversation, run: Run, message?: Message, interaction?: WorkspaceInteraction) => void = () => {}
  45. constructor(readonly store: WorkspaceStore, readonly userActive: (owner: string) => boolean = () => true) {
  46. for (const owner of store.owners()) {
  47. // Forward the already-admitted v0.3.x turn without replaying its prompt.
  48. for (const root of store.list<Run & { queue?: string[]; next?: string[]; hostReturn?: boolean; round: number; currentMessageId?: string; turnConfiguration?: Work['turnConfiguration'] }>(owner, 'run')) {
  49. if (terminal(root.status) || this.works(owner, root.id).length) continue
  50. const c = store.require<Conversation>(owner, 'conversation', root.conversationId)
  51. const trigger = store.require<Message>(owner, 'message', root.messageId)
  52. const continuation = root.queue?.length === 0
  53. const ids = continuation ? root.hostReturn ? [c.administratorId] : root.next ?? [] : root.queue ?? [root.activeAgentId ?? c.administratorId]
  54. if (!ids.length && root.currentMessageId) {
  55. const agentId = store.get<Message>(owner, 'message', root.currentMessageId)?.agentId ?? root.activeAgentId
  56. if (agentId) ids.push(agentId)
  57. }
  58. if (!ids.length) { root.status = root.stopRequested ? 'interrupted' : 'complete'; store.saveRun(owner, root); continue }
  59. const last = store.messages(owner, c.id).filter(m => m.runId === root.id).at(-1)
  60. for (const [index, id] of ids.entries()) {
  61. const work = this.enqueue(owner, root, id, root.round + (continuation && !root.hostReturn ? 1 : 0), root.id, last?.seq ?? trigger.seq, 'mentioned', id === c.administratorId)
  62. if (index === 0 && root.currentMessageId) {
  63. Object.assign(work, { currentMessageId: root.currentMessageId, submitted: true, status: 'uncertain', turnConfiguration: root.turnConfiguration })
  64. store.put(owner, 'turn', work.id, work)
  65. const key = `${c.id}:${id}`
  66. const binding = store.get<{ runId: string; messageId: string; taskId?: string }>(owner, 'binding', key)
  67. if (binding?.runId === root.id && binding.messageId === root.currentMessageId) {
  68. binding.taskId = work.id; store.put(owner, 'binding', key, binding)
  69. }
  70. }
  71. }
  72. }
  73. for (const work of this.works(owner)) {
  74. if (['running', 'waiting'].includes(work.status)) {
  75. work.status = work.submitted ? 'uncertain' : 'queued'
  76. work.error = work.submitted ? '服务已重启,正在核对原执行' : undefined
  77. store.put(owner, 'turn', work.id, work)
  78. }
  79. }
  80. }
  81. }
  82. protected notify(owner: string, c: Conversation, run: Run, message?: Message, interaction?: WorkspaceInteraction): void {
  83. try { this.onNotify(owner, c, run, message, interaction) } catch { /* Push cannot change execution. */ }
  84. }
  85. protected abstract performTurn(owner: string, c: Conversation, agent: Agent, work: Work, recovering: boolean): Promise<Message>
  86. protected abstract interruptTurn(owner: string, work: Work): Promise<void>
  87. protected works(owner: string, runId?: string): Work[] {
  88. return this.store.db.prepare(`SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' ${runId ? "AND json_extract(data,'$.runId')=?" : ''}`).all(...(runId ? [owner, runId] : [owner]))
  89. .map(row => JSON.parse(String(row.data)) as Work)
  90. }
  91. private pendingWorks(owner: string): Work[] {
  92. return this.store.db.prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' AND (json_extract(data,'$.status') NOT IN ('complete','failed','interrupted') OR coalesce(json_extract(data,'$.planned'),0)=0)").all(owner)
  93. .map(row => JSON.parse(String(row.data)) as Work)
  94. }
  95. protected getWork(owner: string, id: string): Work { return this.store.require(owner, 'turn', id) }
  96. protected saveWork(owner: string, work: Work): void {
  97. this.store.atomic(() => { this.store.put(owner, 'turn', work.id, work); this.updateRoot(owner, work.runId) })
  98. }
  99. protected enqueue(owner: string, root: Run, agentId: string, depth: number, batchId: string, triggerSeq: number, replyMode: Work['replyMode'], requiredReply: boolean, reviewOf?: string): Work {
  100. const existing = this.works(owner, root.id).find(w => reviewOf ? w.reviewOf === reviewOf : w.agentId === agentId && w.depth === depth && !w.reviewOf)
  101. if (existing) return existing
  102. const work: Work = { id: randomUUID(), runId: root.id, conversationId: root.conversationId, agentId, messageId: root.messageId, depth, batchId, triggerSeq, replyMode, requiredReply, reviewOf, status: 'queued', createdAt: Date.now() }
  103. this.store.put(owner, 'turn', work.id, work)
  104. return work
  105. }
  106. protected admit(owner: string, root: Run, c: Conversation, trigger: Message): void {
  107. this.store.put(owner, 'run', root.id, root)
  108. const ids = c.kind === 'direct' || c.mode === 'host' ? [c.administratorId]
  109. : root.mentionIds.length ? root.mentionIds : [...new Set([c.administratorId, ...c.autoReplyIds])]
  110. for (const id of ids) this.enqueue(owner, root, id, 0, root.id, trigger.seq,
  111. c.kind === 'direct' ? 'mentioned' : c.mode === 'host' || !root.mentionIds.length ? 'automatic' : 'mentioned', c.kind === 'group' && id === c.administratorId && (c.mode === 'host' || !root.mentionIds.length))
  112. this.updateRoot(owner, root.id)
  113. }
  114. start(): void { this.wake() }
  115. wake(): void {
  116. if (this.closing || this.wakePending) return
  117. this.wakePending = true
  118. queueMicrotask(() => { this.wakePending = false; if (!this.closing) this.pump() })
  119. }
  120. private retrySoon(): void {
  121. if (this.closing || this.retryTimer) return
  122. this.retryTimer = setTimeout(() => { this.retryTimer = undefined; this.wake() }, 500)
  123. this.retryTimer.unref()
  124. }
  125. private updateRoot(owner: string, id: string): void {
  126. const root = this.store.require<Run>(owner, 'run', id), tasks = this.works(owner, id)
  127. const active = tasks.filter(t => !terminal(t.status))
  128. const done = !active.length && tasks.every(t => t.planned)
  129. const wasTerminal = terminal(root.status)
  130. root.round = Math.max(0, ...tasks.map(t => t.depth))
  131. root.activeAgentId = active.find(t => t.status !== 'queued')?.agentId ?? active[0]?.agentId
  132. if (done) {
  133. const interrupted = root.stopRequested || tasks.some(t => t.requiredReply && t.status === 'interrupted') || (tasks.length > 0 && tasks.every(t => t.status === 'interrupted'))
  134. const failed = tasks.some(t => t.status === 'failed' && (t.requiredReply || this.store.require<Conversation>(owner, 'conversation', root.conversationId).kind === 'direct'))
  135. root.status = interrupted ? 'interrupted' : failed ? 'failed' : 'complete'
  136. } else {
  137. root.status = active.some(t => t.status === 'uncertain') ? 'uncertain' : active.some(t => t.status === 'running') ? 'running' : active.some(t => t.status === 'waiting') ? 'waiting' : tasks.some(t => t.status !== 'queued') ? 'running' : 'queued'
  138. }
  139. root.error = tasks.find(t => t.status === 'uncertain' || t.status === 'failed')?.error
  140. this.store.saveRun(owner, root)
  141. if (done && !wasTerminal && root.status !== 'interrupted') {
  142. const c = this.store.require<Conversation>(owner, 'conversation', root.conversationId)
  143. if (root.status === 'failed' && c.kind === 'direct') this.store.saveMessage(owner, { id: randomUUID(), conversationId: c.id, seq: 0, role: 'system', content: `执行失败:${root.error ?? '运行失败'}`, reasoning: '', status: 'failed', runId: root.id, attachments: [], tools: [], createdAt: Date.now() })
  144. this.notify(owner, c, root, this.store.messages(owner, c.id).filter(m => m.runId === id && m.visible !== false).at(-1))
  145. }
  146. }
  147. private plan(owner: string, id: string): void {
  148. this.store.atomic(() => {
  149. const work = this.getWork(owner, id)
  150. if (!terminal(work.status) || work.planned) return
  151. const root = this.store.require<Run>(owner, 'run', work.runId), c = this.store.require<Conversation>(owner, 'conversation', work.conversationId)
  152. work.planned = true
  153. this.store.put(owner, 'turn', work.id, work)
  154. if (root.stopRequested || c.archived || c.kind === 'direct') { this.updateRoot(owner, root.id); return }
  155. const config = work.turnConfiguration ?? { mode: c.mode, administratorId: c.administratorId, members: c.memberIds.map(id => this.store.require<Agent>(owner, 'agent', id)) }
  156. const message = work.currentMessageId ? this.store.get<Message>(owner, 'message', work.currentMessageId) : undefined
  157. if (config.mode === 'host' && work.agentId !== config.administratorId) {
  158. const batch = this.works(owner, root.id).filter(t => t.batchId === work.batchId && !t.reviewOf)
  159. if (batch.every(t => terminal(t.status))) {
  160. const through = Math.max(work.triggerSeq, ...batch.map(t => t.currentMessageId ? this.store.get<Message>(owner, 'message', t.currentMessageId)?.seq ?? 0 : 0))
  161. this.enqueue(owner, root, c.administratorId, work.depth, `review:${work.batchId}`, through, 'automatic', true, work.batchId)
  162. }
  163. } else if (work.status === 'complete' && !work.silent && message) {
  164. const nextDepth = work.depth + 1
  165. const mentions = mentionedAgents(message.content, config.members).filter(id => id !== work.agentId && c.memberIds.includes(id))
  166. const targets = mentions.length ? mentions : config.mode === 'free' ? c.autoReplyIds.filter(id => id !== work.agentId && c.memberIds.includes(id)) : []
  167. if (c.maxReplyRounds === -1 || nextDepth < c.maxReplyRounds) {
  168. for (const target of targets) this.enqueue(owner, root, target, nextDepth, work.id, message.seq, mentions.includes(target) ? 'mentioned' : 'automatic', false)
  169. } else if (targets.length && !this.store.get(owner, 'limit-notice', root.id)) {
  170. this.store.put(owner, 'limit-notice', root.id, { id: root.id })
  171. this.store.saveMessage(owner, { id: randomUUID(), conversationId: c.id, seq: 0, role: 'system', content: '已达到自动协作轮数上限,本轮不再自动分派。', reasoning: '', status: 'complete', runId: root.id, attachments: [], tools: [], createdAt: Date.now() })
  172. }
  173. }
  174. this.updateRoot(owner, root.id)
  175. })
  176. }
  177. private pump(): void {
  178. if (this.pumping || this.closing) return
  179. this.pumping = true
  180. try {
  181. let all = this.store.owners().flatMap(owner => this.pendingWorks(owner).map(work => ({ owner, work })))
  182. for (const { owner, work } of all) {
  183. if (['running', 'waiting'].includes(work.status) && !this.executing.has(work.id)) {
  184. work.status = work.submitted ? 'uncertain' : 'queued'
  185. this.saveWork(owner, work)
  186. }
  187. }
  188. for (const { owner, work } of all) if (terminal(work.status) && !work.planned && !this.executing.has(work.id)) this.plan(owner, work.id)
  189. all = this.store.owners().flatMap(owner => this.pendingWorks(owner).map(work => ({ owner, work })))
  190. all.sort((a, b) => {
  191. const am = this.store.require<Message>(a.owner, 'message', a.work.messageId), bm = this.store.require<Message>(b.owner, 'message', b.work.messageId)
  192. return am.createdAt - bm.createdAt || (a.work.conversationId === b.work.conversationId ? am.seq - bm.seq : 0) || a.work.createdAt - b.work.createdAt || a.work.id.localeCompare(b.work.id)
  193. })
  194. for (const { owner, work: candidate } of all) {
  195. const work = this.getWork(owner, candidate.id)
  196. if (work.cancelRequested && work.status === 'uncertain' && this.executing.has(work.id)) {
  197. if ((this.recoverAfter.get(work.id) ?? 0) > Date.now()) { this.retrySoon(); continue }
  198. if (!this.interrupting.has(work.id)) {
  199. this.interrupting.add(work.id)
  200. void this.interruptTurn(owner, work).catch(error => {
  201. if (this.closing) return
  202. const current = this.getWork(owner, work.id)
  203. if (terminal(current.status)) return
  204. current.status = 'uncertain'; current.error = `停止状态待确认:${error instanceof Error ? error.message : '连接中断'}`
  205. this.saveWork(owner, current)
  206. const attempt = this.attempts.get(work.id) ?? 0
  207. this.attempts.set(work.id, attempt + 1)
  208. this.recoverAfter.set(work.id, Date.now() + Math.min(30_000, 500 * 2 ** Math.min(attempt, 6)))
  209. this.retrySoon()
  210. }).finally(() => { this.interrupting.delete(work.id); this.wake() }).catch(() => this.retrySoon())
  211. }
  212. continue
  213. }
  214. if (this.executing.size >= 4 || !['queued', 'uncertain'].includes(work.status) || this.executing.has(work.id)) continue
  215. if (!this.userActive(owner)) { this.retrySoon(); continue }
  216. const c = this.store.require<Conversation>(owner, 'conversation', work.conversationId), root = this.store.require<Run>(owner, 'run', work.runId)
  217. if (work.status === 'queued' && c.mode === 'host' && work.depth === 0 && work.batchId === root.id && work.requiredReply && !work.currentMessageId) {
  218. work.agentId = c.administratorId
  219. }
  220. if (work.status === 'queued' && (c.archived || root.stopRequested || !c.memberIds.includes(work.agentId))) {
  221. work.status = 'interrupted'; work.error = '执行前成员已移除或聊天已停止'; this.saveWork(owner, work); this.wake(); continue
  222. }
  223. const occupied = all.map(entry => this.getWork(entry.owner, entry.work.id)).filter(t => (['running', 'waiting', 'uncertain'].includes(t.status) || this.executing.has(t.id)) && t.id !== work.id)
  224. if (occupied.some(t => t.conversationId === c.id && t.agentId === work.agentId)) continue
  225. const inRoom = occupied.filter(t => t.conversationId === c.id)
  226. if (work.status === 'queued' && (occupied.length >= 4 || inRoom.length >= 3)) continue
  227. if (work.status === 'uncertain' && (this.recoverAfter.get(work.id) ?? 0) > Date.now()) { this.retrySoon(); continue }
  228. if (c.mode === 'host' || c.kind === 'direct') {
  229. if (inRoom.some(t => c.kind === 'direct' || t.runId !== work.runId || t.batchId !== work.batchId || t.agentId === c.administratorId || work.agentId === c.administratorId)) continue
  230. }
  231. this.executing.add(work.id)
  232. const recovering = work.status === 'uncertain'
  233. if (!recovering) {
  234. work.status = 'running'
  235. if (c.kind === 'group' && c.mode === 'host' && work.agentId === c.administratorId) { work.requiredReply = true; work.replyMode = 'automatic' }
  236. work.turnConfiguration = { mode: c.mode, administratorId: c.administratorId, members: c.memberIds.map(id => { const a = this.store.require<Agent>(owner, 'agent', id); return { id, name: a.name } }) }
  237. this.saveWork(owner, work)
  238. }
  239. void this.executeWork(owner, work, recovering).catch(() => this.retrySoon())
  240. }
  241. } catch { this.retrySoon() } finally { this.pumping = false }
  242. }
  243. private async executeWork(owner: string, work: Work, recovering: boolean): Promise<void> {
  244. try {
  245. if (work.cancelRequested) await this.interruptTurn(owner, work)
  246. else {
  247. const c = this.store.require<Conversation>(owner, 'conversation', work.conversationId)
  248. const agent = this.store.require<Agent>(owner, 'agent', work.agentId)
  249. const message = await this.performTurn(owner, c, agent, work, recovering)
  250. if (message.visible !== false) await this.onMessage(owner, message).catch(() => {})
  251. }
  252. } catch (error) {
  253. if (this.closing) return
  254. const current = this.getWork(owner, work.id)
  255. if (!terminal(current.status) && current.status !== 'uncertain') {
  256. current.status = current.submitted ? 'uncertain' : 'failed'
  257. current.error = error instanceof Error ? error.message : '执行失败'
  258. this.saveWork(owner, current)
  259. }
  260. if (current.status === 'failed' && !current.currentMessageId) {
  261. current.currentMessageId = randomUUID()
  262. this.store.saveMessage(owner, { id: current.currentMessageId, conversationId: current.conversationId, seq: 0, role: 'assistant', agentId: current.agentId, agentName: this.store.get<Agent>(owner, 'agent', current.agentId)?.name, content: `执行失败:${current.error}`, reasoning: '', status: 'failed', error: current.error, taskId: current.id, runId: current.runId, attachments: [], tools: [], createdAt: Date.now() })
  263. this.saveWork(owner, current)
  264. }
  265. } finally {
  266. this.executing.delete(work.id)
  267. if (!this.closing) {
  268. const current = this.getWork(owner, work.id)
  269. if (current.status === 'uncertain') {
  270. const attempt = this.attempts.get(work.id) ?? 0
  271. this.attempts.set(work.id, attempt + 1)
  272. this.recoverAfter.set(work.id, Date.now() + Math.min(30_000, 500 * 2 ** Math.min(attempt, 6)))
  273. this.retrySoon()
  274. } else { this.attempts.delete(work.id); this.recoverAfter.delete(work.id) }
  275. this.wake()
  276. }
  277. }
  278. }
  279. async reconcile(owner: string, id: string): Promise<void> {
  280. this.store.require<Run>(owner, 'run', id)
  281. for (const w of this.works(owner, id)) this.recoverAfter.delete(w.id)
  282. this.wake()
  283. }
  284. async stop(owner: string, id: string): Promise<void> {
  285. const root = this.store.require<Run>(owner, 'run', id)
  286. if (terminal(root.status)) return
  287. root.stopRequested = true
  288. this.store.saveRun(owner, root)
  289. await this.cancelWorks(owner, this.works(owner, id))
  290. }
  291. async stopAgent(owner: string, conversationId: string, agentId: string): Promise<void> {
  292. const c = this.store.require<Conversation>(owner, 'conversation', conversationId)
  293. if (!c.memberIds.includes(agentId)) throw new HttpError(400, '只能停止群内成员', 'invalid_members')
  294. await this.cancelWorks(owner, this.works(owner).filter(w => w.conversationId === conversationId && w.agentId === agentId))
  295. }
  296. async stopConversation(owner: string, id: string): Promise<void> {
  297. this.store.require<Conversation>(owner, 'conversation', id)
  298. const roots = this.store.list<Run>(owner, 'run').filter(r => r.conversationId === id && !terminal(r.status))
  299. this.store.atomic(() => { for (const root of roots) { root.stopRequested = true; this.store.saveRun(owner, root) } })
  300. await this.cancelWorks(owner, this.works(owner).filter(w => roots.some(r => r.id === w.runId)))
  301. }
  302. private async cancelWorks(owner: string, works: Work[]): Promise<void> {
  303. await Promise.all(works.filter(w => !terminal(w.status)).map(async w => {
  304. const current = this.getWork(owner, w.id)
  305. current.cancelRequested = true
  306. if (current.status === 'queued') { current.status = 'interrupted'; this.saveWork(owner, current) }
  307. else {
  308. this.saveWork(owner, current)
  309. try { await this.interruptTurn(owner, current) }
  310. catch (error) {
  311. const latest = this.getWork(owner, current.id)
  312. if (terminal(latest.status)) return
  313. latest.status = 'uncertain'; latest.error = `停止状态待确认:${error instanceof Error ? error.message : '连接中断'}`
  314. this.saveWork(owner, latest); this.recoverAfter.delete(latest.id); this.retrySoon()
  315. }
  316. }
  317. }))
  318. this.wake()
  319. }
  320. protected closeScheduler(): void {
  321. this.closing = true
  322. if (this.retryTimer) clearTimeout(this.retryTimer)
  323. this.recoverAfter.clear()
  324. this.attempts.clear()
  325. }
  326. }