groups.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import type {
  2. GroupAgent, GroupCapabilities, GroupInteraction, GroupMessagePage, GroupNode, GroupRoomDetail, GroupRoomPage, GroupRun, GroupTopicPage, GroupTopicSummary, JsonValue, UploadReference,
  3. } from '@shared/types'
  4. import { apiRequest, apiUrl, unwrapData } from './client'
  5. import {
  6. normalizeGroupAgent, normalizeGroupCapabilities, normalizeGroupInteraction, normalizeGroupMessage,
  7. normalizeGroupRoom, normalizeGroupRoomDetail, normalizeGroupRun, normalizeGroupTopic, record, values,
  8. } from '@/utils/normalize'
  9. import { createUuid } from '@/utils/id'
  10. const BASE = '/api/app/groups'
  11. function requestId(): string { return createUuid() }
  12. export async function getGroupCapabilities(): Promise<GroupCapabilities> {
  13. return normalizeGroupCapabilities(unwrapData(await apiRequest<unknown>(`${BASE}/capabilities`)))
  14. }
  15. export async function getGroupNodes(): Promise<GroupNode[]> {
  16. const payload = record(unwrapData(await apiRequest<unknown>(`${BASE}/nodes`)))
  17. return values(payload.items ?? payload.nodes).flatMap(value => {
  18. const node = record(value)
  19. const nodeId = String(node.nodeId ?? node.node_id ?? '')
  20. if (!nodeId) return []
  21. return [{
  22. nodeId,
  23. name: String(node.name ?? nodeId),
  24. serverUrl: String(node.serverUrl ?? node.server_url ?? ''),
  25. fingerprint: String(node.fingerprint ?? ''),
  26. createdAt: Number(node.createdAt ?? node.created_at ?? 0),
  27. updatedAt: Number(node.updatedAt ?? node.updated_at ?? 0),
  28. profiles: values(node.profiles).flatMap(profileValue => {
  29. const profile = record(profileValue)
  30. const name = String(profile.name ?? '')
  31. return name ? [{
  32. name,
  33. displayName: String(profile.displayName ?? profile.display_name ?? name),
  34. model: String(profile.model ?? ''),
  35. avatar: typeof profile.avatar === 'string' ? profile.avatar : undefined,
  36. color: typeof profile.color === 'string' ? profile.color : undefined,
  37. }] : []
  38. }),
  39. }]
  40. })
  41. }
  42. export async function refreshGroupNodeIdentities(): Promise<void> {
  43. await apiRequest(`${BASE}/nodes/refresh-identities`, {
  44. method: 'POST', body: {},
  45. })
  46. }
  47. export async function getGroupRooms(cursor?: string, limit = 50, archived = false): Promise<GroupRoomPage> {
  48. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`${BASE}/rooms`, { cursor, limit: Math.max(1, Math.min(100, limit)), archived })))
  49. const source = record(payload)
  50. return {
  51. items: values(source.items ?? source.rooms ?? payload).map(normalizeGroupRoom).filter(room => room.id),
  52. nextCursor: typeof source.nextCursor === 'string' ? source.nextCursor : typeof source.next_cursor === 'string' ? source.next_cursor : null,
  53. }
  54. }
  55. export async function getGroupRoom(roomId: string): Promise<GroupRoomDetail> {
  56. return normalizeGroupRoomDetail(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}`)))
  57. }
  58. export async function getGroupTopics(roomId: string, cursor?: string, limit = 50, archived = false): Promise<GroupTopicPage> {
  59. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`${BASE}/rooms/${encodeURIComponent(roomId)}/topics`, {
  60. cursor, limit: Math.max(1, Math.min(100, limit)), archived,
  61. })))
  62. const source = record(payload)
  63. return {
  64. items: values(source.items ?? source.topics ?? payload).map(normalizeGroupTopic).filter(topic => topic.id && topic.roomId),
  65. nextCursor: typeof source.nextCursor === 'string' ? source.nextCursor : typeof source.next_cursor === 'string' ? source.next_cursor : null,
  66. }
  67. }
  68. export async function getPinnedGroupTopics(limit = 100): Promise<GroupTopicPage> {
  69. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`${BASE}/topics/pinned`, { limit: Math.max(1, Math.min(100, limit)) })))
  70. const source = record(payload)
  71. return { items: values(source.items ?? source.topics ?? payload).map(normalizeGroupTopic).filter(topic => topic.id && topic.roomId), nextCursor: null }
  72. }
  73. export async function getGlobalGroupTopics(cursor?: string, limit = 50): Promise<GroupTopicPage> {
  74. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`${BASE}/topics`, {
  75. cursor, limit: Math.max(1, Math.min(100, limit)),
  76. })))
  77. const source = record(payload)
  78. return {
  79. items: values(source.items ?? source.topics ?? payload).map(normalizeGroupTopic).filter(topic => topic.id && topic.roomId),
  80. nextCursor: typeof source.nextCursor === 'string' ? source.nextCursor : typeof source.next_cursor === 'string' ? source.next_cursor : null,
  81. }
  82. }
  83. export async function updateGroupTopic(roomId: string, topicId: string, input: { title?: string; pinned?: boolean }): Promise<GroupTopicSummary> {
  84. return normalizeGroupTopic(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/topics/${encodeURIComponent(topicId)}`, {
  85. method: 'PATCH', body: { requestId: requestId(), ...input } as JsonValue,
  86. })))
  87. }
  88. export async function archiveGroupTopic(roomId: string, topicId: string): Promise<GroupTopicSummary> {
  89. return normalizeGroupTopic(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/topics/${encodeURIComponent(topicId)}`, {
  90. method: 'DELETE', body: { requestId: requestId() } as JsonValue,
  91. })))
  92. }
  93. export async function restoreGroupTopic(roomId: string, topicId: string): Promise<GroupTopicSummary> {
  94. return normalizeGroupTopic(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/topics/${encodeURIComponent(topicId)}/restore`, {
  95. method: 'POST', body: { requestId: requestId() } as JsonValue,
  96. })))
  97. }
  98. export async function markGroupTopicRead(roomId: string, topicId: string, throughSeq: number): Promise<void> {
  99. await apiRequest(`${BASE}/rooms/${encodeURIComponent(roomId)}/topics/${encodeURIComponent(topicId)}/read`, {
  100. method: 'PATCH', body: { requestId: requestId(), throughSeq } as JsonValue,
  101. })
  102. }
  103. export interface AgentSeed {
  104. profile: string
  105. nodeId?: string
  106. nodeLabel?: string
  107. displayName: string
  108. description?: string
  109. replyWithoutMention?: boolean
  110. isHost?: boolean
  111. model?: string | null
  112. provider?: string | null
  113. reasoningEffort?: string | null
  114. fastMode?: boolean | null
  115. }
  116. export async function createGroupRoom(input: { name: string; cwd?: string; instructions?: string; avatar?: string; agents: AgentSeed[]; maxReplyRounds?: number; orchestrationMode?: 'free' | 'host' }): Promise<GroupRoomDetail> {
  117. return normalizeGroupRoomDetail(unwrapData(await apiRequest<unknown>(`${BASE}/rooms`, {
  118. method: 'POST', body: { requestId: requestId(), cwd: '', maxReplyRounds: 3, ...input } as unknown as JsonValue,
  119. })))
  120. }
  121. export async function updateGroupRoom(roomId: string, input: { name?: string; cwd?: string; instructions?: string; avatar?: string; maxReplyRounds?: number; orchestrationMode?: 'free' | 'host' }): Promise<GroupRoomDetail> {
  122. return normalizeGroupRoomDetail(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}`, {
  123. method: 'PATCH', body: { requestId: requestId(), ...input } as JsonValue,
  124. })))
  125. }
  126. export async function archiveGroupRoom(roomId: string): Promise<GroupRoomDetail> {
  127. return normalizeGroupRoomDetail(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}`, {
  128. method: 'DELETE', body: { requestId: requestId() },
  129. })))
  130. }
  131. export async function restoreGroupRoom(roomId: string): Promise<GroupRoomDetail> {
  132. return normalizeGroupRoomDetail(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/restore`, {
  133. method: 'POST', body: { requestId: requestId() } as JsonValue,
  134. })))
  135. }
  136. export async function addGroupAgent(roomId: string, input: AgentSeed): Promise<GroupAgent> {
  137. return normalizeGroupAgent(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/agents`, {
  138. method: 'POST', body: { requestId: requestId(), description: '', replyWithoutMention: false, ...input } as JsonValue,
  139. })))
  140. }
  141. export async function updateGroupAgent(roomId: string, agentId: string, input: Partial<Omit<AgentSeed, 'profile'>> & { enabled?: boolean }): Promise<GroupAgent> {
  142. return normalizeGroupAgent(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/agents/${encodeURIComponent(agentId)}`, {
  143. method: 'PATCH', body: { requestId: requestId(), ...input } as JsonValue,
  144. })))
  145. }
  146. export async function removeGroupAgent(roomId: string, agentId: string): Promise<GroupAgent> {
  147. return normalizeGroupAgent(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/agents/${encodeURIComponent(agentId)}`, {
  148. method: 'DELETE', body: { requestId: requestId() },
  149. })))
  150. }
  151. export async function interruptGroupAgent(roomId: string, agentId: string): Promise<unknown> {
  152. return unwrapData(await apiRequest(`${BASE}/rooms/${encodeURIComponent(roomId)}/agents/${encodeURIComponent(agentId)}/interrupt`, {
  153. method: 'POST', body: { requestId: requestId() },
  154. }))
  155. }
  156. export async function getGroupMessages(roomId: string, options: { topicId?: string; beforeSeq?: number; afterSeq?: number; limit?: number } = {}): Promise<GroupMessagePage> {
  157. if (options.beforeSeq && options.afterSeq) throw new Error('beforeSeq 与 afterSeq 不能同时使用')
  158. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`${BASE}/rooms/${encodeURIComponent(roomId)}/messages`, {
  159. topicId: options.topicId, beforeSeq: options.beforeSeq, afterSeq: options.afterSeq, limit: Math.max(1, Math.min(100, options.limit ?? 100)),
  160. })))
  161. const source = record(payload)
  162. return { items: values(source.items ?? source.messages ?? payload).map(normalizeGroupMessage).filter(message => message.id) }
  163. }
  164. export async function sendGroupMessage(
  165. roomId: string,
  166. content: string,
  167. mentionAgentIds: string[],
  168. clientMessageId: string,
  169. topicId?: string,
  170. uploadIds: string[] = [],
  171. stableRequestId = requestId(),
  172. ): Promise<{ message: ReturnType<typeof normalizeGroupMessage>; runs: GroupRun[] }> {
  173. const payload = record(unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/messages`, {
  174. method: 'POST', body: { requestId: stableRequestId, clientMessageId, topicId, content, mentionAgentIds, uploadIds } as JsonValue,
  175. })))
  176. return { message: normalizeGroupMessage(payload.message), runs: values(payload.runs).map(normalizeGroupRun).filter(run => run.id) }
  177. }
  178. export async function approveGroupInteraction(roomId: string, interactionId: string, choice: 'once' | 'session' | 'always' | 'deny'): Promise<GroupInteraction | unknown> {
  179. const payload = unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/interactions/${encodeURIComponent(interactionId)}/approval`, {
  180. method: 'POST', body: { requestId: requestId(), choice, permanent: choice === 'always' },
  181. }))
  182. const source = record(payload)
  183. return source.interaction ? normalizeGroupInteraction(source.interaction) : payload
  184. }
  185. export async function clarifyGroupInteraction(roomId: string, interactionId: string, response: string): Promise<GroupInteraction | unknown> {
  186. const payload = unwrapData(await apiRequest<unknown>(`${BASE}/rooms/${encodeURIComponent(roomId)}/interactions/${encodeURIComponent(interactionId)}/clarification`, {
  187. method: 'POST', body: { requestId: requestId(), response },
  188. }))
  189. const source = record(payload)
  190. return source.interaction ? normalizeGroupInteraction(source.interaction) : payload
  191. }
  192. export async function uploadGroupFiles(roomId: string, files: File[]): Promise<UploadReference[]> {
  193. const form = new FormData()
  194. form.set('roomId', roomId)
  195. for (const file of files) form.append('files', file, file.name)
  196. const payload = unwrapData(await apiRequest<unknown>('/api/app/group-uploads', {
  197. method: 'POST', body: form, timeoutMs: 120_000,
  198. }))
  199. const source = record(payload)
  200. return values(source.files ?? source.items ?? source.uploads ?? payload).map(value => {
  201. const item = record(value)
  202. return {
  203. id: String(item.id ?? ''), name: String(item.name ?? item.filename ?? ''),
  204. mimeType: String(item.mimeType ?? item.mime_type ?? 'application/octet-stream'),
  205. size: Number(item.size ?? 0), markdown: typeof item.markdown === 'string' ? item.markdown : undefined,
  206. refText: typeof item.refText === 'string' ? item.refText : typeof item.ref_text === 'string' ? item.ref_text : undefined,
  207. }
  208. }).filter(item => item.id && item.name)
  209. }