workspaceStore.ts 56 KB

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