workspaceStore.ts 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. import { chmodSync, mkdirSync } from 'node:fs'
  2. import { join } from 'node:path'
  3. import { createHash, randomUUID } from 'node:crypto'
  4. import { DatabaseSync } from 'node:sqlite'
  5. import { EventEmitter } from 'node:events'
  6. import { messageAppendPatch } from '../shared/workspaceMessagePatch.js'
  7. import { z } from 'zod'
  8. import { HttpError } from './errors.js'
  9. import { isVisibleMessageFile } from '../shared/messageFiles.js'
  10. import type { StoredWorkspaceFile } from './workspaceAssets.js'
  11. import { notificationPlainText } from './notificationText.js'
  12. import {supportsHostEnvironment} from '../shared/workspace.js'
  13. import type { WorkspaceLifecycleAction, WorkspaceLifecyclePreview } from '../shared/workspaceLifecycle.js'
  14. import { decodeAgentMascotAvatar, isAgentImageAvatar, defaultAgentIdentity, encodeAgentAvatar, normalizeAvatar, randomAgentIdentity, MAX_AVATAR_DESCRIPTOR_LENGTH } from '../shared/agentIdentity.js'
  15. import type {
  16. WorkspaceAgent as Agent,
  17. WorkspaceConversation as Conversation,
  18. WorkspaceTask as Task,
  19. WorkspaceMessage as Message,
  20. WorkspaceRun as Run,
  21. WorkspaceEvent,
  22. } from '../shared/workspace.js'
  23. const name = z
  24. .string()
  25. .trim()
  26. .min(1)
  27. .max(100)
  28. .refine((v) => !/[\u0000-\u001f@]/.test(v), '名称不能包含 @ 或控制字符')
  29. const avatar = z
  30. .string()
  31. .max(MAX_AVATAR_DESCRIPTOR_LENGTH)
  32. .refine(
  33. (v) => !v || isAgentImageAvatar(v) || !!decodeAgentMascotAvatar(v) || /^builtin:team-animal:(fox|whale|owl|rabbit|bear)$/.test(v),
  34. '请选择有效的内置头像或 PNG、JPEG、WebP 图片',
  35. )
  36. const taskTitle = z.string().trim().min(1).max(100).refine((v) => !/[\u0000-\u001f]/.test(v), '标题不能包含控制字符')
  37. export const agentInput = z
  38. .object({
  39. name,
  40. avatar: avatar.default(''),
  41. instructions: z.string().max(24_000).default(''),
  42. execution:z.enum(['profile','computer']).default('profile'),
  43. computer:z.enum(['auto','cloud','vm','local','browser','off']).optional(),
  44. allowHostEnvironment:z.boolean().default(false),
  45. vmExecution:z.enum(['worker','profile']).optional(),
  46. browserProfile:z.enum(['persistent','temporary']).optional(),
  47. canManageTeam: z.boolean().default(false),
  48. nodeId: z.string().default('local'),
  49. profile: z.string().min(1).max(256),
  50. })
  51. .strict()
  52. export const agentPatch = z
  53. .object({
  54. name: name.optional(),
  55. avatar: avatar.optional(),
  56. instructions: z.string().max(24_000).optional(),
  57. execution:z.enum(['profile','computer']).optional(),
  58. computer:z.enum(['auto','cloud','vm','local','browser','off']).optional(),
  59. allowHostEnvironment:z.boolean().optional(),
  60. vmExecution:z.enum(['worker','profile']).optional(),
  61. browserProfile:z.enum(['persistent','temporary']).optional(),
  62. nodeId:z.string().min(1).max(256).optional(),
  63. profile:z.string().min(1).max(256).optional(),
  64. canManageTeam: z.boolean().optional(),
  65. archived: z.boolean().optional(),
  66. })
  67. .strict()
  68. const memberRoles = z.record(z.string().uuid(), z.object({
  69. name: z.string().trim().min(1).max(100),
  70. description: z.string().max(500),
  71. }).strict()).refine(value => Object.keys(value).length <= 8, '最多 8 个群内角色')
  72. export const groupInput = z
  73. .object({
  74. name,
  75. avatar: avatar.default(''),
  76. memberIds: z.array(z.string().uuid()).min(2).max(8),
  77. memberRoles: memberRoles.default({}),
  78. instructions: z.string().max(24_000).default(''),
  79. administratorId: z.string().uuid(),
  80. mode: z.enum(['host', 'free']).default('host'),
  81. autoReplyIds: z.array(z.string().uuid()).max(8).default([]),
  82. maxReplyRounds: z.union([z.literal(-1), z.number().int().min(1).max(100)]).default(3),
  83. })
  84. .strict()
  85. export const conversationPatch = z
  86. .object({
  87. name: name.optional(),
  88. avatar: avatar.optional(),
  89. instructions: z.string().max(24_000).optional(),
  90. memberIds: z.array(z.string().uuid()).min(1).max(8).optional(),
  91. memberRoles: memberRoles.optional(),
  92. administratorId: z.string().uuid().optional(),
  93. mode: z.enum(['host', 'free']).optional(),
  94. autoReplyIds: z.array(z.string().uuid()).max(8).optional(),
  95. maxReplyRounds: z.union([z.literal(-1), z.number().int().min(1).max(100)]).optional(),
  96. archived: z.boolean().optional(),
  97. pinned: z.boolean().optional(),
  98. })
  99. .strict()
  100. export const taskInput = z
  101. .object({ title: z.string().trim().max(100).refine((v) => !/[\u0000-\u001f]/.test(v), '标题不能包含控制字符').optional() })
  102. .strict()
  103. export const taskPatch = z
  104. .object({ title: taskTitle })
  105. .strict()
  106. export function parse<T>(schema: z.ZodType<T>, value: unknown): T {
  107. const parsed = schema.safeParse(value)
  108. if (!parsed.success)
  109. throw new HttpError(
  110. 400,
  111. parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '),
  112. 'invalid_workspace_request',
  113. )
  114. return parsed.data
  115. }
  116. export class WorkspaceStore {
  117. readonly messagePatchesEnabled: boolean
  118. private summaryTimers = new Map<string, ReturnType<typeof setTimeout>>()
  119. private scheduleSummary(owner: string, conversation: Conversation): void {
  120. const key = `${owner}\0${conversation.id}`
  121. if (this.summaryTimers.has(key)) return
  122. const timer = setTimeout(() => {
  123. this.summaryTimers.delete(key)
  124. try {
  125. const current = this.get<Conversation>(owner, 'conversation', conversation.id)
  126. if (!current || current.archived) return
  127. const latest = this.messages(owner, current.id, Number.MAX_SAFE_INTEGER, 1)[0]
  128. if (!latest || !latest.content.trim()) return
  129. this.atomic(() => {
  130. current.updatedAt = Date.now()
  131. current.lastMessageAt = Math.max(current.lastMessageAt ?? 0, latest.createdAt)
  132. current.preview = notificationPlainText(latest.content, { maximum: 160, fallback: '' })
  133. current.previewAgentId = latest.role === 'assistant' ? latest.agentId : undefined
  134. this.put(owner, 'conversation', current.id, current)
  135. this.event(owner, 'conversation.changed', current, current.id)
  136. })
  137. } catch { /* The message is already durable; a later update can retry its list summary. */ }
  138. }, Math.max(1, 250 - (Date.now() - conversation.updatedAt)))
  139. timer.unref(); this.summaryTimers.set(key, timer)
  140. }
  141. private wireEvents = new WeakMap<WorkspaceEvent, WorkspaceEvent>()
  142. wireEvent(event: WorkspaceEvent): WorkspaceEvent { return this.wireEvents.get(event) ?? event }
  143. hasPatchEvents(owner: string, after: number, through: number): boolean {
  144. return !!this.db.prepare("SELECT 1 FROM workspace_events WHERE owner=? AND seq>? AND seq<=? AND type='message.patch' LIMIT 1").get(owner, after, through)
  145. }
  146. prepareAgent?: (owner:string,agent:Agent)=>void
  147. private observers = new Set<(owner: string, event: WorkspaceEvent) => void>()
  148. observe(listener: (owner: string, event: WorkspaceEvent) => void): () => void {
  149. this.observers.add(listener)
  150. return () => { this.observers.delete(listener) }
  151. }
  152. private publish(owner: string, event: WorkspaceEvent): void {
  153. this.changes.emit(owner, event)
  154. for (const listener of this.observers) { try { listener(owner, event) } catch { /* Observers cannot undo a committed transaction. */ } }
  155. }
  156. readonly db: DatabaseSync
  157. readonly changes = new EventEmitter()
  158. private transactionEvents: Array<{ owner: string; event: WorkspaceEvent }> | undefined
  159. constructor(home: string, options: { messagePatches?: boolean } = {}) {
  160. this.messagePatchesEnabled = options.messagePatches ?? process.env.HERMES_YAOYAO_WORKSPACE_MESSAGE_PATCHES !== '0'
  161. mkdirSync(home, { recursive: true, mode: 0o700 })
  162. const path = join(home, 'workspace.sqlite3')
  163. this.db = new DatabaseSync(path)
  164. chmodSync(path, 0o600)
  165. this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
  166. CREATE TABLE IF NOT EXISTS workspace_entities(owner TEXT NOT NULL,kind TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(owner,kind,id));
  167. CREATE TABLE IF NOT EXISTS workspace_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,owner TEXT NOT NULL,type TEXT NOT NULL,conversation_id TEXT,data TEXT NOT NULL);
  168. CREATE INDEX IF NOT EXISTS workspace_events_owner ON workspace_events(owner,seq);
  169. CREATE TABLE IF NOT EXISTS workspace_commands(owner TEXT NOT NULL,id TEXT NOT NULL,fingerprint TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(owner,id));`)
  170. this.db.exec(`CREATE INDEX IF NOT EXISTS workspace_turn_run ON workspace_entities(owner, json_extract(data,'$.runId')) WHERE kind='turn';
  171. CREATE INDEX IF NOT EXISTS workspace_turn_status ON workspace_entities(owner, json_extract(data,'$.status'), json_extract(data,'$.planned')) WHERE kind='turn';
  172. CREATE INDEX IF NOT EXISTS workspace_turn_conversation ON workspace_entities(owner, json_extract(data,'$.conversationId')) WHERE kind='turn';
  173. CREATE INDEX IF NOT EXISTS workspace_message_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.seq')) WHERE kind='message';
  174. CREATE INDEX IF NOT EXISTS workspace_message_conversation ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.seq')) WHERE kind='message';
  175. CREATE INDEX IF NOT EXISTS workspace_message_hidden ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.conversationTaskId'), json_extract(data,'$.seq')) WHERE kind='message' AND json_extract(data,'$.visible')=0;
  176. CREATE INDEX IF NOT EXISTS workspace_task_unread ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.unread')) WHERE kind='conversation-task';
  177. CREATE INDEX IF NOT EXISTS workspace_run_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.status')) WHERE kind='run';
  178. CREATE INDEX IF NOT EXISTS workspace_turn_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.status')) WHERE kind='turn';`)
  179. this.db.exec('CREATE TABLE IF NOT EXISTS server_identity(singleton INTEGER PRIMARY KEY CHECK(singleton=1), server_id TEXT NOT NULL, name TEXT NOT NULL, revision INTEGER NOT NULL)')
  180. this.db.prepare('INSERT OR IGNORE INTO server_identity VALUES(1, ?, ?, 0)').run(randomUUID(), '')
  181. this.changes.setMaxListeners(0)
  182. this.atomic(() => {
  183. this.db.exec('CREATE TABLE IF NOT EXISTS workspace_migrations(id TEXT PRIMARY KEY)')
  184. if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get('avatar-v2')) return
  185. for (const owner of this.owners()) {
  186. for (const agent of this.list<Agent>(owner, 'agent')) {
  187. this.put(owner, 'agent', agent.id, { ...agent, avatar: normalizeAvatar(agent.avatar) })
  188. }
  189. for (const conversation of this.list<Conversation>(owner, 'conversation')) {
  190. if (conversation.kind !== 'direct') continue
  191. const agent = this.get<Agent>(owner, 'agent', conversation.memberIds[0] || '')
  192. this.put(owner, 'conversation', conversation.id, { ...conversation, avatar: agent?.avatar ?? normalizeAvatar(conversation.avatar) })
  193. }
  194. }
  195. this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run('avatar-v2')
  196. })
  197. this.atomic(() => {
  198. if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get('avatar-random-default-v1')) return
  199. for (const owner of this.owners()) {
  200. for (const agent of this.list<Agent>(owner, 'agent')) {
  201. const identity = decodeAgentMascotAvatar(agent.avatar)
  202. const isSystemDefault = identity && !identity.imageDataURL && identity.shape === 'circle'
  203. && identity.color === '#00c875' && identity.expression === 'idle' && !identity.bodyId
  204. if (!isSystemDefault) continue
  205. const avatar = encodeAgentAvatar(randomAgentIdentity(agent.id, agent.name))
  206. this.put(owner, 'agent', agent.id, { ...agent, avatar })
  207. for (const conversation of this.list<Conversation>(owner, 'conversation')) {
  208. if (conversation.kind === 'direct' && conversation.memberIds[0] === agent.id) {
  209. this.put(owner, 'conversation', conversation.id, { ...conversation, avatar })
  210. }
  211. }
  212. }
  213. }
  214. this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run('avatar-random-default-v1')
  215. })
  216. this.atomic(() => {
  217. const migration = 'conversation-task-history-v1'
  218. if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration)) return
  219. for (const owner of this.owners()) {
  220. for (const conversation of this.list<Conversation>(owner, 'conversation')) {
  221. if (conversation.kind === 'group') this.backfillConversationTask(owner, conversation)
  222. }
  223. }
  224. this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration)
  225. })
  226. this.atomic(() => {
  227. const migration = 'workspace-unread-flag-v1'
  228. if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration)) return
  229. for (const owner of this.owners()) {
  230. for (const task of this.list<Task>(owner, 'conversation-task')) {
  231. task.unread ??= task.unreadCount > 0
  232. task.unreadVersion ??= task.unread ? 1 : 0
  233. task.unreadCount = task.unread ? 1 : 0
  234. this.put(owner, 'conversation-task', task.id, task)
  235. }
  236. for (const conversation of this.list<Conversation>(owner, 'conversation')) {
  237. conversation.unread ??= conversation.kind === 'group'
  238. ? this.hasUnreadTask(owner, conversation.id)
  239. : !!this.db.prepare("SELECT 1 FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.seq')>? AND coalesce(json_extract(data,'$.visible'),1)!=0 LIMIT 1").get(owner, conversation.id, conversation.readSeq)
  240. conversation.unreadVersion ??= conversation.unread ? 1 : 0
  241. conversation.unreadCount = conversation.unread ? 1 : 0
  242. this.put(owner, 'conversation', conversation.id, conversation)
  243. }
  244. }
  245. this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration)
  246. })
  247. this.atomic(() => {
  248. const migration='host-environment-option-v1'
  249. if(this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration))return
  250. for(const row of this.db.prepare("SELECT owner,id,data FROM workspace_entities WHERE kind='agent' AND json_extract(data,'$.computer')='hybrid'").all()){
  251. const agent=JSON.parse(String(row.data))
  252. this.put(String(row.owner),'agent',String(row.id),{...agent,computer:'vm',execution:'computer',allowHostEnvironment:!agent.temporaryGoalId&&!agent.remoteAgentId,revision:(agent.revision??0)+1})
  253. }
  254. this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration)
  255. })
  256. }
  257. private hasUnreadTask(owner: string, conversationId: string): boolean {
  258. return !!this.db.prepare("SELECT 1 FROM workspace_entities WHERE owner=? AND kind='conversation-task' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.unread')=1 LIMIT 1").get(owner, conversationId)
  259. }
  260. get<T>(owner: string, kind: string, id: string): T | undefined {
  261. const row = this.db
  262. .prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
  263. .get(owner, kind, id)
  264. return row ? (JSON.parse(String(row.data)) as T) : undefined
  265. }
  266. require<T>(owner: string, kind: string, id: string): T {
  267. const value = this.get<T>(owner, kind, id)
  268. if (!value) throw new HttpError(404, '记录不存在', 'workspace_not_found')
  269. return value
  270. }
  271. list<T>(owner: string, kind: string): T[] {
  272. return this.db
  273. .prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=?')
  274. .all(owner, kind)
  275. .map((r) => JSON.parse(String(r.data)) as T)
  276. }
  277. owners(): string[] {
  278. return this.db
  279. .prepare('SELECT DISTINCT owner FROM workspace_entities')
  280. .all()
  281. .map((r) => String(r.owner))
  282. }
  283. put(owner: string, kind: string, id: string, value: unknown): void {
  284. this.db
  285. .prepare(
  286. 'INSERT INTO workspace_entities VALUES(?,?,?,?) ON CONFLICT(owner,kind,id) DO UPDATE SET data=excluded.data',
  287. )
  288. .run(owner, kind, id, JSON.stringify(value))
  289. }
  290. remove(owner: string, kind: string, id: string): void {
  291. this.db
  292. .prepare('DELETE FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
  293. .run(owner, kind, id)
  294. }
  295. atomic<T>(fn: () => T): T {
  296. if (this.transactionEvents) return fn()
  297. this.db.exec('BEGIN IMMEDIATE')
  298. this.transactionEvents = []
  299. try {
  300. const result = fn()
  301. this.db.exec('COMMIT')
  302. const events = this.transactionEvents
  303. this.transactionEvents = undefined
  304. for (const entry of events) this.publish(entry.owner, entry.event)
  305. return result
  306. } catch (error) {
  307. this.db.exec('ROLLBACK')
  308. this.transactionEvents = undefined
  309. throw error
  310. }
  311. }
  312. event(owner: string, type: string, data: unknown, conversationId?: string, projection?: { type: string; data: unknown }): number {
  313. const seq = Number(
  314. this.db
  315. .prepare('INSERT INTO workspace_events(owner,type,conversation_id,data) VALUES(?,?,?,?)')
  316. .run(owner, type, conversationId ?? null, JSON.stringify(data)).lastInsertRowid,
  317. )
  318. const wire = { seq, type, conversationId, data: this.eventDataForDisplay(owner, type, data) }
  319. const event = projection ? { seq, conversationId, type: projection.type, data: this.eventDataForDisplay(owner, projection.type, projection.data) } : wire
  320. if (projection) this.wireEvents.set(event, wire)
  321. if (this.transactionEvents) this.transactionEvents.push({ owner, event })
  322. else this.publish(owner, event)
  323. return seq
  324. }
  325. events(owner: string, after: number): WorkspaceEvent[] {
  326. return this.db
  327. .prepare('SELECT * FROM workspace_events WHERE owner=? AND seq>? ORDER BY seq LIMIT 250')
  328. .all(owner, after)
  329. .map((r) => ({
  330. seq: Number(r.seq),
  331. type: String(r.type),
  332. conversationId: r.conversation_id ? String(r.conversation_id) : undefined,
  333. data: this.eventDataForDisplay(owner, String(r.type), JSON.parse(String(r.data))),
  334. }))
  335. }
  336. cursor(owner: string): number {
  337. return Number(
  338. this.db
  339. .prepare('SELECT coalesce(max(seq),0) AS n FROM workspace_events WHERE owner=?')
  340. .get(owner)!.n,
  341. )
  342. }
  343. command<T>(owner: string, id: string, payload: unknown, fn: () => T): T {
  344. parse(z.string().uuid(), id)
  345. const fingerprint = createHash('sha256').update(JSON.stringify(payload)).digest('hex')
  346. return this.atomic(() => {
  347. const old = this.db
  348. .prepare('SELECT fingerprint,result FROM workspace_commands WHERE owner=? AND id=?')
  349. .get(owner, id)
  350. if (old) {
  351. if (old.fingerprint !== fingerprint)
  352. throw new HttpError(409, '请求编号已用于其他内容', 'idempotency_conflict')
  353. return JSON.parse(String(old.result)) as T
  354. }
  355. const result = fn()
  356. this.db
  357. .prepare('INSERT INTO workspace_commands VALUES(?,?,?,?)')
  358. .run(owner, id, fingerprint, JSON.stringify(result))
  359. return result
  360. })
  361. }
  362. taskMemberIds(owner:string,conversation:Conversation,taskId?:string):string[]{
  363. const base=conversation.memberIds.filter(id=>!this.get<Agent>(owner,'agent',id)?.temporaryGoalId)
  364. if(!taskId)return base
  365. const goal=this.get<import('../shared/agentTasks.js').AgentGoal>(owner,'goal',taskId)
  366. if(!goal||goal.conversationId!==conversation.id||['complete','blocked','cancelled','cancelling'].includes(goal.status))return base
  367. return [...new Set([...base,...this.list<Agent>(owner,'agent').filter(agent=>!agent.archived&&agent.temporaryGoalId===taskId&&agent.helperActivation===(goal.activation??1)).map(agent=>agent.id)])]
  368. }
  369. requireAgentTask(owner:string,agent:Agent,conversationId:string,taskId?:string):void {
  370. if(!agent.temporaryGoalId)return
  371. const conversation=this.require<Conversation>(owner,'conversation',conversationId)
  372. if(agent.temporaryGoalId!==taskId||!this.taskMemberIds(owner,conversation,taskId).includes(agent.id))throw new HttpError(403,'临时助手只能执行所属任务','helper_task_bound')
  373. }
  374. createAgent(owner: string, input: unknown, origin?: { createdByAgentId: string; createdFromRunId: string;temporaryGoalId?:string;helperActivation?:number;helperRunnerId?:string }): Agent {
  375. const body = parse(agentInput, input)
  376. if(!supportsHostEnvironment(body)||origin)body.allowHostEnvironment=false
  377. if(body.computer!=='vm'||origin)body.vmExecution='worker'
  378. if(body.vmExecution==='profile')body.allowHostEnvironment=true
  379. if (origin) this.require<Agent>(owner, 'agent', origin.createdByAgentId)
  380. return this.atomic(() => {
  381. if (
  382. this.list<Agent>(owner, 'agent').some(
  383. (a) => a.name.toLocaleLowerCase() === body.name.toLocaleLowerCase(),
  384. )
  385. )
  386. throw new HttpError(409, '机器人名称已存在', 'duplicate_agent_name')
  387. const now = Date.now(),
  388. id = randomUUID()
  389. const agent: Agent = {
  390. ...body,
  391. ...origin,
  392. avatar: body.avatar ? normalizeAvatar(body.avatar) : encodeAgentAvatar(randomAgentIdentity(id, body.name)),
  393. id,
  394. archived: false,
  395. revision: 1,
  396. teamAuthorizationVersion: body.canManageTeam ? 1 : 0,
  397. createdAt: now,
  398. updatedAt: now,
  399. }
  400. this.prepareAgent?.(owner,agent)
  401. this.put(owner, 'agent', id, agent)
  402. if(origin?.temporaryGoalId){this.event(owner,'agent.changed',agent);return agent}
  403. const conversation: Conversation = {
  404. id: randomUUID(),
  405. kind: 'direct',
  406. name: agent.name,
  407. avatar: agent.avatar,
  408. memberIds: [id],
  409. instructions: '',
  410. administratorId: id,
  411. mode: 'host',
  412. autoReplyIds: [],
  413. maxReplyRounds: 1,
  414. archived: false,
  415. pinned: false,
  416. readSeq: 0,
  417. unread: false,
  418. unreadVersion: 0,
  419. lastSeq: 0,
  420. preview: '',
  421. createdAt: now,
  422. updatedAt: now,
  423. }
  424. this.put(owner, 'conversation', conversation.id, conversation)
  425. this.event(owner, 'agent.changed', agent)
  426. this.event(owner, 'conversation.changed', conversation, conversation.id)
  427. return agent
  428. })
  429. }
  430. updateAgent(owner: string, id: string, input: unknown): Agent {
  431. const patch = parse(agentPatch, input)
  432. if (patch.avatar !== undefined) patch.avatar = normalizeAvatar(patch.avatar)
  433. return this.atomic(() => {
  434. const agent = this.require<Agent>(owner, 'agent', id)
  435. if(patch.vmExecution==='profile'&&patch.allowHostEnvironment===false)throw new HttpError(400,'本机协作模式需要本机环境,请选择虚拟机模式','computer_profile_host_required')
  436. if(agent.vmExecution==='profile'){
  437. if(patch.allowHostEnvironment===false&&patch.vmExecution===undefined)patch.vmExecution='worker'
  438. if(patch.vmExecution==='worker'&&patch.allowHostEnvironment===undefined)patch.allowHostEnvironment=false
  439. }
  440. if((patch.computer??agent.computer)!=='vm'&&(patch.vmExecution!==undefined||agent.vmExecution==='profile'))patch.vmExecution='worker'
  441. if((patch.vmExecution??agent.vmExecution)==='profile'&&(patch.computer??agent.computer)==='vm')patch.allowHostEnvironment=true
  442. if(!supportsHostEnvironment({...agent,...patch})&&(agent.allowHostEnvironment===true||patch.allowHostEnvironment!==undefined))patch.allowHostEnvironment=false
  443. const sourceChanged=(patch.nodeId!==undefined&&patch.nodeId!==agent.nodeId)||(patch.profile!==undefined&&patch.profile!==agent.profile)
  444. const hostPermissionChanged=patch.allowHostEnvironment!==undefined&&patch.allowHostEnvironment!==(agent.allowHostEnvironment===true)
  445. const destinationChanged=hostPermissionChanged||(patch.vmExecution!==undefined&&patch.vmExecution!==(agent.vmExecution??'worker'))||(patch.computer!==undefined&&patch.computer!==agent.computer)||(patch.browserProfile!==undefined&&patch.browserProfile!==(agent.browserProfile??'persistent'))
  446. if(sourceChanged||destinationChanged){
  447. if(this.list<{agentId:string;status:string}>(owner,'turn').some(work=>work.agentId===id&&['queued','running','waiting','uncertain','cancelling'].includes(work.status)))throw new HttpError(409,'请先停止当前任务,再修改机器人来源或电脑','agent_execution_busy')
  448. if(this.list<{owner:string;agentId:string;environmentId?:string;expiresAt:number}>('_system','computer-control').some(grant=>grant.owner===owner&&grant.expiresAt>Date.now()&&(grant.agentId===id||grant.environmentId===(agent.computerEnvironmentId??id))))throw new HttpError(409,'请先交还电脑控制权','agent_execution_busy')
  449. if(sourceChanged&&agent.computerEnvironmentId){const shared=this.require<{nodeId:string;profile:string;managedLocalVm?:boolean;managedCompose?:boolean}>(owner,'shared-computer',agent.computerEnvironmentId);if((patch.nodeId??agent.nodeId)!==shared.nodeId||(!shared.managedLocalVm&&!shared.managedCompose&&shared.profile!=='*'&&(patch.profile??agent.profile)!==shared.profile))throw new HttpError(409,'请先解除电脑共享,再切换到其他来源','shared_computer_active')}
  450. }
  451. if(agent.temporaryGoalId&&(Object.keys(patch).some(key=>key!=='archived')||patch.archived===false))throw new HttpError(409,'临时助手由所属任务管理,不能修改权限或恢复为持久成员','helper_task_bound')
  452. if(agent.computerEnvironmentId&&patch.execution==='profile')throw new HttpError(409,'请先解除电脑共享,再切换执行环境','shared_computer_active')
  453. if(patch.execution&&patch.execution!==(agent.execution??'profile')&&this.list<{agentId:string;status:string}>(owner,'turn').some(work=>work.agentId===id&&['running','waiting','uncertain'].includes(work.status)))throw new HttpError(409,'请先停止当前任务,再切换执行环境','agent_execution_busy')
  454. if (agent.remoteAgentId && Object.keys(patch).some(key => key !== 'archived'))
  455. throw new HttpError(409, '引用机器人的配置由远端管理', 'remote_agent_read_only')
  456. if (
  457. patch.name &&
  458. this.list<Agent>(owner, 'agent').some(
  459. (a) => a.id !== id && a.name.toLocaleLowerCase() === patch.name!.toLocaleLowerCase(),
  460. )
  461. )
  462. throw new HttpError(409, '机器人名称已存在', 'duplicate_agent_name')
  463. const next = { ...agent, ...patch, revision: agent.revision + 1, updatedAt: Date.now() }
  464. if (patch.canManageTeam !== undefined && patch.canManageTeam !== (agent.canManageTeam === true))
  465. next.teamAuthorizationVersion = (agent.teamAuthorizationVersion ?? 0) + 1
  466. this.put(owner, 'agent', id, next)
  467. if(sourceChanged)for(const binding of this.list<{id:string}>(owner,'binding').filter(binding=>binding.id.endsWith(`:${id}`))){this.put(owner,'binding-reset',binding.id,{id:binding.id});this.remove(owner,'binding',binding.id)}
  468. this.event(owner, 'agent.changed', next)
  469. for (const c of this.list<Conversation>(owner, 'conversation').filter(
  470. (c) => c.kind === 'direct' && c.memberIds[0] === id,
  471. )) {
  472. Object.assign(c, { name: next.name, avatar: next.avatar, archived: next.archived })
  473. this.put(owner, 'conversation', c.id, c)
  474. this.event(owner, 'conversation.changed', c, c.id)
  475. }
  476. return next
  477. })
  478. }
  479. conversationLifecycle(owner: string, id: string): WorkspaceLifecyclePreview {
  480. const conversation = this.require<Conversation>(owner, 'conversation', id)
  481. const agent = conversation.kind === 'direct' ? this.require<Agent>(owner, 'agent', conversation.memberIds[0]!) : undefined
  482. const groups = agent ? this.list<Conversation>(owner, 'conversation')
  483. .filter(group => group.kind === 'group' && group.memberIds.includes(agent.id))
  484. .sort((a, b) => a.id.localeCompare(b.id)) : []
  485. return {
  486. name: conversation.name,
  487. kind: conversation.kind,
  488. groups: groups.map(group => ({ id: group.id, name: group.name, administrator: group.administratorId === agent?.id })),
  489. confirmationToken: createHash('sha256').update(JSON.stringify([
  490. conversation.id, conversation.name, conversation.archived, agent?.revision,
  491. groups.map(group => [group.id, group.name, group.administratorId, group.memberIds]),
  492. ])).digest('hex'),
  493. }
  494. }
  495. private requireConversationIdle(owner: string, id: string): void {
  496. if (['run', 'turn'].some(kind => this.list<{ conversationId: string; status: string }>(owner, kind).some(run => run.conversationId === id && !['complete', 'failed', 'interrupted', 'skipped'].includes(run.status))))
  497. throw new HttpError(409, '聊天仍有任务未结束,请停止任务后重试', 'conversation_running')
  498. if (this.list<{ conversationId: string; origin?: { conversationId: string }; status: string }>(owner, 'goal').some(goal =>
  499. (goal.conversationId === id || goal.origin?.conversationId === id) && !['complete', 'blocked', 'cancelled'].includes(goal.status)))
  500. throw new HttpError(409, '聊天仍有关联任务未结束,请停止任务后重试', 'conversation_running')
  501. }
  502. changeConversationLifecycle(owner: string, id: string, action: WorkspaceLifecycleAction, confirmationToken?: string): void {
  503. this.atomic(() => {
  504. const conversation = this.require<Conversation>(owner, 'conversation', id)
  505. const agent = conversation.kind === 'direct' ? this.require<Agent>(owner, 'agent', conversation.memberIds[0]!) : undefined
  506. if (action === 'restore') {
  507. if (agent) this.updateAgent(owner, agent.id, { archived: false })
  508. else this.updateConversation(owner, id, { archived: false })
  509. return
  510. }
  511. const preview = this.conversationLifecycle(owner, id)
  512. const managed = preview.groups.filter(group => group.administrator)
  513. if (managed.length) throw new HttpError(409, `此 Bot 是群聊${managed.map(group => `「${group.name}」`).join('、')}的管理者,请先转交管理权,再归档或删除`, 'agent_group_administrator')
  514. if (confirmationToken !== undefined && confirmationToken !== preview.confirmationToken)
  515. throw new HttpError(409, '聊天或群聊成员已变化,请重新确认后操作', 'lifecycle_confirmation_stale')
  516. if (preview.groups.length && !confirmationToken)
  517. throw new HttpError(409, '此 Bot 仍是群聊成员,请确认退出群聊后再归档或删除', 'agent_in_group')
  518. if (agent?.temporaryGoalId) throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound')
  519. if (agent?.computerEnvironmentId) throw new HttpError(409, '请先解除电脑共享,再归档或删除 Bot', 'shared_computer_active')
  520. if (agent && this.list<{ agentId: string; status: string }>(owner, 'turn').some(turn => turn.agentId === agent.id && !['complete', 'failed', 'interrupted', 'skipped'].includes(turn.status)))
  521. throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running')
  522. for (const conversationId of [id, ...preview.groups.map(group => group.id)]) this.requireConversationIdle(owner, conversationId)
  523. for (const group of preview.groups) {
  524. const current = this.require<Conversation>(owner, 'conversation', group.id)
  525. this.updateConversation(owner, group.id, { memberIds: current.memberIds.filter(memberId => memberId !== agent!.id) })
  526. }
  527. if (agent) {
  528. this.updateAgent(owner, agent.id, { archived: true })
  529. if (action === 'delete') this.deleteAgent(owner, agent.id)
  530. } else {
  531. this.updateConversation(owner, id, { archived: true })
  532. if (action === 'delete') this.deleteConversation(owner, id)
  533. }
  534. })
  535. }
  536. deleteAgent(owner: string, id: string): void {
  537. this.atomic(() => {
  538. const agent = this.require<Agent>(owner, 'agent', id)
  539. if (!agent.archived) throw new HttpError(409, '请先归档 Bot,再删除', 'agent_not_archived')
  540. if (agent.temporaryGoalId) throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound')
  541. if (agent.computerEnvironmentId) throw new HttpError(409, '请先解除电脑共享,再删除 Bot', 'shared_computer_active')
  542. const conversations = this.list<Conversation>(owner, 'conversation')
  543. if (conversations.some(c => c.kind === 'group' && c.memberIds.includes(id)))
  544. throw new HttpError(409, '此 Bot 仍是群聊成员,请先从群聊移除或删除相关群聊', 'agent_in_group')
  545. if (this.list<{ agentId: string; status: string }>(owner, 'turn').some(work => work.agentId === id && !['complete', 'failed', 'interrupted', 'skipped'].includes(work.status)))
  546. throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running')
  547. for (const conversation of conversations.filter(c => c.kind === 'direct' && c.memberIds[0] === id))
  548. this.deleteConversation(owner, conversation.id, true)
  549. for(const kind of ['routine','routine-run'])for(const item of this.list<{id:string;agentId:string}>(owner,kind).filter(item=>item.agentId===id))this.remove(owner,kind,item.id)
  550. this.remove(owner, 'agent', id)
  551. this.event(owner, 'agent.deleted', { id })
  552. })
  553. }
  554. deleteConversation(owner: string, id: string, deletingAgent = false): void {
  555. this.atomic(() => {
  556. const conversation = this.require<Conversation>(owner, 'conversation', id)
  557. if (conversation.kind === 'direct' && !deletingAgent)
  558. throw new HttpError(400, '请删除对应的 Bot', 'delete_agent_instead')
  559. if (!conversation.archived) throw new HttpError(409, '请先归档聊天,再删除', 'conversation_not_archived')
  560. this.requireConversationIdle(owner, id)
  561. const taskIds = new Set(this.list<Task>(owner, 'conversation-task').filter(task => task.conversationId === id).map(task => task.id))
  562. for (const taskId of taskIds) {
  563. this.remove(owner, 'context', taskId)
  564. this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind='task-delivery' AND json_extract(data,'$.goalId')=?").run(owner, taskId)
  565. }
  566. // Keep files in the file library, matching task deletion; detach their chat references.
  567. for (const file of this.list<{ id: string; conversationId?: string; conversationTaskId?: string }>(owner, 'file')) {
  568. if (file.conversationId === id || (file.conversationTaskId && taskIds.has(file.conversationTaskId)))
  569. this.put(owner, 'file', file.id, { ...file, conversationId: undefined, conversationTaskId: undefined, messageId: undefined })
  570. }
  571. const bindingPrefix = `${id}:`
  572. this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND ((kind='binding' AND substr(id,1,?)=?) OR (kind='interaction-binding' AND substr(json_extract(data,'$.key'),1,?)=?))").run(owner, bindingPrefix.length, bindingPrefix, bindingPrefix.length, bindingPrefix)
  573. this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind IN ('message','run','turn','interaction','interaction-binding','binding','conversation-task','goal','assignment') AND json_extract(data,'$.conversationId')=?").run(owner, id)
  574. this.db.prepare("DELETE FROM workspace_commands WHERE owner=? AND json_extract(result,'$.conversationId')=?").run(owner, id)
  575. this.remove(owner, 'context', id)
  576. if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workspace_inspector'").get())this.db.prepare('DELETE FROM workspace_inspector WHERE owner=? AND conversation_id=?').run(owner,id)
  577. this.remove(owner, 'conversation', id)
  578. this.event(owner, 'conversation.deleted', { id }, id)
  579. })
  580. }
  581. createGroup(owner: string, input: unknown): Conversation {
  582. const body = parse(groupInput, input)
  583. const ids = new Set(body.memberIds)
  584. if (
  585. ids.size !== body.memberIds.length ||
  586. !ids.has(body.administratorId) ||
  587. body.autoReplyIds.some((id) => !ids.has(id)) ||
  588. Object.keys(body.memberRoles).some(id => !ids.has(id))
  589. )
  590. throw new HttpError(400, '群成员或管理员无效', 'invalid_members')
  591. for (const id of ids){
  592. const agent=this.require<Agent>(owner,'agent',id)
  593. if(agent.temporaryGoalId)throw new HttpError(409,'临时助手不能加入持久团队','helper_task_bound')
  594. if(agent.archived)throw new HttpError(409,'已归档机器人不能加入新群','agent_archived')
  595. }
  596. const now = Date.now()
  597. const c: Conversation = {
  598. ...body,
  599. id: randomUUID(),
  600. kind: 'group',
  601. archived: false,
  602. pinned: false,
  603. readSeq: 0,
  604. unread: false,
  605. unreadVersion: 0,
  606. lastSeq: 0,
  607. preview: '',
  608. createdAt: now,
  609. updatedAt: now,
  610. }
  611. this.atomic(() => {
  612. this.put(owner, 'conversation', c.id, c)
  613. this.event(owner, 'conversation.changed', c, c.id)
  614. this.createTask(owner, c.id, {})
  615. })
  616. return c
  617. }
  618. private backfillConversationTask(owner: string, conversation: Conversation): void {
  619. const legacyMessages = this.list<Message>(owner, 'message')
  620. .filter(message => message.conversationId === conversation.id && !message.conversationTaskId)
  621. .sort((a, b) => a.seq - b.seq || a.createdAt - b.createdAt || a.id.localeCompare(b.id))
  622. if (!legacyMessages.length) return
  623. const existingTasks = this.tasks(owner, conversation.id)
  624. const assignedTaskIds = new Set(
  625. this.list<Message>(owner, 'message')
  626. .filter(message => message.conversationId === conversation.id && message.conversationTaskId)
  627. .map(message => message.conversationTaskId!),
  628. )
  629. const reusable = existingTasks.length === 1
  630. && existingTasks[0]!.titleSource === 'automatic'
  631. && existingTasks[0]!.title === '新任务'
  632. && existingTasks[0]!.messageCount === 0
  633. && !assignedTaskIds.has(existingTasks[0]!.id)
  634. ? existingTasks[0]
  635. : undefined
  636. const visibleMessages = legacyMessages.filter(message => message.visible !== false)
  637. const meaningfulMessages = visibleMessages.filter(
  638. message => message.content.trim() || message.attachments.length,
  639. )
  640. const firstMessage = legacyMessages[0]!,
  641. lastMessage = meaningfulMessages.at(-1) ?? visibleMessages.at(-1) ?? legacyMessages.at(-1)!,
  642. firstUserMessage = visibleMessages.find(
  643. message => message.role === 'user' && (message.content.trim() || message.attachments.length),
  644. ),
  645. title = notificationPlainText(firstUserMessage?.content ?? '', {
  646. maximum: 48,
  647. fallback: firstUserMessage?.attachments[0]?.name ?? '',
  648. }).trim()
  649. || notificationPlainText(conversation.preview, { maximum: 48, fallback: '' }).trim()
  650. || '历史任务',
  651. lastSeq = legacyMessages.reduce((value, message) => Math.max(value, message.seq), 0),
  652. readSeq = Math.min(conversation.readSeq, lastSeq),
  653. task: Task = {
  654. ...(reusable ?? {
  655. id: randomUUID(),
  656. conversationId: conversation.id,
  657. title: '历史任务',
  658. titleSource: 'automatic' as const,
  659. messageCount: 0,
  660. readSeq: 0,
  661. lastSeq: 0,
  662. unreadCount: 0,
  663. createdAt: firstMessage.createdAt,
  664. updatedAt: lastMessage.createdAt,
  665. }),
  666. title,
  667. titleSource: 'automatic',
  668. messageCount: visibleMessages.length,
  669. readSeq,
  670. lastSeq,
  671. unreadCount: visibleMessages.some(message => message.seq > readSeq) ? 1 : 0,
  672. lastMessageAt: lastMessage.createdAt,
  673. createdAt: firstMessage.createdAt,
  674. updatedAt: lastMessage.createdAt,
  675. }
  676. for (const message of legacyMessages) {
  677. this.put(owner, 'message', message.id, {
  678. ...message,
  679. conversationTaskId: task.id,
  680. })
  681. }
  682. const migratedInteractions = new Map<string, string>()
  683. for (const kind of ['run', 'turn', 'interaction'] as const) {
  684. for (const entity of this.list<Record<string, unknown> & {
  685. id: string
  686. conversationId?: string
  687. conversationTaskId?: string
  688. agentId?: string
  689. }>(owner, kind)) {
  690. if (entity.conversationId !== conversation.id || entity.conversationTaskId) continue
  691. this.put(owner, kind, entity.id, { ...entity, conversationTaskId: task.id })
  692. if (kind === 'interaction' && entity.agentId) {
  693. migratedInteractions.set(entity.id, entity.agentId)
  694. }
  695. }
  696. }
  697. for (const [interactionId, agentId] of migratedInteractions) {
  698. const binding = this.get<Record<string, unknown> & {
  699. conversationTaskId?: string
  700. }>(owner, 'interaction-binding', interactionId)
  701. if (!binding || binding.conversationTaskId) continue
  702. this.put(owner, 'interaction-binding', interactionId, {
  703. ...binding,
  704. key: `${conversation.id}:${task.id}:${agentId}`,
  705. conversationTaskId: task.id,
  706. })
  707. }
  708. for (const agentId of conversation.memberIds) {
  709. const legacyKey = `${conversation.id}:${agentId}`,
  710. taskKey = `${conversation.id}:${task.id}:${agentId}`,
  711. binding = this.get<Record<string, unknown> & {
  712. conversationTaskId?: string
  713. }>(owner, 'binding', legacyKey)
  714. if (!binding || binding.conversationTaskId) continue
  715. this.put(owner, 'binding', taskKey, { ...binding, conversationTaskId: task.id })
  716. this.remove(owner, 'binding', legacyKey)
  717. }
  718. const context = this.get<Record<string, unknown> & {
  719. conversationTaskId?: string
  720. }>(owner, 'context', conversation.id)
  721. if (context && !context.conversationTaskId) {
  722. this.put(owner, 'context', task.id, { ...context, conversationTaskId: task.id })
  723. this.remove(owner, 'context', conversation.id)
  724. }
  725. this.db.prepare(
  726. `UPDATE workspace_commands
  727. SET result=json_set(result,'$.conversationTaskId',?)
  728. WHERE owner=? AND json_extract(result,'$.conversationId')=?
  729. AND json_extract(result,'$.conversationTaskId') IS NULL`,
  730. ).run(task.id, owner, conversation.id)
  731. const activeRuns = this.list<Run>(owner, 'run')
  732. .filter(run => run.conversationTaskId === task.id && !['complete', 'failed', 'interrupted'].includes(run.status))
  733. .sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id))
  734. task.activeRunId = activeRuns[0]?.id
  735. task.activeRunStatus = activeRuns[0]?.status
  736. this.put(owner, 'conversation-task', task.id, task)
  737. }
  738. tasks(owner: string, conversationId: string): Task[] {
  739. const conversation = this.require<Conversation>(owner, 'conversation', conversationId)
  740. if (conversation.kind !== 'group')
  741. throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported')
  742. return this.list<Task>(owner, 'conversation-task')
  743. .filter((task) => task.conversationId === conversationId)
  744. .sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt || a.id.localeCompare(b.id))
  745. }
  746. createTask(owner: string, conversationId: string, input: unknown): Task {
  747. const body = parse(taskInput, input),
  748. conversation = this.require<Conversation>(owner, 'conversation', conversationId)
  749. if (conversation.kind !== 'group')
  750. throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported')
  751. const now = Date.now(),
  752. explicitTitle = body.title?.trim(),
  753. task: Task = {
  754. id: randomUUID(),
  755. conversationId,
  756. title: explicitTitle || '新任务',
  757. titleSource: explicitTitle ? 'user' : 'automatic',
  758. messageCount: 0,
  759. readSeq: 0,
  760. lastSeq: 0,
  761. unread: false,
  762. unreadVersion: 0,
  763. unreadCount: 0,
  764. createdAt: now,
  765. updatedAt: now,
  766. }
  767. this.atomic(() => {
  768. this.put(owner, 'conversation-task', task.id, task)
  769. this.event(owner, 'task.changed', task, conversationId)
  770. })
  771. return task
  772. }
  773. requireTask(owner: string, conversationId: string, taskId: string): Task {
  774. const task = this.require<Task>(owner, 'conversation-task', taskId)
  775. if (task.conversationId !== conversationId)
  776. throw new HttpError(404, '任务不存在', 'workspace_task_not_found')
  777. return task
  778. }
  779. resolveTask(owner: string, conversationId: string, taskId?: string): Task | undefined {
  780. const conversation = this.require<Conversation>(owner, 'conversation', conversationId)
  781. if (conversation.kind === 'direct') {
  782. if (taskId) throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported')
  783. return undefined
  784. }
  785. if (taskId) return this.requireTask(owner, conversationId, taskId)
  786. return this.tasks(owner, conversationId)[0] ?? this.createTask(owner, conversationId, {})
  787. }
  788. updateTask(owner: string, conversationId: string, taskId: string, input: unknown): Task {
  789. const patch = parse(taskPatch, input)
  790. return this.atomic(() => {
  791. const task = this.requireTask(owner, conversationId, taskId),
  792. next: Task = { ...task, title: patch.title, titleSource: 'user', updatedAt: Date.now() }
  793. this.put(owner, 'conversation-task', task.id, next)
  794. this.event(owner, 'task.changed', next, conversationId)
  795. return next
  796. })
  797. }
  798. markTaskRead(owner: string, conversationId: string, taskId: string, seq: number, unreadVersion?: number): Task {
  799. return this.atomic(() => {
  800. const task = this.requireTask(owner, conversationId, taskId)
  801. task.readSeq = Math.max(task.readSeq, Math.min(seq, task.lastSeq))
  802. if (unreadVersion === undefined ? seq >= task.lastSeq : unreadVersion === (task.unreadVersion ?? 0)) task.unread = false
  803. task.unreadCount = task.unread ? 1 : 0
  804. this.put(owner, 'conversation-task', task.id, task)
  805. const conversation = this.require<Conversation>(owner, 'conversation', conversationId)
  806. conversation.unread = this.hasUnreadTask(owner, conversationId)
  807. conversation.unreadCount = conversation.unread ? 1 : 0
  808. this.put(owner, 'conversation', conversationId, conversation)
  809. this.event(owner, 'task.changed', task, conversationId)
  810. this.event(owner, 'conversation.changed', conversation, conversationId)
  811. return task
  812. })
  813. }
  814. markConversationRead(owner: string, conversationId: string, seq: number, unreadVersion?: number): Conversation {
  815. return this.atomic(() => {
  816. const conversation = this.require<Conversation>(owner, 'conversation', conversationId)
  817. conversation.readSeq = Math.max(conversation.readSeq, Math.min(seq, conversation.lastSeq))
  818. if (conversation.kind === 'direct' && (unreadVersion === undefined ? seq >= conversation.lastSeq : unreadVersion === (conversation.unreadVersion ?? 0))) conversation.unread = false
  819. conversation.unreadCount = conversation.unread ? 1 : 0
  820. this.put(owner, 'conversation', conversationId, conversation)
  821. this.event(owner, 'conversation.changed', conversation, conversationId)
  822. return this.conversationSummary(owner, conversation)
  823. })
  824. }
  825. deleteTask(owner: string, conversationId: string, taskId: string): void {
  826. this.atomic(() => {
  827. const task = this.requireTask(owner, conversationId, taskId)
  828. if (this.list<Run>(owner, 'run').some(run => run.conversationTaskId === taskId && !['complete', 'failed', 'interrupted'].includes(run.status)))
  829. throw new HttpError(409, '任务仍在运行,暂时无法移除', 'workspace_task_running')
  830. const messageIds = new Set(this.list<Message>(owner, 'message').filter(message => message.conversationTaskId === taskId).map(message => message.id))
  831. this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind IN ('message','run','turn','interaction','interaction-binding','binding') AND json_extract(data,'$.conversationTaskId')=?").run(owner, taskId)
  832. this.remove(owner, 'context', taskId)
  833. this.remove(owner, 'conversation-task', taskId)
  834. this.db.prepare("DELETE FROM workspace_commands WHERE owner=? AND json_extract(result,'$.conversationTaskId')=?").run(owner, taskId)
  835. for (const file of this.list<Record<string, unknown> & { id: string; messageId?: string }>(owner, 'file')) {
  836. if (!file.messageId || !messageIds.has(file.messageId)) continue
  837. this.put(owner, 'file', String(file.id), { ...file, conversationId: undefined, messageId: undefined })
  838. }
  839. this.event(owner, 'task.deleted', { id: taskId, conversationId }, conversationId)
  840. const remaining = this.tasks(owner, conversationId)
  841. if (!remaining.length) this.createTask(owner, conversationId, {})
  842. const conversation = this.require<Conversation>(owner, 'conversation', conversationId),
  843. history = this.messages(owner, conversationId, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
  844. const last = history.at(-1)
  845. conversation.preview = last ? notificationPlainText(last.content, { maximum: 160, fallback: '' }) : ''
  846. conversation.previewAgentId = last?.role === 'assistant' ? last.agentId : undefined
  847. conversation.lastMessageAt = last?.createdAt
  848. conversation.updatedAt = Date.now()
  849. conversation.unread = this.hasUnreadTask(owner, conversationId)
  850. conversation.unreadCount = conversation.unread ? 1 : 0
  851. this.projectConversationRuns(owner, conversation)
  852. this.put(owner, 'conversation', conversationId, conversation)
  853. this.event(owner, 'conversation.changed', conversation, conversationId)
  854. })
  855. }
  856. updateConversation(owner: string, id: string, input: unknown): Conversation {
  857. const patch = parse(conversationPatch, input),
  858. c = this.require<Conversation>(owner, 'conversation', id)
  859. if (c.kind === 'direct' && Object.keys(patch).some((k) => k !== 'pinned'))
  860. throw new HttpError(400, '请编辑机器人资料', 'edit_agent_instead')
  861. const memberIds = patch.memberIds ?? c.memberIds
  862. const members = new Set(memberIds)
  863. if (!members.has(c.administratorId))
  864. throw new HttpError(400, '当前管理员不能移除,请先更换管理员并保存', 'administrator_required')
  865. if (
  866. members.size !== memberIds.length ||
  867. !members.has(patch.administratorId ?? c.administratorId) ||
  868. patch.autoReplyIds?.some((a) => !members.has(a) && !c.memberIds.includes(a)) ||
  869. Object.keys(patch.memberRoles ?? {}).some(a => !members.has(a) && !c.memberIds.includes(a))
  870. )
  871. throw new HttpError(400, '群成员或管理员无效', 'invalid_members')
  872. for (const memberId of memberIds) {
  873. const agent = this.require<Agent>(owner, 'agent', memberId)
  874. if(agent.temporaryGoalId)throw new HttpError(409,'临时助手不能加入其他群聊','helper_task_bound')
  875. if (!c.memberIds.includes(memberId) && agent.archived)
  876. throw new HttpError(409, '已归档机器人不能加入群聊', 'agent_archived')
  877. }
  878. const next = {
  879. ...c, ...patch, memberIds,
  880. autoReplyIds: (patch.autoReplyIds ?? c.autoReplyIds).filter(a => members.has(a)),
  881. memberRoles: Object.fromEntries(Object.entries(patch.memberRoles ?? c.memberRoles ?? {}).filter(([id]) => members.has(id))),
  882. updatedAt: Date.now(),
  883. }
  884. this.atomic(() => {
  885. this.put(owner, 'conversation', id, next)
  886. this.event(owner, 'conversation.changed', next, id)
  887. })
  888. return next
  889. }
  890. messages(
  891. owner: string,
  892. conversationId: string,
  893. before = Number.MAX_SAFE_INTEGER,
  894. limit = 100,
  895. includeHidden = false,
  896. conversationTaskId?: string,
  897. ): Message[] {
  898. this.require(owner, 'conversation', conversationId)
  899. if (conversationTaskId) this.requireTask(owner, conversationId, conversationTaskId)
  900. const taskClause = conversationTaskId ? "AND json_extract(data,'$.conversationTaskId')=?" : ''
  901. return this.db
  902. .prepare(
  903. `SELECT data FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? ${taskClause} AND json_extract(data,'$.seq')<? ${includeHidden ? '' : "AND coalesce(json_extract(data,'$.visible'),1) != 0"} ORDER BY json_extract(data,'$.seq') DESC LIMIT ?`,
  904. )
  905. .all(...(conversationTaskId ? [owner, conversationId, conversationTaskId, before, limit] : [owner, conversationId, before, limit]))
  906. .map((r) => this.messageForDisplay(owner, JSON.parse(String(r.data)) as Message))
  907. .reverse()
  908. }
  909. nativeMessageForFile?: (owner: string, file: StoredWorkspaceFile) => Message | undefined
  910. visibleFiles(owner: string): StoredWorkspaceFile[] {
  911. const messages = new Map(this.list<Message>(owner, 'message').map(message => [message.id, message]))
  912. return this.list<StoredWorkspaceFile>(owner, 'file').filter(file =>
  913. isVisibleMessageFile(file, messages.get(file.messageId ?? '') ?? this.nativeMessageForFile?.(owner, file)))
  914. }
  915. messageForDisplay(owner: string, message: Message): Message {
  916. const attachments = message.role === 'user' || message.role === 'assistant'
  917. ? message.attachments.filter(file => isVisibleMessageFile(
  918. this.get<StoredWorkspaceFile>(owner, 'file', file.id) ?? file, message))
  919. : []
  920. return { ...message, attachments }
  921. }
  922. private eventDataForDisplay(owner: string, type: string, data: unknown): unknown {
  923. if (type === 'message.changed') return this.messageForDisplay(owner, data as Message)
  924. return data
  925. }
  926. saveMessage(owner: string, message: Message): void {
  927. this.atomic(() => {
  928. const c = this.require<Conversation>(owner, 'conversation', message.conversationId)
  929. const previous = this.get<Message>(owner, 'message', message.id)
  930. // Do not emit revisions for gateway events which did not change the message.
  931. if (previous?.status === 'streaming' && message.status === 'streaming' && JSON.stringify({ ...previous, revision: undefined }) === JSON.stringify({ ...message, revision: undefined })) return
  932. message.revision = (previous?.revision ?? 0) + 1
  933. const patch = this.messagePatchesEnabled ? messageAppendPatch(previous, message) : undefined
  934. const updateSummary = !patch || Date.now() - c.updatedAt >= 250
  935. if (previous && previous.conversationTaskId !== message.conversationTaskId)
  936. throw new HttpError(409, '消息不能移入其他任务', 'message_task_mismatch')
  937. const task = c.kind === 'group'
  938. ? message.conversationTaskId
  939. ? this.requireTask(owner, c.id, message.conversationTaskId)
  940. : (() => { throw new HttpError(400, '群聊消息必须指定任务', 'workspace_task_required') })()
  941. : undefined
  942. if (previous?.visible === false && message.visible !== false) message.seq = 0
  943. if (!message.seq) message.seq = c.lastSeq + 1
  944. c.lastSeq = Math.max(c.lastSeq, message.seq)
  945. const needsAttention = (value: Message | undefined) => !!value && value.role !== 'user' && value.visible !== false
  946. && ['complete', 'failed', 'interrupted'].includes(value.status)
  947. && !!(value.content.trim() || value.error || this.messageForDisplay(owner, value).attachments.length)
  948. if (needsAttention(message) && !needsAttention(previous)) {
  949. c.unread = true
  950. c.unreadVersion = (c.unreadVersion ?? 0) + 1
  951. if (task) { task.unread = true; task.unreadVersion = (task.unreadVersion ?? 0) + 1 }
  952. }
  953. c.unreadCount = c.unread ? 1 : 0
  954. if (updateSummary && message.visible !== false && (message.content.trim() || message.attachments.length)) {
  955. c.updatedAt = Date.now()
  956. c.lastMessageAt = Math.max(c.lastMessageAt ?? 0, message.createdAt)
  957. c.preview = notificationPlainText(message.content, { maximum: 160, fallback: '' })
  958. c.previewAgentId = message.role === 'assistant' ? message.agentId : undefined
  959. }
  960. this.put(owner, 'message', message.id, message)
  961. if (updateSummary) this.put(owner, 'conversation', c.id, c)
  962. if (task && updateSummary) {
  963. const becameVisible = message.visible !== false && (!previous || previous.visible === false),
  964. becameHidden = Boolean(previous && previous.visible !== false && message.visible === false)
  965. if (becameVisible) task.messageCount += 1
  966. if (becameHidden) task.messageCount = Math.max(0, task.messageCount - 1)
  967. task.lastSeq = Math.max(task.lastSeq, message.seq)
  968. task.unreadCount = task.unread ? 1 : 0
  969. if (message.visible !== false && (message.content.trim() || message.attachments.length)) {
  970. if (message.role === 'user' && task.titleSource === 'automatic' && task.messageCount <= 1) {
  971. const source = notificationPlainText(message.content, { maximum: 48, fallback: message.attachments[0]?.name ?? '' }).trim()
  972. if (source) task.title = source
  973. }
  974. task.lastMessageAt = Math.max(task.lastMessageAt ?? 0, message.createdAt)
  975. task.updatedAt = Date.now()
  976. }
  977. this.put(owner, 'conversation-task', task.id, task)
  978. this.event(owner, 'task.changed', task, c.id)
  979. }
  980. if (patch) this.event(owner, 'message.patch', patch, c.id, { type: 'message.changed', data: message })
  981. else this.event(owner, 'message.changed', message, c.id)
  982. if (updateSummary) {
  983. const key = `${owner}\0${c.id}`
  984. clearTimeout(this.summaryTimers.get(key)); this.summaryTimers.delete(key)
  985. this.event(owner, 'conversation.changed', c, c.id)
  986. } else this.scheduleSummary(owner, c)
  987. })
  988. }
  989. agentSummary(agent: Agent): Agent {
  990. return { ...agent, avatar: agent.avatar || encodeAgentAvatar(defaultAgentIdentity(agent.id, agent.name)) }
  991. }
  992. conversationSummary(owner: string, conversation: Conversation): Conversation {
  993. const member = conversation.kind === 'direct' ? this.get<Agent>(owner, 'agent', conversation.memberIds[0] ?? '') : undefined
  994. return {
  995. ...conversation,
  996. unread: conversation.unread ?? false,
  997. unreadVersion: conversation.unreadVersion ?? 0,
  998. unreadCount: conversation.unread ? 1 : 0,
  999. ...(member ? { avatar: this.agentSummary(member).avatar } : {}),
  1000. lastMessageAt: conversation.lastMessageAt
  1001. ?? (conversation.lastSeq > 0 ? this.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 1).at(-1)?.createdAt : undefined)
  1002. ?? conversation.createdAt,
  1003. }
  1004. }
  1005. hiddenMessageIds(owner: string, conversationId: string, conversationTaskId?: string): string[] {
  1006. this.require(owner, 'conversation', conversationId)
  1007. if (conversationTaskId) this.requireTask(owner, conversationId, conversationTaskId)
  1008. const taskClause = conversationTaskId ? "AND json_extract(data,'$.conversationTaskId')=?" : ''
  1009. return this.db.prepare(`SELECT id FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.visible')=0 ${taskClause} ORDER BY json_extract(data,'$.seq') ASC`)
  1010. .all(...(conversationTaskId ? [owner, conversationId, conversationTaskId] : [owner, conversationId])).map(row => String(row.id))
  1011. }
  1012. saveRun(owner: string, run: Run): void {
  1013. this.atomic(() => {
  1014. const c = this.require<Conversation>(owner, 'conversation', run.conversationId)
  1015. run.updatedAt = Date.now()
  1016. this.put(owner, 'run', run.id, run)
  1017. if (run.conversationTaskId) {
  1018. const task = this.requireTask(owner, c.id, run.conversationTaskId),
  1019. activeRuns = this.list<Run>(owner, 'run')
  1020. .filter(root => root.conversationTaskId === task.id && !['complete', 'failed', 'interrupted'].includes(root.status))
  1021. .sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id)),
  1022. active = activeRuns[0]
  1023. task.activeRunId = active?.id
  1024. task.activeRunStatus = active?.status
  1025. this.put(owner, 'conversation-task', task.id, task)
  1026. this.event(owner, 'task.changed', task, c.id)
  1027. }
  1028. this.projectConversationRuns(owner, c)
  1029. this.put(owner, 'conversation', c.id, c)
  1030. this.event(owner, 'run.changed', run, c.id)
  1031. this.event(owner, 'conversation.changed', c, c.id)
  1032. })
  1033. }
  1034. activeTaskCount(owner: string, conversationId: string): number {
  1035. return new Set(
  1036. this.list<Run>(owner, 'run')
  1037. .filter(run => run.conversationId === conversationId && run.conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status))
  1038. .map(run => run.conversationTaskId!),
  1039. ).size
  1040. }
  1041. private projectConversationRuns(owner: string, conversation: Conversation): void {
  1042. const roots = this.list<Run>(owner, 'run').filter(run => run.conversationId === conversation.id && !['complete', 'failed', 'interrupted'].includes(run.status))
  1043. .sort((a, b) => this.require<Message>(owner, 'message', a.messageId).seq - this.require<Message>(owner, 'message', b.messageId).seq),
  1044. current = roots[0]
  1045. conversation.activeRunId = current?.id
  1046. conversation.activeAgentId = current?.activeAgentId
  1047. conversation.activeRunStatus = current?.status
  1048. const turns = this.db.prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.status') IN ('running','waiting','uncertain','queued') AND (json_extract(data,'$.status') != 'queued' OR json_extract(data,'$.planned')=1) ORDER BY CASE json_extract(data,'$.status') WHEN 'queued' THEN 0 WHEN 'running' THEN 1 ELSE 2 END").all(owner, conversation.id)
  1049. .map(row => JSON.parse(String(row.data)) as { agentId: string; status: string })
  1050. conversation.activeAgentStates = Object.fromEntries(turns.map(turn => [turn.agentId, turn.status as 'running' | 'waiting' | 'uncertain' | 'queued']))
  1051. const outcomes = this.db.prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.status') IN ('complete','failed') AND json_extract(data,'$.updatedAt')>=? ORDER BY json_extract(data,'$.updatedAt') ASC").all(owner, conversation.id, Date.now() - 2000)
  1052. .map(row => JSON.parse(String(row.data)) as {id:string;agentId:string;status:string;updatedAt:number})
  1053. conversation.avatarSignals = Object.fromEntries(outcomes.filter(turn => Date.now() - turn.updatedAt < 2000).map(turn => [turn.agentId, { id:turn.id, state:turn.status === 'failed' ? 'failure' as const : 'success' as const, at:turn.updatedAt }]))
  1054. conversation.queuedMessageCount = roots.filter(run => run.status === 'queued').length
  1055. }
  1056. ownsUpstream(id: string): boolean {
  1057. return Boolean(
  1058. this.db
  1059. .prepare(
  1060. `SELECT 1 FROM workspace_entities WHERE kind='binding' AND (json_extract(data,'$.storedId')=? OR json_extract(data,'$.runtimeId')=? OR EXISTS(SELECT 1 FROM json_each(json_extract(data,'$.aliases')) WHERE value=?)) LIMIT 1`,
  1061. )
  1062. .get(id, id, id),
  1063. )
  1064. }
  1065. close(): void {
  1066. for (const timer of this.summaryTimers.values()) clearTimeout(timer)
  1067. this.summaryTimers.clear()
  1068. this.changes.emit('workspace.close')
  1069. this.changes.removeAllListeners()
  1070. this.db.close()
  1071. }
  1072. }